title
stringlengths 13
150
| body
stringlengths 749
64.2k
| label
int64 0
3
| token_count
int64 1.02k
28.5k
|
---|---|---|---|
REACT this.props.history.push does not redirect
|
<p>I've got this search method where I want to redirect the user after searching. The issue is that it does not do anything and I don't know why. this.props.history IS defined but the "location" property of the object "history" does not seem to change accordingly to what i put in the parameters of the push method ('./connexion') ... The search method IS binded and I use <code>export default withRouter(SearchBar);</code> to access the history via props</p>
<pre><code> search(event) {
if (this.state.location === null) {
this.setState({ geosuggestId: 'geosuggest-input-alert' });
} else if (this.state.subjects.length === 0) {
this.setState({ matieresButtonId: 'matieres-button-alert' });
} else {
console.log(this.props.parent);
if (this.props.parent === 'Homepage') {
console.log(this.props.history);
this.props.history.push('/connexion');
}
}
}
</code></pre>
<p>Full file : </p>
<pre><code>import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import Geosuggest from 'react-geosuggest';
import SearchBySubjectsModal from './modals/search_by_subjects_modal';
import { withRouter } from 'react-router-dom';
/**
* Search bar for parent to search for profs
*/
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
location: null,
subjects: [],
level: 'Collège',
matieresButtonId: 'matieres-button',
geosuggestId: 'geosuggest-input'
}
this.onSuggestSelect = this.onSuggestSelect.bind(this);
this.setSubjects = this.setSubjects.bind(this);
this.search = this.search.bind(this);
}
/**
* if the state for subjects and location is not null, then stop fields warning
*/
componentDidUpdate() {
if (this.state.subjects.length > 0) {
if (this.state.matieresButtonId !== 'matieres-button')
this.setState({ matieresButtonId: 'matieres-button' });
}
if (this.state.location !== null) {
if (this.state.geosuggestId !== 'geosuggest-input')
this.setState({ geosuggestId: 'geosuggest-input' });
}
}
/**
* set the state when choosing a location
* @param {*} suggest
*/
onSuggestSelect(suggest) {
this.setState({ location: suggest });
}
/**
* set the state when choosing subjects
* @param {*} suggest
*/
setSubjects(subjects, level) {
this.setState({ subjects, level });
}
/**
* Search method
* Check if subjects or location are null (is so, show warnings)
* If no warnings, perform search and redirect to search page
* @param {*} event
*/
search(event) {
if (this.state.location === null) {
this.setState({ geosuggestId: 'geosuggest-input-alert' });
} else if (this.state.subjects.length === 0) {
this.setState({ matieresButtonId: 'matieres-button-alert' });
} else {
console.log(this.props.parent);
if (this.props.parent === 'Homepage') {
console.log(this.props.history);
this.props.history.push('/connexion');
}
}
}
/**
* Uses GeoSuggest (google places api) to choose a town
* Uses Search By Subject modal to choose subjects
*/
render() {
return (
<div className="container" id="search-bar" >
<div className="text-center">
<form action="">
<div className="row">
<div className="col">
<Geosuggest
queryDelay={150}
autoActivateFirstSuggest={true}
inputClassName={this.state.geosuggestId}
placeholder="Où ?"
country="fr"
onSuggestSelect={this.onSuggestSelect} />
</div>
<div className="col">
<Link to="/">
<button data-toggle="modal" data-target=".choose-subject-modal" className="btn clickable" id={this.state.matieresButtonId}>
<i className="fa fa-graduation-cap"></i> Matières ?
</button>
</Link>
</div>
<div className="col">
<Link to="/">
<button type="submit" className="btn clickable" id="search-button" onClick={this.search}>
<h5 id="search-btn-txt"><i className="fa fa-search"></i> Trouver</h5>
</button>
</Link>
</div>
</div>
</form>
<SearchBySubjectsModal search={this.search} location={this.state.location} setSubjects={this.setSubjects} />
</div>
</div>
);
};
}
export default withRouter(SearchBar);
</code></pre>
<p>Thank you for your answers :)</p>
| 1 | 2,544 |
c++ how-to: import numeric variables from .txt or .csv file
|
<p>still being a beginner at C++, I cannot figure out how to use <code>fstream</code>.
I want to assign values to a set of <code>double</code> variables in my program, from
a <code>.txt</code> or a <code>.csv</code> file (<code>.csv</code> might be better for practical reasons.)</p>
<p>Let's say that my <code>input_file.csv</code> looks like that:</p>
<pre><code>10
0
20
0.4
0.1333382222
0
0.5
10
20
0.76
0.3
0.1
0.2
</code></pre>
<p>These values should be assigned to the following variables (first declared as equal to <code>0</code> ) in my code:</p>
<pre><code>/// geometry
double Dist=0; ///Distance between the 2
double PosAi = 0;
double PosAo = 0;
double PosBi = 0;
double PosBo = 0; ///positions i/o
/// densities
double iDA=0;
double oDA=0;
double iDAtop=0;
double oDAtop=0; /// Left
double iDB=0;
double oDB=0;
double iDBtop=0;
double oDBtop=0; /// Right
</code></pre>
<p>I want to read the values of <code>input_file.csv</code> and assign them to my variables, so that if I type:</p>
<pre><code>cout<<Dist<<" "<<PosAi<<" "<<PosAo<<" "<<
</code></pre>
<p>...........etc. <code>;</code></p>
<p>I get the following list on the console:</p>
<pre><code>10 0 20 0.4 0.1333382222 0 0.5 10 20 0.76 0.3 0.1 0.2
</code></pre>
<p>But I don't know how to use fsteam for that, could you please help a bit?
Thanks!</p>
<hr>
<p>Ok here's the answer if ever some beginner like me gets the same problem:</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
/// geometry
double Dist=0; ///Distance between the 2
double PosAi = 0;
double PosAo = 0;
double PosBi = 0;
double PosBo = 0; ///positions i/o
/// densities
double iDA=0;
double oDA=0;
double iDAtop=0;
double oDAtop=0; /// Left
double iDB=0;
double oDB=0;
double iDBtop=0;
double oDBtop=0; /// Right
int main()
{
ifstream ifs ("input.csv");
if (!ifs)
// process error
ifs >> Dist;
ifs >> PosAi;
ifs >> PosAo;
ifs >> PosBi;
ifs >> PosBo;
ifs >> iDA;
ifs >> oDA;
ifs >> iDAtop;
ifs >> oDAtop;
ifs >> iDB;
ifs >> oDB;
ifs >> iDBtop;
ifs >> oDBtop;
// print variables
cout << Dist << " " << PosAi << " " << PosAo << " " << PosBi << " " << PosBo << " " << iDA << " " << oDA << " " << iDAtop << " " << oDAtop << " " << iDB << " " << oDB << " " << iDBtop << " " << oDBtop << endl;
}
</code></pre>
<p>Thanks</p>
| 1 | 1,197 |
Phonegap - onDeviceReady() wasn't fired
|
<p>Please have a look and helps me resolve this issue. I have spent 2 days of headache. The function onDeviceReady never be called.
Here is my codes:</p>
<pre><code> <!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>DemoSimpleControls</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link href="jqueryMobile/jquery.mobile-1.3.0.css" rel="stylesheet">
<link rel="stylesheet" href="css/DemoSimpleControls.css">
<script src="jqueryMobile/jquery.mobile-1.3.0.js"></script>
<script src="../js/jquery-1.9.1.min.js"></script>
< script type="text/javascript" charset="utf-8" src="../cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
// Handler for .ready() called.
document.addEventListener("deviceready", onDeviceReady, true);
});
$(function() {
document.addEventListener("deviceready", onDeviceReady, true);
});
function onDeviceReady(){
alert("ready");
$("#mysavedData").html("XYZ");
$("#mysavedData").html(window.localStorage.getItem("data"));
}
</script>
</head>
<body id="content" onLoad="onLoad();" >
<div data-role="page" id="page">
<div data-role="header" >
<a data-rel="back" href="#" >Back</a>
<h1>My page</h1>
</div>
<div data-role="content" style="padding: 15px" data-theme="e">
<div id="mysavedData">My data</div>
</div>
</div>
</body>
</html>
</code></pre>
| 1 | 1,661 |
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects
|
<p>I`m trying to build web api for complex object. For this aim I built the custom binder which deserialize this object from JSON.</p>
<p>My Customer Binder looks like:</p>
<pre><code>var paramType = p_BindingContext.ModelType;
dynamic updatedParam = Activator.CreateInstance(paramType);
JsonReader reader = new JTokenReader(JObject.Parse
(p_ActionContext.Request.Content.ReadAsStringAsync().Result));
JObject jObject = JObject.Load(reader);
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(jObject.CreateReader(), updatedParam);//Here the exception thorws
p_BindingContext.Model = updatedParam;
</code></pre>
<p>The object to serialize is very comlex:</p>
<pre><code> public class ModelRegisterUserRequest{
public ModelUser User { get; set; }
public CampaignItem CampaignWithChosenProposal { get; set; }
public string ValidationToken { get; set; }
public string IVRToken { get; set; }
public string DealerID { get; set; }
public string SalePersonID { get; set; }
}
public class CampaignItem
{
public List<BannerItem> Banners { get; set; }
public string Code { get; set; }
public string CustomerInstruction { get; set; }
public string InfoLink { get; set; }
public string LobbySubTitle { get; set; }
public string LobbyTitle { get; set; }
public string MoreText { get; set; }
public uint NumOfColumns { get; set; }
public uint NumOfRows { get; set; }
public string OriginString { get; set; }
public int OriginInt { get; set; }
public List<ProposalItem> Proposals { get; set; }
public string RegulationsInfoLink { get; set; }
public string ServiceType { get; set; }
public string SubTitle { get; set; }
public string SWDefault { get; set; }
public string Title { get; set; }
}
public partial class ProposalItem
{
public List<string> EquipmentsCode { get; set; }
public string FeatureCode { get; set; }
public string InvalidReason { get; set; }
public bool IsExistsMoreInfo { get; set; }
public bool IsValid { get; set; }
public string LeadCode { get; set; }
public int ParamCombinationCode { get; set; }
public string ProductCode { get; set; }
public string ProductCombinationCode { get; set; }
public string ProposalCode { get; set; }
public List<ColumnItem> Columns { get; set; }
public List<MoreInfoItem> MoreInfoList { get; set; }
public List<string> PricePlans { get; set; }
public string ProductName { get; set; }
</code></pre>
<p>}</p>
<p>The Json is created with JSON.stringify command from Javascript code and look like :</p>
<pre><code> {
"ValidationToken": "1cc6cca8-44d5-4042-af37-de6a0d198d17",
"AppID": "TST",
"campaignWithChosenProposal": {
"Banners": [
{
"LocationCodeString": "ManagerTab",
"LocationCodeInt": 256,
"MediaUrl": "<a href=\"c:\\\">BANNER 10</a>"
}
],
"Code": "CAMP221",
"CustomerInstruction": "-1",
"InfoLink": "http://test.aspx",
"LobbySubTitle": "",
"LobbyTitle": "",
"MoreText": "",
"NumOfColumns": 0,
"NumOfRows": 0,
"OriginString": "INT",
"OriginInt": 4,
"Proposals": [
[
{
"EquipmentsCode": [
"5455"
],
"FeatureCode": "BE5455",
"InvalidReason": "",
"IsExistsMoreInfo": true,
"IsValid": true,
"LeadCode": "3792956510",
"ParamCombinationCode": 0,
"ProductCode": "OANTIVRP2",
"ProductCombinationCode": "0",
"ProposalCode": "291600010201C8F83661D5B82FD5F3603967588B7A72",
"Columns": [
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
}
],
"MoreInfoList": [
{
"Content": "3",
"MoreInfoTypesString": "LicenseFrom",
"MoreInfoTypesInt": 16
},
{
"Content": "3",
"MoreInfoTypesString": "LicenseTo",
"MoreInfoTypesInt": 32
},
{
"Content": "4.3",
"MoreInfoTypesString": "PricePeriod1",
"MoreInfoTypesInt": 64
}
],
"PricePlans": [
"O2"
],
"ProductName": ""
}
]
],
"RegulationsInfoLink": "http://www.test.aspx",
"ServiceType": "TST",
"SubTitle": "",
"SWDefault": "1",
"Title": ""
},
"User": {
"CurrentLicenseNumber": 0,
"CustomerID": "21670106",
"FirstName": "",
"LastName": "",
"RequestedLicenseNumber": "3",
"SubscriberPhoneNumber": "035448428",
"IdentityNumber": "058470",
"Email": "alexanrbe@gmail.com",
"RegistrationStatus": "NOTREGISTERED"
},
"SalePersonID": "3178364",
}
</code></pre>
<p>The Exception is thrown on serilization row and looks like:</p>
<pre><code>Cannot deserialize the current JSON array (e.g. [1,2,3]) into type WebAPI.Models.Entities.Campaigns.CampaignObjects.ProposalItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
</code></pre>
<p>I spent nights for resolve this exception but did not find any solutions
Also the solutions on this site are excisted but not supports such complex problem.</p>
<p><a href="https://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-a-c-sharp-poco-class">https://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-a-c-sharp-poco-class
</a></p>
<p><a href="https://stackoverflow.com/questions/17762032/cannot-deserialize-the-current-json-array-e-g-1-2-3-into-type">Cannot deserialize the current JSON array (e.g. [1,2,3]) into type</a></p>
<p>Somebody met such JSON unexpected behaiviour and could help?</p>
<p>Thanks</p>
| 1 | 2,851 |
Spring Batch: Retrying a tasklet using @Retryable and @EnableRetry annotation
|
<p>I have this tasklet which uploads a file to Amazon S3. Now, I want to retry the tasklet execution whenever an <code>AmazonClientException</code> is thrown. I figured using <code>@Retryable</code> annotation will do the job.</p>
<p>Tasklet:</p>
<pre><code>@Component
@StepScope
@Retryable(value=AmazonClientException.class, stateful=true, backoff=@Backoff(2000))
public class S3UploadTasklet extends ArgsSupport implements Tasklet {
@Autowired
private S3Client s3Client;
@Autowired
private S3Properties s3Properties;
private static final Logger LOGGER = LoggerFactory.getLogger(S3UploadTasklet.class);
private static final String FILE_EXTENSION = ".gpg";
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
try {
String localFilename = getTempOutputFilename() + FILE_EXTENSION;
String s3Filename = s3Properties.getReportPath() + getS3OutputFilename() + FILE_EXTENSION;
File f = new File(localFilename);
if(f.exists()) {
LOGGER.info("Uploading " + localFilename + " to s3...");
s3Client.upload(localFilename, s3Filename, s3Properties.getBucketName());
LOGGER.info("Uploading done!");
} else {
throw new RuntimeException("Encrypted file not found! Encryption process might have failed.");
}
} catch(AmazonClientException e) {
LOGGER.error("Problems uploading to S3. " + e.getMessage(), e);
throw e;
} catch(RuntimeException e) {
LOGGER.error("Runtime error occured. " + e.getMessage(), e);
throw e;
}
return RepeatStatus.FINISHED;
}
}
</code></pre>
<p>Job configuration:</p>
<pre><code>@Configuration
@EnableBatchProcessing
@EnableRetry
public class BatchConfiguration {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private Step generateReport;
@Autowired
private Step encrypt;
@Autowired
private Step upload;
@Autowired
private Step cleanUp;
@Bean
@Transactional(value="appTransactionManager", isolation=Isolation.READ_COMMITTED)
public Job generateReconJob() {
return jobBuilderFactory.get("reconJob")
.incrementer(new RunIdIncrementer())
.start(generateReport)
.on("COMPLETED").to(encrypt)
.from(generateReport)
.on("NOOP").end()
.from(generateReport)
.on("FAILED").to(cleanUp)
.from(encrypt)
.on("COMPLETED").to(upload)
.from(encrypt)
.on("FAILED").to(cleanUp)
.from(upload)
.on("*").to(cleanUp)
.from(cleanUp)
.on("*").end()
.end()
.build();
}
}
</code></pre>
<p>However, it doesn't do what it is supposed to do. The batch job still doesn't retry the tasklet when the exception is thrown.</p>
<p>Any thoughts?</p>
<p>Here's the config also</p>
<pre><code>@Configuration
public class ReportConfiguration {
...
@Autowired
private S3UploadTasklet s3UploadTasklet;
...
@Bean
public Step upload() {
return stepBuilderFactory.get("upload")
.tasklet(s3UploadTasklet)
.build();
}
}
</code></pre>
| 1 | 1,547 |
How to delete item from custom listview on long click in android?
|
<p>I have a listview with custom base adapter which validate some items in listview. What i want is when i long click on item oflistview, a dialog should open stating "Yes" or "No" and when i tap on "Yes" it should delete that item from adapter.How can i do that.</p>
<p>Here is code of Adapter</p>
<pre><code>private static final String TAG = CDealAppListingAdapter.class.getSimpleName();
private static final String DEAL_CODE = "DealCode";
private static final String HEADER_TEXT = "headerText";
private static final String LOGO_PATH = "logoPath";
private final Context m_Context;// declaring context variable
private final ArrayList<CDealAppDatastorage> s_oDataset;// declaring array list ariable
public CDealAppListingAdapter(Context m_Context, ArrayList<CDealAppDatastorage> mDataList) {
this.m_Context = m_Context;
s_oDataset = mDataList;
}
@Override
public int getCount() {// get total arraylist size
return s_oDataset.size();
}
@Override
public Object getItem(int position) {// get item position in array list
return s_oDataset.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressWarnings("deprecation")
@SuppressLint({"SetTextI18n", "InflateParams"})
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.deallisting_card_view, null);
viewHolder.m_Header = (TextView) convertView.findViewById(R.id.headingText);
viewHolder.m_DummyText = (TextView) convertView.findViewById(R.id.subHeadingText);
viewHolder.m_logoImage = (ImageView) convertView.findViewById(R.id.appImage);
viewHolder.m_getBtn = (Button) convertView.findViewById(R.id.getDealBtn);
viewHolder.mProgress = (ProgressBar) convertView.findViewById(R.id.progressBar3);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.m_getBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
@Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
if (NetworkUtil.isConnected(m_Context)) {
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra(DEAL_CODE, s_oDataset.get(position).getM_szsubHeaderText());// get deal code from deal data storage
i.putExtra(HEADER_TEXT, s_oDataset.get(position).getM_szHeaderText());// get deal name from deal dta storage
i.putExtra(LOGO_PATH, s_oDataset.get(position).getM_szLogoPath());
v.getContext().startActivity(i);
} else {
/*here I am getting error*/
CSnackBar.showSnackBarError(v, m_Context.getString(R.string.no_internet_connection), v.getContext());
}
}
});
CDealAppDatastorage m = s_oDataset.get(position);
viewHolder.m_Header.setText(m.getM_szHeaderText());
viewHolder.m_DummyText.setText(m.getM_szDetails());
viewHolder.m_getBtn.setText("GET " + m.getM_szDealValue() + " POINTS");// set deal button text
Picasso.with(m_Context).load(m.getM_szLogoPath()).into(viewHolder.m_logoImage, new Callback() {
@Override
public void onSuccess() {
Log.e(TAG, "OnSuccess Called::");
viewHolder.mProgress.setVisibility(View.INVISIBLE);
}
@Override
public void onError() {
Log.e(TAG, "OnError Called::");
}
});
return convertView;
}
private class ViewHolder {
public TextView m_Header, m_Subheader, m_DummyText;
public ImageView m_logoImage;
public Button m_getBtn;
public ProgressBar mProgress;
}
}
</code></pre>
| 1 | 1,599 |
Why ConstraintLayout slower than LinearLayout in RecyclerView item?
|
<p>I'm changing the xml item of recyclyerView from LinearLayout to ConstraintLayout.
When I'm scrolling the recyclerView horizontal, it lags and renders very slowly than LinearLayout.</p>
<p><strong>ConstraintLayout</strong></p>
<p><img src="https://i.stack.imgur.com/DEQvt.gif" alt="ConstraintLayout"></p>
<p><strong>LinearLayout</strong></p>
<p><img src="https://i.stack.imgur.com/jKXNY.gif" alt="LinearLayout"></p>
<p>Here i am sharing my xml for ConstraintLayout.</p>
<p><strong>my ConstraintLayout Item</strong></p>
<pre><code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="85dp"
android:layout_height="wrap_content">
<android.support.constraint.ConstraintLayout
android:id="@+id/merchant_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/merchant_img"
android:layout_width="75dp"
android:layout_height="75dp"
android:transitionName="profile"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UnusedAttribute"
tools:src="@drawable/avatar" />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:maxLines="1"
android:maxWidth="72dp"
android:minWidth="72dp"
android:textAlignment="center"
android:textColor="@color/blackFont"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="@id/merchant_img"
app:layout_constraintStart_toStartOf="@id/merchant_img"
app:layout_constraintTop_toBottomOf="@id/merchant_img"
tools:text="Chili's" />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_offer_percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/redColor"
android:textSize="12sp"
app:layout_constraintBottom_toTopOf="@id/tv_distance"
app:layout_constraintEnd_toStartOf="@id/merchant_offer_type"
app:layout_constraintStart_toStartOf="@id/merchant_name"
app:layout_constraintTop_toBottomOf="@id/merchant_name"
app:textBold="bold"
tools:text="25%" />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_offer_type"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textColor="@color/blackFont"
android:textSize="12sp"
app:layout_constraintBottom_toTopOf="@id/tv_distance"
app:layout_constraintEnd_toEndOf="@id/merchant_name"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toEndOf="@id/merchant_offer_percent"
app:layout_constraintTop_toBottomOf="@id/merchant_name"
tools:text=" | Refund " />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/tv_distance"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textAlignment="center"
android:textColor="@color/greyFont"
android:textSize="14sp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/merchant_img"
app:layout_constraintStart_toStartOf="@id/merchant_img"
app:layout_constraintTop_toBottomOf="@id/merchant_offer_percent" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</code></pre>
<p><strong>my LinearLayout Item</strong> </p>
<pre><code><android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="85dp"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/merchant_layout"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="10dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/merchant_img"
android:layout_width="75dp"
android:layout_height="75dp"
android:transitionName="profile"
tools:ignore="UnusedAttribute"
tools:src="@drawable/avatar" />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:ellipsize="end"
android:maxLines="1"
android:maxWidth="72dp"
android:minWidth="72dp"
android:textAlignment="center"
android:textColor="@color/blackFont"
android:textSize="14sp"
tools:text="Chili's" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:orientation="horizontal">
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_offer_percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/redColor"
android:textSize="12sp"
app:textBold="bold"
tools:text="25%" />
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/merchant_offer_type"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:lines="1"
android:textColor="@color/blackFont"
android:textSize="12sp"
tools:text=" | Refund " />
</LinearLayout>
<com.max.xclusivekotlin.customViews.MyTextView
android:id="@+id/tv_distance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textAlignment="center"
android:textColor="@color/greyFont"
android:textSize="14sp"
android:visibility="gone" />
</LinearLayout>
</android.support.v7.widget.CardView>
</code></pre>
<p>How can I solve this?</p>
| 1 | 3,332 |
Android/Java - Test if date was last month
|
<p>I am working on an app where I store some information between each use, this data essentially boils down to counting the number of times an event has happened today, this week, this month and in the apps lifetime. I store this data in 4 distinct counters I can load/save using SharedPreferences.</p>
<p>Alongside the data I store the "last run time" of the app as a date, my plan was that during load time I will load in the counters then test the stored date against today's date to determine which counters need to be cleared.</p>
<p>Sounds simple right!</p>
<p>After pulling my hair out for a while and going backward and forwards through the Calendar documentation I think I understand them enough to come up with the following:</p>
<pre><code> Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, -1);
if ( !last.after(today) )
{
today = 0;
}
today.add(Calendar.WEEK_OF_MONTH, -1);
today.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
if ( !last.after(today) )
{
today = 0;
week = 0;
}
today = Calendar.getInstance();
today.add(Calendar.MONTH, -1);
today.set(Calendar.DATE, today.getActualMaximum(Calendar.DATE));
if ( !last.after(today) )
{
today = 0;
week = 0;
month = 0;
}
</code></pre>
<p>I think this should be fine, however the issue I have is testing, testing today is easy, however testing the month logic would require either waiting a month, or writing a test case which uses the Calendar API to simulate an old date, however I can't write the test case if my assumptions on how the API works was wrong in the first place!</p>
<p>Therefore, after a large wall of text my question is... does the above block of code look sane, or have I completely mis-understood working with dates in Java?</p>
<p>Thanks!</p>
<h2>Edit:</h2>
<p>Second pass at the code:</p>
<p>Does this look any more sensible? If I am understanding things correctly I am now attempting to compare the end of the date that was last saved with the very start of today, this week and this month.</p>
<pre><code>Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
last.set(Calendar.HOUR_OF_DAY, last.getActualMaximum(Calendar.HOUR_OF_DAY));
last.set(Calendar.MINUTE, last.getActualMaximum(Calendar.MINUTE));
last.set(Calendar.SECOND, last.getActualMaximum(Calendar.SECOND));
last.set(Calendar.MILLISECOND, last.getActualMaximum(Calendar.MILLISECOND));
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, todayStart.getActualMinimum(Calendar.HOUR_OF_DAY));
todayStart.set(Calendar.MINUTE, todayStart.getActualMinimum(Calendar.MINUTE));
todayStart.set(Calendar.SECOND, todayStart.getActualMinimum(Calendar.SECOND));
todayStart.set(Calendar.MILLISECOND, todayStart.getActualMinimum(Calendar.MILLISECOND));
// If the last recorded date was before the absolute minimum of today
if ( last.before(todayStart) )
{
todayCount = 0;
}
Calendar thisWeekStart = Calendar.getInstance();
thisWeekStart.set(Calendar.HOUR_OF_DAY, thisWeekStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisWeekStart.set(Calendar.MINUTE, thisWeekStart.getActualMinimum(Calendar.MINUTE));
thisWeekStart.set(Calendar.SECOND, thisWeekStart.getActualMinimum(Calendar.SECOND));
thisWeekStart.set(Calendar.DAY_OF_WEEK, thisWeekStart.getFirstDayOfWeek());
thisWeekStart.set(Calendar.MILLISECOND, thisWeekStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this week then clear
// this week (and today, just to be on the safe side)
if ( last.before(thisWeekStart) )
{
todayCount = 0;
weekCount = 0;
}
Calendar thisMonthStart = Calendar.getInstance();
thisMonthStart.set(Calendar.HOUR_OF_DAY, thisMonthStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisMonthStart.set(Calendar.MINUTE, thisMonthStart.getActualMinimum(Calendar.MINUTE));
thisMonthStart.set(Calendar.SECOND, thisMonthStart.getActualMinimum(Calendar.SECOND));
thisMonthStart.set(Calendar.DAY_OF_MONTH, thisMonthStart.getActualMinimum(Calendar.MONTH));
thisMonthStart.set(Calendar.MILLISECOND, thisMonthStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this month then clear month...
if ( !last.after(thisMonthStart) )
{
todayCount = 0;
weekCount = 0;
monthCount = 0;
}
</code></pre>
| 1 | 1,686 |
Mongoengine - command find requires authentication
|
<p>I am new to using Mongoengine with an authenticated MongoDB.</p>
<p>I have a Mongo Database called 'gambit_test'. I have enabled authentication on it and I have a proper user that can I authenticate into the database to perform read and write.</p>
<p>I created the user for 'gambit_test' using the following command in Mongo Client:</p>
<pre><code>use gambit_test
db.createUser({
user: "gambit_admin",
pwd: "xxxxxx",
roles:[{role: "userAdmin" , db:"admin"}]
})
</code></pre>
<p>When I log into MongoDB to check my user status, I use a command as follows (logging in as a super admin):</p>
<pre><code>mongo -u sup_admin -p yyyyyyyy
</code></pre>
<p>To verify my user status, here is what I run:</p>
<pre><code>use gambit_test
show users
</code></pre>
<p>It returns the following:</p>
<pre><code>{
"_id" : "gambit_test.gambit_admin",
"user" : "gambit_admin",
"db" : "gambit_test",
"roles" : [
{
"role" : "readWrite",
"db" : "gambit_test"
},
{
"role" : "dbAdmin",
"db" : "gambit_test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
</code></pre>
<p>Inside my Python <code>test.py</code> code, here is what I am doing:</p>
<pre><code>from mongoengine import *
class History(Document):
name = StringField(required=True)
if __name__ == "__main__":
try:
connect('gambit_test')
History.objects().get()
except Exception as e:
connect(host='mongodb://gambit_admin:xxxxxx@localhost' +
':27017/gambit_test')
History.objects().get()
</code></pre>
<p>When I try to run the above python code, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 12, in <module>
History.objects().get()
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 267, in get
result = six.next(queryset)
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/mongoengine/queryset/base.py", line 1484, in __next__
raw_doc = six.next(self._cursor)
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 1189, in next
if len(self.__data) or self._refresh():
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 1104, in _refresh
self.__send_message(q)
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/cursor.py", line 982, in __send_message
helpers._check_command_response(first)
File "/home/ubuntu/gambit/genv/lib/python3.6/site-packages/pymongo/helpers.py", line 155, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command find requires authentication
</code></pre>
<p>I have no clue why this is happening. The reason is I can perform normal find() and insert() using Mongo client. But, when I use Mongoengine, things break...</p>
<p>Any help would be very much appreciated.</p>
| 1 | 1,211 |
Connect remote scylla db server shows error
|
<p>I have installed scylla-db in google cloud servers.</p>
<p><strong>Steps i have followed:</strong></p>
<pre><code>sudo yum install epel-release
sudo curl -o /etc/yum.repos.d/scylla.repo -L http://repositories.scylladb.com/scylla/repo/a2a0ba89d456770dfdc1cd70325e3291/centos/scylladb-2.0.repo
sudo yum install scylla
sudo scylla_setup
(Given yes to "verify supportable version" , " verify packages" , "core dump", " fstim ssd "
For remaining : Given NO)
IN file :/etc/scylla.d/io.conf
SEASTAR_IO="--max-io-requests=12 --num-io-queues=1"
( edited this file manually )
sudo systemctl start scylla-server
</code></pre>
<p>It shows: Cannot able to read yaml file. Then google it and downgraded the yaml-cpp version to 0.5.1 from 0.5.3 version.
<em>then
scylla-server started running .</em></p>
<pre><code>[root@scylla ~]# nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns Host ID Rack
UN 127.0.0.1 208.69 KB 256 ? 888e91da-9385-4c61-8417-dd59c1a979b8 rack1
Note: Non-system keyspaces don't have the same replication settings, effective ownership information is meaningless
[root@scylla ~]# cat /etc/scylla/scylla.yaml | grep seeds:
- seeds: "127.0.0.1"
[root@scylla ~]# cat /etc/scylla/scylla.yaml | grep rpc_address:
rpc_address: localhost
#broadcast_rpc_address:
[root@scylla ~]# cat /etc/scylla/scylla.yaml | grep listen_address:
listen_address: localhost
[root@scylla ~]# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.0.8 | CQL spec 3.3.1 | Native protocol v4]
Use HELP for help.
cqlsh> exit
[root@scylla ~]# netstat -tupln | grep LISTEN
tcp 0 0 127.0.0.1:10000 0.0.0.0:* LISTEN 6387/scylla
tcp 0 0 127.0.0.1:9042 0.0.0.0:* LISTEN 6387/scylla
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1105/sshd
tcp 0 0 127.0.0.1:7000 0.0.0.0:* LISTEN 6387/scylla
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1119/master
tcp 0 0 0.0.0.0:9180 0.0.0.0:* LISTEN 6387/scylla
tcp 0 0 127.0.0.1:9160 0.0.0.0:* LISTEN 6387/scylla
tcp6 0 0 :::80 :::* LISTEN 5217/httpd
tcp6 0 0 :::22 :::* LISTEN 1105/sshd
tcp6 0 0 :::35063 :::* LISTEN 6412/scylla-jmx
tcp6 0 0 ::1:25 :::* LISTEN 1119/master
tcp6 0 0 127.0.0.1:7199 :::* LISTEN 6412/scylla-jmx
</code></pre>
<p>scylla-server is running.</p>
<p>Same setup was done another server
Server Name scylla-db-1</p>
<p>I need to connect to the server scylla ( IP: xx.xx.xxx) from this server.</p>
<p>when i execute the below :</p>
<pre><code>[root@scylla-db-1 ~]# cqlsh xx.xx.xxx
Connection error: ('Unable to connect to any servers', {'xx.xx.xxx': error(111, "Tried connecting to [('xx.xx.xxx', 9042)]. Last error: Connection refused")})
</code></pre>
<p><strong>How to connect the remote server from this server?</strong></p>
<p>Also
while checking the <a href="http://xx.xx.xxx:10000" rel="nofollow noreferrer">http://xx.xx.xxx:10000</a> and <a href="http://xx.xx.xxx:10000/ui" rel="nofollow noreferrer">http://xx.xx.xxx:10000/ui</a> in the browser , I m getting problem loading page.</p>
<p>Note :</p>
<blockquote>
<p>I have done editing the /etc/scylla.d/io.conf file for assigning the
max-io-requests manually </p>
</blockquote>
| 1 | 2,088 |
How to read healthKit Heartrate data?
|
<p>I know this questions been asked, but hasn't really been answered. I've tried things from threads like this:
<a href="https://stackoverflow.com/questions/31440205/heart-rate-with-apples-healthkit">Heart Rate With Apple's Healthkit</a></p>
<p>I tried converting this from Objective-C to Swift but didn't work.</p>
<p>My question is, what's the best way to read heart rate data from health kit. I want to be able to read every heart rate measurement from the time it started taking them, and I want to be able to see the time/day stamps of said measurements.</p>
<p>I asked for permission here: </p>
<pre><code>import Foundation
import UIKit
import HealthKit
class HealthKitManager: NSObject {
static let healthKitStore = HKHealthStore()
static func authorizeHealthKit() {
let healthKitTypes: Set = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
]
healthKitStore.requestAuthorizationToShareTypes(healthKitTypes,
readTypes: healthKitTypes) { _, _ in }
}
}
</code></pre>
<p>Here is my view Controller code for now (I'm not sure why this doesn't work):</p>
<pre><code>import UIKit
import HealthKit
class ViewController: UIViewController {
let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func authorizeTapped(sender: AnyObject) {
print("button tapped")
self.createStreamingQuery()
HealthKitManager.authorizeHealthKit()
}
func createStreamingQuery() -> HKQuery
{
let queryPredicate = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)
let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query error: \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
}
}
}
}
query.updateHandler =
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query-handler error : \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
}
}
}//eo-non_error
}//eo-query-handler
return query
}
}
</code></pre>
<p>I can't get anything to print to the console, which is really just what I want.</p>
<p>Also - none of this code is going towards homeworks, personal/professional projects...etc. Its just for fun/to learn, and most of this code is what I tried and what I've found looking through multiple stack over flow and other forums.</p>
| 1 | 1,558 |
What is the best way to read and write data to a buffer for my bar code reader?
|
<p>I need to write a driver for a bar code reader for Linux in C. The bar code reader works through the serial bus. When I send a set of commands to the bar code reader, the bar code reader should return status messages to me. I managed to configure the port and to create a signal handler. In the signal handler, I read the data which the serial bus receives.</p>
<p>So the question is: Should I read the data in buffer and then work with it? And can I even write the data in the buffer with the port configured in this way? When the device replies to me, according to that reply data, I need to send another command to the device.
Also, can I use <code>write()</code> to write the messages? If I can’t use that, what command should I use?
And can you help me a little with the write command?</p>
<p>The command that I send to the device is always 7 bytes, but the reply data varies between 7-32 bytes. If the read function sends different number of bytes that are read, how can I be sure that I received all of the data, so I can work with it?</p>
<p>Here is some code that I've written. Am I going in the right direction?
Once more, the idea is very simple: I am sending a command to a device, and the device interupt me and replies. I read what was send, I work with the reply data, and according to that data, I am send another command.
Thanks in forward. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <errno.h>
#include <termios.h>
void signal_handler_IO (int status); /* definition of signal handler */
int n;
int fd;
int connected;
char buffer[14];
int bytes;
struct termios termAttr;
struct sigaction saio;
int main(int argc, char *argv[])
{
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyO1\n");
exit(1);
}
saio.sa_handler = signal_handler_IO;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
fcntl(fd, F_SETFL, FNDELAY);
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, O_ASYNC );
tcgetattr(fd,&termAttr);
//baudRate = B115200;
cfsetispeed(&termAttr,B115200);
cfsetospeed(&termAttr,B115200);
termAttr.c_cflag &= ~PARENB;
termAttr.c_cflag &= ~CSTOPB;
termAttr.c_cflag &= ~CSIZE;
termAttr.c_cflag |= CS8;
termAttr.c_cflag |= (CLOCAL | CREAD);
termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
termAttr.c_oflag &= ~OPOST;
tcsetattr(fd,TCSANOW,&termAttr);
printf("UART1 configured....\n");
connected = 1;
while(connected == 1){
//write function and read data analyze(Processing)
}
close(fd);
exit(0);
}
void signal_handler_IO (int status)
{
bytes = read(fd, &buffer, sizeof(buffer));
printf("%s\n", buffer);
}
</code></pre>
| 1 | 1,261 |
null pointer exception when retrieving from HashMap even though containsKey() returns true
|
<p>I've been developing an Android guitar app, and currently I'm having some problems with <code>HashMap</code>.</p>
<p>To sum it up, I get a <strong>nullpointer exception</strong> when I try to retrieve a value from a <code>HashMap</code> with <code>get(key)</code> despite <code>containsKey(key)</code> returning <code>true</code> for that key.</p>
<p>Specifically, I have an instance <code>_currentPreset</code> of a class, which has a <code>HashMap</code> called <code>_maxCoordRange</code>, which is initialized in the class like this: </p>
<pre><code>private Map<String, Float> _maxCoordRange = new HashMap<String, Float>();
</code></pre>
<p>This parameter is not modified in the constructors of the class. Instead, it can only be modified by the following method:</p>
<pre><code>public void setMaxCoordRange(String parName, float value) {
_maxCoordRange.put(parName, value);
}
</code></pre>
<p>and accessed by:</p>
<pre><code>public float getMaxCoordRange(String parName) {
return _maxCoordRange.get(parName);
}
</code></pre>
<p>Once I've created the <code>_currentPreset</code> instance, I set some values to the <code>_maxCoordRange</code> map like this:</p>
<pre><code>for (int i = 0; i < _currentPreset.getCoordiates().size(); i++) {
_currentPreset.setMaxCoordRange(_currentPreset.getParNames().get(i), 0.75f);
}
</code></pre>
<p>In other parts of the code I do the following:</p>
<pre><code>if(_currentPreset.getMaxCoordRange().containsKey(pareterName)){
cord.setMaxValueCoord(_currentPreset.getMaxCoordRange(pareterName));
}
</code></pre>
<p>Here is the odd part. I get a nullpointer exeption when I try to retrieve the value corresponding to the <code>pareterName</code> from the <code>HashMap</code> with <code>getMaxCoordRange</code>, despite <code>containsKey(key)</code> returning true.</p>
<p>I did some debugging and I found something rather strange to me.
When I finished putting the values in the map, in the expressions tag (when in debugging mode in eclipse), the table looks like this:</p>
<pre><code>table HashMap$HashMapEntry[16] (id=829660787832)
[0] null
[1] null
[2] null
[3] null
[4] null
[5] null
[6] null
[7] null
[8] HashMap$HashMapEntry (id=829660788568)
[9] HashMap$HashMapEntry (id=829660786456)
[10] HashMap$HashMapEntry (id=829660787920)
[11] HashMap$HashMapEntry (id=829660788376)
[12] HashMap$HashMapEntry (id=829660787448)
[13] HashMap$HashMapEntry (id=829660787640)
[14] HashMap$HashMapEntry (id=829660786840)
hash 789729998
key "Test Par3" (id=829660737240)
next HashMap$HashMapEntry (id=829660786144)
hash 789729854
key "Test Par1" (id=829660736816)
next null
value Float (id=829660786088)
value Float (id=829660786824)
[15] HashMap$HashMapEntry (id=829660787088)
hash 789729999
key "Test Par4" (id=829660737376)
next HashMap$HashMapEntry (id=829660786648)
hash 789729855
key "Test Par2" (id=829660737104)
next null
value Float (id=829660786632)
value Float (id=829660787016)
</code></pre>
<p>There should be 10 values, and there are, but 2 of them are in the <code>next</code> field of elements 14 and 15. I read that this is the way the hashMaps arrange the data in order to be more efficient, but couldn't it be the reason why I'm not able to retrieve the values?</p>
<p>Sorry about giving so much information, but I don't really know where the problem is. I've used HashMaps before and I didn't have this problem.</p>
<p>Any ideas on how can i solve this and finally get my values from the map?</p>
| 1 | 1,491 |
Android HTTPPost List<NameValuePair> post to php?
|
<p>I have been searching for hours and I am still unclear on <code>HTTPPost</code> method. I have code like this...</p>
<pre><code>httpclient = new DefaultHttpClient();
httppost = new HttpPost(url);
// Add your data
Log.i("ACTIVITY","PostInfo");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", stringeditemail));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
</code></pre>
<p>Is this supposed to post the information to the given php from the designated site?
If so, What am I doing wrong that it is not posting?</p>
<p>This is my PHP</p>
<pre><code><?php
require('include/config.php');
require('include/function.php');
require('classes/captcha.class.php');
require('language/' .$_SESSION['language']. '/signup.lang.php');
if ( $config['user_registrations'] == 0 ) {
$msg = $lang['signup.registration_disabled'];
session_write_close();
header('Location: index.php?msg=' .$msg);
die();
}
$email = NULL;
if ( isset($_REQUEST['action_signup']) && $_REQUEST['action_signup'] != '' )
{
$email = $filterObj->process(trim($_POST['email']));
if( $email == '' )
$err = $lang['signup.email_empty'];
elseif ( !check_email($email) )
$err = $lang['signup.email_invalid'];
elseif ( check_field_exists($email, 'email', 'signup') == 1 )
$err = $lang['signup.email_exists'];
$_REQUEST['pack_id'] == '' )
$err = $lang['signup.select_package'];
if ( $err == '' ) {
$email = mysql_real_escape_string($email);
$sql = "insert into signup set email='" .$email. "';
$conn->execute($sql);
if( $config['enable_package'] == 'yes' ) {
$pack_id = mysql_real_escape_string($_REQUEST['pack_id']);
$sql = "select * from package where pack_id='" .$pack_id. "'";
$rs = $conn->execute($sql);
} else {
$sql = "update signup set acount_status='Inactive' where UID='" .$userid. "' limit 1";
$conn->execute($sql);
session_write_close();
header("Location: pack_ops.php?pack=$_REQUEST[pack_id]&uid=".base64_encode($userid));
die();
}
}
$sql = "INSERT INTO users_online (UID, online) VALUES (" .$userid. ", " .time(). ")";
$conn->execute($sql);
$_SESSION['EMAIL'] = $_REQUEST['email'];
$ran=time().rand(1,99999999);
$sql="update verify as v, signup as s set v.vcode='" .$ran. "', s.emailverified='no' WHERE v.UID=s.UID and v.UID='" .$userid. "'";
$conn->execute($sql);
STemplate::assign('vcode',$ran);
$to = $_SESSION['EMAIL'];
$name = $config['site_name'];
$from = $config['admin_email'];
$rs = $conn->execute("select * from emailinfo where email_id='verify_email'");
$subj = $rs->fields['email_subject'];
$email_path = $rs->fields['email_path'];
$mailbody = STemplate::fetch($email_path);
mailing($to,$name,$from,$subj,$mailbody);
$_SESSION['verification_sent'] = $lang['signup.verification_sent'];
$redirect = ( isset($_SESSION['redirect']) && $_SESSION['redirect'] != '' ) ? $_SESSION['redirect'] : $config['BASE_URL'];
$_SESSION['redirect'] = NULL;
session_write_close();
header('Location: ' .$redirect);
die();
}
}
if ( $config['enable_package'] == 'yes' ) {
$sql = "select * from package where status = 'Active' order by price desc";
$rs = $conn->execute($sql);
STemplate::assign('package', $rs->getrows());
}
STemplate::assign('err',$err);
STemplate::assign('msg',$msg);
STemplate::assign('head_bottom',"homelinks.tpl");
STemplate::assign('username', $username);
STemplate::assign('email', $email);
STemplate::display('head1.tpl');
STemplate::display('err_msg.tpl');
STemplate::display('signup.tpl');
STemplate::display('footer.tpl');
STemplate::gzip_encode();
?>
</code></pre>
| 1 | 1,647 |
How do I fix 403 Errors when trying to display an SVG <image>?
|
<p>I'm building an interactive report based on this: <a href="https://avocode.com/design-report-2017" rel="nofollow noreferrer">https://avocode.com/design-report-2017</a></p>
<p>Everything worked great on localhost, but when I uploaded it to the server, I'm getting a 403 (Forbidden) error for all of the SVG images.</p>
<p>I have tried using both relative and absolute paths for the images. Images not in <code><image></code> tags (regular <code><img></code>) work well.</p>
<p>Based on this question: <a href="https://stackoverflow.com/questions/25157431/403-forbidden-error-when-displaying-svg-image">403 forbidden error when displaying svg image</a>, it really sounds like the problem is that the server does not have the proper permissions to load SVG images. </p>
<p>However, I can't seem to find what the permissions need to be <em>changed to</em>. I don't have access to make server changes and have no idea what to tell the back-end developer to change.</p>
<p>I've also read that xlink:href is deprecated (<a href="https://css-tricks.com/on-xlinkhref-being-deprecated-in-svg/" rel="nofollow noreferrer">https://css-tricks.com/on-xlinkhref-being-deprecated-in-svg/</a>) and should be replaced with <code><use></code>, but I can't find documentation on how to use <code><use></code> tags in conjunction with <code><image></code> tags. MDN (<a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image</a>) and W3C (<a href="https://www.w3.org/TR/SVG11/struct.html#ImageElement" rel="nofollow noreferrer">https://www.w3.org/TR/SVG11/struct.html#ImageElement</a>) still use xlink:href in their <code><image></code> documentation.</p>
<p>If the error is due to xlink:href deprecation, how do I properly reference an image file within an <code><svg></code>? If <code><use></code> is the preferred method, how would I rewrite the above code to accommodate?</p>
<p>Any help on rewriting my code to properly display the images or reconfiguring the server to display them would be a life-saver.</p>
<p>Thank you for your time.</p>
<p>My code is below:</p>
<pre><code><div title aria-label="aimation" style="width: 100%; height: 100%; overflow: hidden; margin: 0px auto;">
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" viewbox="0 -100 800 1000" width="1340" height="1440" style="width: 100%; height: 100%;">
<g>
<g id="o-phone" class="image" transform="translate(-500 500)">
<image width="500px" height="300px" href="/img/omnichannel/Phone.svg"></image>
</g>
<g id="o-floating-shelf" class="image" transform="translate(750 -200)">
<image width="120px" height="300px" href="/img/omnichannel/Floating Shelves.svg"></image>
</g>
<g id="o-bookshelf1" class="image" transform="translate(445 -1000)">
<image width="150px" height="300px" href="/img/omnichannel/Bookshelf.svg"></image>
</g>
<g id="o-stack1" class="image" transform="translate(520 -500)">
<image width="35px" height="300px" href="/img/omnichannel/Stack Back Bottom.svg"></image>
</g>
<g id="o-bookshelf2" class="image" transform="translate(420 -1000)">
<image width="150px" height="300px" href="/img/omnichannel/Bookshelf.svg"></image>
</g>
<g id="o-stack2" class="image" transform="translate(390 -500)">
<image width="35px" height="300px" href="/img/omnichannel/Stack Front Bottom.svg"></image>
</g>
</g>
</svg>
</div>
</code></pre>
| 1 | 1,483 |
Program to determine total stops taken by elevator
|
<p>I was asked a question to write a optimal program that would determine the total number of stops a elevator has taken to serve X number of people. Question description is as below.</p>
<p>There is a elevator in a building with M floors, this elevator can take a max of X people at a time or max of total weight Y. Given that a set of people has arrived and their weight and the floor they need to stop given how many stops has the elevator taken to serve all the people. Consider elevator serves in the first come first serve basis.</p>
<p>E.g. Let Array A be the weight of people to be considered
A[] = {60, 80, 40 }</p>
<p>Let Array B be the floors where person needs to be dropped respectively
B[] = {2, 3, 5}</p>
<p>Total building floors be 5,max allowed person in elevator be 2 at a time with max weight capacity being 200
For this example the elevator would take total of 5 stops floors ground, 2, 3,ground, 5 , ground</p>
<p>What would be the optimal code for this?</p>
<p>One of my solution is as below. Is there any other better solutions?</p>
<pre><code>class Solution
{
/// <summary>
/// Return total stops used
/// </summary>
/// <param name="A">weight of people</param>
/// <param name="B">floors they need to get down</param>
/// <param name="M">total floors in the building</param>
/// <param name="X">Max people to carry at a time</param>
/// <param name="Y">max weight to carry at a time</param>
/// <returns></returns>
public int solution(int[] A, int[] B, int M, int X, int Y)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
int totalStops = 0;
long totalWeightPerRound = 0;
int maxPersonsCount = 0;
List<int> lstFloors = new List<int>();
int currPerson = 0;
bool startLift = false;
while (currPerson < A.Length)
{
if ((totalWeightPerRound + A[currPerson]) <= Y && (maxPersonsCount+1) <= X)
{
totalWeightPerRound += A[currPerson];
maxPersonsCount++;
lstFloors.Add(B[currPerson]);
if (currPerson == A.Length - 1)
startLift = true;
currPerson++;
}
else
{
startLift = true;
}
if (startLift)
{
totalStops += lstFloors.Distinct().Count() + 1;
lstFloors.Clear();
maxPersonsCount = 0;
totalWeightPerRound = 0;
startLift = false;
}
}
return totalStops;
}
}
</code></pre>
| 1 | 1,190 |
Initial SessionFactory creation failed.org.hibernate.HibernateException: Missing column: dept_id
|
<pre><code>Initial SessionFactory creation failed.org.hibernate.HibernateException: Missing column: dept_id
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.atom.HibernateOne.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at com.atom.HibernateOne.HibernateUtil.<clinit>(HibernateUtil.java:8)
at com.atom.HibernateOne.Main.main(Main.java:17)
Caused by: org.hibernate.HibernateException: Missing column: dept_id
at org.hibernate.mapping.Table.validateColumns(Table.java:212)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:964)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:116)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:296)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1164)
at com.atom.HibernateOne.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
</code></pre>
<hr>
<p>department table</p>
<pre><code>CREATE TABLE `department` (
`dept_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(50) NOT NULL DEFAULT '0',
PRIMARY KEY (`dept_id`)
)
;
</code></pre>
<p>employeeo table </p>
<pre><code>CREATE TABLE `employeeo` (
`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(50) NULL DEFAULT NULL,
`lastname` VARCHAR(50) NULL DEFAULT NULL,
`birth_date` DATE NULL DEFAULT NULL,
`cell_phone` VARCHAR(15) NULL DEFAULT NULL,
`deptest.departmentt_id` BIGINT(20) NULL DEFAULT NULL,
PRIMARY KEY (`employee_id`),
INDEX `FK_DEPT` (`dept_id`),
CONSTRAINT `FK_DEPT` FOREIGN KEY (`dept_id`) REFERENCES `department` (`dept_id`)
);
</code></pre>
<hr>
<p>department.hbm.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.atom.HibernateOne">
<class name="com.atom.HibernateOne.Department" table="department">
<id name="departmentId" type="java.lang.Long" column="dept_id" >
<generator class="identity" />
</id>
<property name="departmentName" column="DEPT_NAME"/>
<set name="employees"
table="EMPLOYEEO"
inverse="true"
fetch="select">
<key>
<column name="dept_id"
not-null="true" />
</key>
<one-to-many class="com.atom.HibernateOne.EmployeeO" />
</set>
</class>
</hibernate-mapping>
</code></pre>
<hr>
<p>employeeo.hbm.xml</p>
<p>
</p>
<p></p>
<pre><code> <class name="com.atom.HibernateOne.EmployeeO" table="EMPLOYEE">
<id name="employeeId" column="EMPLOYEE_ID">
</id>
<property name="firstname" column="FIRSTNAME"/>
<property name="lastname" column="LASTNAME" />
<property name="birthDate" type="date" column="BIRTH_DATE" />
<property name="cellphone" column="CELL_PHONE" />
<many-to-one name="department" class="com.atom.HibernateOne.Department" fetch="select">
<column name="dept_id" not-null="true" />
</many-to-one>
</class>
</code></pre>
<p></p>
<p><strong>* Initial SessionFactory creation failed.org.hibernate.HibernateException: Missing column: dept_id*</strong></p>
<p>I am not able to understand the occurrence of error </p>
| 1 | 1,681 |
SQLite subtract time difference between two tables if there is a match
|
<p>I need some help with a SQLite Query. I have two tables, a table called 'production' and a table called 'pause':</p>
<pre><code>CREATE TABLE production (
date TEXT,
item TEXT,
begin TEXT,
end TEXT
);
CREATE TABLE pause (
date TEXT,
begin TEXT,
end TEXT
);
</code></pre>
<p>For every item which is produced, an entry in the table production with the current date, the start time and the end time (two timestamps in the format HH:MM:SS) is created. So let's assume, the production table looks like: </p>
<pre><code>+------------+-------------+------------+----------+
| date | item | begin | end |
+------------+-------------+------------+----------+
| 2013-07-31 | Item 1 | 06:18:00 | 08:03:05 |
| 2013-08-01 | Item 2 | 06:00:03 | 10:10:10 |
| 2013-08-01 | Item 1 | 10:30:15 | 14:20:13 |
| 2013-08-01 | Item 1 | 15:00:10 | 16:00:00 |
| 2013-08-02 | Item 3 | 08:50:00 | 15:00:00 |
+------------+-------------+------------+----------+
</code></pre>
<p>The second table also contains a date and a start and an end time. So let's assume, the 'pause' table looks like:</p>
<pre><code>+------------+------------+----------+
| date | begin | end |
+------------+------------+----------+
| 2013-08-01 | 08:00:00 | 08:30:00 |
| 2013-08-01 | 12:00:00 | 13:30:00 |
| 2013-08-02 | 10:00:00 | 10:30:00 |
| 2013-08-02 | 13:00:00 | 14:00:00 |
+------------+------------+----------+
</code></pre>
<p>Now I wanna get a table, which contains the time difference between the production begin and end time for every item. If there is a matching entry in the 'pause' table, the pause time should be subtracted. </p>
<p>So basically, the end result should look like:</p>
<pre><code>+------------+------------+-------------------------------------------------+
| date | Item | time difference (in seconds), excluding pause |
+------------+------------+-------------------------------------------------+
| 2013-07-31 | Item 1 | 6305 |
| 2013-08-01 | Item 1 | 12005 |
| 2013-08-01 | Item 2 | 13207 |
| 2013-08-02 | Item 3 | 16800 |
+------------+------------+-------------------------------------------------+
</code></pre>
<p>I am not really sure, how I can accomplish it with SQLite. I know that it is possible to do this sort of calculation with Python, but in the end I think it would be better to let the database do the calculations. Maybe someone of you could give me a hint on how to solve this problem. I tried different queries, but I always ended up with different results than I expected. </p>
| 1 | 1,058 |
Heading identification with Regex
|
<p>I'm wondering how I can identify headings with differing numerical marking styles with one or more regular expressions assuming sometimes styles overlap between documents. The goal is to extract all the subheadings and data for a specific heading in each file, but these files aren't standardized. Is regular expressions even the right approach here?</p>
<p>I'm working on a program that parses a .pdf file and looks for a specific section. Once it finds the section it finds all subsections of that section and their content and stores it in a <code>dictionary<string, string></code>. I start by reading the entire pdf into a string, and then use this function to locate the "marking" section.</p>
<pre><code>private string GetMarkingSection(string text)
{
int startIndex = 0;
int endIndex = 0;
bool startIndexFound = false;
Regex rx = new Regex(HEADINGREGEX);
foreach (Match match in rx.Matches(text))
{
if (startIndexFound)
{
endIndex = match.Index;
break;
}
if (match.ToString().ToLower().Contains("marking"))
{
startIndex = match.Index;
startIndexFound = true;
}
}
return text.Substring(startIndex, (endIndex - startIndex));
}
</code></pre>
<p>Once the marking section is found, I use this to find subsections.</p>
<pre><code>private Dictionary<string, string> GetSubsections(string text)
{
Dictionary<string, string> subsections = new Dictionary<string, string>();
string[] unprocessedSubSecs = Regex.Split(text, SUBSECTIONREGEX);
string title = "";
string content = "";
foreach(string s in unprocessedSubSecs)
{
if(s != "") //sometimes it pulls in empty strings
{
Match m = Regex.Match(s, SUBSECTIONREGEX);
if (m.Success)
{
title = s;
}
else
{
content = s;
if (!String.IsNullOrWhiteSpace(content) && !String.IsNullOrWhiteSpace(title))
{
subsections.Add(title, content);
}
}
}
}
return subsections;
}
</code></pre>
<p>Getting these methods to work the way I want them to isn't an issue, the problem is getting them to work with each of the documents. <strong>I'm working on a commercial application so any API that requires a license isn't going to work for me.</strong>
These documents are anywhere from 1-16 years old, so the formatting varies quite a bit. <a href="https://regex101.com/r/6RckWL/5" rel="nofollow noreferrer">Here is a link to some sample headings and subheadings from various documents.</a> But to make it easy, here are the regex patterns I'm using:</p>
<ul>
<li>Heading: <code>(?m)^(\d+\.\d+\s[ \w,\-]+)\r?$</code></li>
<li>Subheading: <code>(?m)^(\d\.[\d.]+ ?[ \w]+) ?\r?$</code></li>
<li>Master Key: <code>(?m)^(\d\.?[\d.]*? ?[ \-,:\w]+) ?\r?$</code></li>
</ul>
<p>Since some headings use the subheading format in other documents I am unable to use the same heading regex for each file, and the same goes for my subheading regex.</p>
<p>My alternative to this was that I was going to write a master key (listed in the regex link) to identify all types of headings and then locate the last instance of a numeric character in each heading (5.1.X) and then look for 5.1.X+1 to find the end of that section.</p>
<p>That's when I ran into another problem. Some of these files have absolutely no proper structure. Most of them go from 5.2->7.1.5 (5.2->5.3/6.0 would be expected)</p>
<p>I'm trying to wrap my head around a solution for something like this, but I've got nothing... I am open to ideas not involving regex as well.</p>
<p>Here is my updated <code>GetMarkingSection</code> method:</p>
<pre><code>private Dictionary<string, string> GetMarkingSection(string text)
{
var headingRegex = HEADING1REGEX;
var subheadingRegex = HEADING2REGEX;
Dictionary<string, string> markingSection = new Dictionary<string, string>();
if (Regex.Matches(text, HEADING1REGEX, RegexOptions.Multiline | RegexOptions.Singleline).Count > 0)
{
foreach (Match m in Regex.Matches(text, headingRegex, RegexOptions.Multiline | RegexOptions.Singleline))
{
if (Regex.IsMatch(m.ToString(), HEADINGMASTERKEY))
{
if (m.Groups[2].Value.ToLower().Contains("marking"))
{
var subheadings = Regex.Matches(m.ToString(), subheadingRegex, RegexOptions.Multiline | RegexOptions.Singleline);
foreach (Match s in subheadings)
{
markingSection.Add(s.Groups[1].Value + " " + s.Groups[2].Value, s.Groups[3].Value);
}
return markingSection;
}
}
}
}
else
{
headingRegex = HEADING2REGEX;
subheadingRegex = HEADING3REGEX;
foreach(Match m in Regex.Matches(text, headingRegex, RegexOptions.Multiline | RegexOptions.Singleline))
{
if(Regex.IsMatch(m.ToString(), HEADINGMASTERKEY))
{
if (m.Groups[2].Value.ToLower().Contains("marking"))
{
var subheadings = Regex.Matches(m.ToString(), subheadingRegex, RegexOptions.Multiline | RegexOptions.Singleline);
foreach (Match s in subheadings)
{
markingSection.Add(s.Groups[1].Value + " " + s.Groups[2].Value, s.Groups[3].Value);
}
return markingSection;
}
}
}
}
return null;
}
</code></pre>
<p>Here are some example PDF files:
<a href="https://i.stack.imgur.com/ifAsz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifAsz.png" alt="Style 1"></a>
<a href="https://i.stack.imgur.com/z1ApI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z1ApI.png" alt="Style 2"></a></p>
| 1 | 2,443 |
How to retrieve browser session data in ASP.Net MVC Controller?
|
<p>I'm having a pretty tough time with this issue. I've done a lot of research but haven't found anything that works!</p>
<p><strong>What I want to do:</strong>
I want to use javascript to capture the user's timezone and utc timezone offset, store these two pieces of data in the browsers session, and then retrieve them in the controller.</p>
<p><strong>What is working:</strong>
My javascript is working to extract the user's timezone and timezone offset and save these two variables into the session. The following is my working JS:</p>
<pre><code><script type="text/javascript">
window.onload = function () {
var UserTime = new Date();
var stringtz = UserTime.toString();
var tzstart = stringtz.indexOf("(") + 1;
var tzend = stringtz.indexOf(")");
var userTZ = stringtz.slice(tzstart, tzend);
sessionStorage.setItem("userTZOffset", UserTime.getTimezoneOffset().toString());
sessionStorage.setItem("userTZ", userTZ);
};
</script>
</code></pre>
<p><strong>What is not working:</strong>
When the user signs in, I want to grab the two variables (userTZ and userTZOffset) saved in the session and create claims for them. However, when I try to pull these into my controller I get null as the values. Upon further inspection, I can see the session timeout, id, etc but the keys and values are blank.</p>
<p>Here is a snipped of code from my sign in action in my controller:</p>
<pre><code> var claims = UserManager.GetClaims(user.Id);
var timezoneclaim = claims.First(c => c.Type == "UserTZ");
UserManager.RemoveClaim(user.Id, timezoneclaim);
var timezoneoffsetclaim = claims.First(c => c.Type == "UserTZOffset");
UserManager.RemoveClaim(user.Id, timezoneoffsetclaim);
var test = HttpContext.Session["userTZ"];
var test2 = HttpContext.Session["userTZOffset"];
UserManager.AddClaim(user.Id, new Claim("UserTZ", test.ToString()));
UserManager.AddClaim(user.Id, new Claim("UserTZOffset", test2.ToString()));
</code></pre>
<p>I set breakpoints on this and walk through the code but everytime, test and test2 are null. When I look into the session itself on the breakpoints I see SessionId, Timeout, etc but the count is 0 and the Key count is 0.</p>
<p>I've tried:</p>
<ol>
<li>Adding remove name="Session" and add name="Session" type="System.Web.SessionState.SessionStateModule" to my webconfig based on a similar issue I found <a href="https://stackoverflow.com/questions/218057/httpcontext-current-session-is-null-when-routing-requests">here</a>.</li>
<li>I tried adding the Microsoft.Aspnet.Session nuget package and following <a href="http://benjii.me/2015/07/using-sessions-and-httpcontext-in-aspnet5-and-mvc6/" rel="nofollow noreferrer">this</a> tutorial but my project's startup.cs doesn't have a ConfigureServices section and adding my own didn't work either.</li>
<li>I set the session state to InProc in the webconfig based on what I found <a href="https://stackoverflow.com/questions/28081004/mvc-5-session-is-null">here</a> but again, nothing changed.</li>
</ol>
<p>Thoughts?</p>
| 1 | 1,049 |
Entity Framework Foreign Key (or lack thereof)
|
<p>So I have pouring of this code forever, trying to figure this out... I am using Entity Framework 1.0 with ASP.NET MVC in .NET 3.5 SP1 with EFPocoAdapter (so separate Poco classes).</p>
<p>So I have the following code for one of Controllers:</p>
<pre><code> [AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditUser(int? id, FormCollection form)
{
var user = new User();
using (var db = new UMSEntities { DeferredLoadingEnabled = false })
{
if (id != null)
{
user = db.Users.FirstOrDefault(p => p.UserID.Equals((int) id));
db.LoadProperty(user, p => p.UserProfiles);
db.LoadProperty(user, p => p.UserCompanyProfile);
}
else
{
user.UserGuid = Guid.NewGuid();
user.DateCreated = DateTime.Now;
user.DateLastActivity = DateTime.Now;
user.DateModified = DateTime.Now;
user.Password = "demo";
user.Version = 0;
user.SecretAnswer = "";
user.SecretQuestion = "";
user.IsApproved = true;
user.IsActive = true;
user.UserProfiles = new UserProfile();
user.UserCompanyProfile = new UserCompanyProfile
{
EmployeeID = "",
HireDate = DateTime.Now,
Title = "",
UserCode = "",
Company = db.Companies.First(p => p.CompanyID == 8)
};
db.Users.InsertOnSaveChanges(user);
}
TryUpdateModel(user);
db.SaveChanges();
}
</code></pre>
<p>Editing an exist user works perfect (notice if id != null). However, it is the portion of code that adds a new user. It works until I get to the portion of code where I add the UserCompanyProfile to the user object. If I comment this code out, it works just fine. The problem arises when I try to attach a company to the UserCompanyProfile by querying the database-- I get this error.</p>
<pre><code>Entities in 'UMSEntities.UserCompanyProfiles' participate in the 'FK__UserCompa__Compa__25869641' relationship. 0 related 'Companies' were found. 1 'Companies' is expected.
</code></pre>
<p>By the way, it does in fact return one Company object (it is of type PocoProxies.CompanyProxy). Any help would certainly be appreciated!</p>
| 1 | 1,170 |
CSS layout zoom issue
|
<p>My issue is that when I zoom in or out of the page (in all the browsers I tried), only some parts of it are displayed as zoomed (the contents that are in the divs, but not the divs themselves). I put the borders to show it easily.</p>
<p>When I searched for a solution, all of them mentioned that it is because of fixed width values by using pixels (px). So, I used <code>%</code> when putting values to width and height; but still, the issue remains...</p>
<p><strong>Here are some screenshots to illustrate my problem:</strong></p>
<p><strong>When zoomed-in:</strong></p>
<p><img src="https://i.stack.imgur.com/gXZtD.jpg" alt="zoomed-in"></p>
<p><strong>When zoomed-out:</strong></p>
<p><img src="https://i.stack.imgur.com/CIE7W.jpg" alt="zoomed-out"></p>
<p><strong>Here is my code:</strong></p>
<p><strong>HTML:</strong></p>
<pre><code><html>
<head>
<link href="style.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="title_bar">
some txt here
<div id="title_img"></div>
<div id="title_txt"></div>
<div id="menu_navigation"></div>
</div>
<div id="title_bar_2">
some txt here
</div>
<div id="container_columns">
<div id="column_1">
<span id="column_1_content">some txt here</span>
</div>
<div id="column_2">
<span id="column_2_content">some txt here</span>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>html body
{
margin: 0;
width: 100%;
height: 100%;
background-color:#f2f2f2;
}
div#title_bar
{
height:4%;
width:76%;
margin:auto;
margin-top:4%;
border-style:solid;
border-color:blue;
}
div#title_bar_2
{
text-align:center;
height:44%;
width:76%;
margin:auto;
margin-top:2%;
border-style:solid;
border-color:blue;
}
div#title_bar img
{
margin-top:1%;
float:left;
}
div#title_txt
{
float:left;
margin-left:2%;
margin-top:1.4%;
font-style: italic;
font-family:verdana;
font-size: 16px;
}
div#menu_navigation
{
float:left;
margin-left:35%;
margin-top:1.4%;
font-size:19px;
}
div#container_columns
{
margin:auto;
width:76.5%;
margin-top:2%;
height:27%;
border-style:solid;
border-color:blue;
}
div#column_1
{
height:100%;
width:49%;
float:left;
border-style:solid;
border-color:blue;
}
div#column_2
{
margin-left:1%;
width:48%;
float:left;
height:100%;
}
</code></pre>
| 1 | 1,354 |
Android default button styling not working
|
<p>I'm trying to set up my styles to make all buttons a particular color combination, specifically blue with white text. Here's my main styles.xml:</p>
<pre><code><resources>
<style name="CustomTheme" parent="MaterialDrawerTheme.Light.DarkToolbar">
<!-- various items -->
<item name="android:buttonStyle">@style/ButtonStyle</item>
</style>
<!-- a couple of other styles -->
<style name="ButtonStyle" parent="android:style/Widget.Button">
<item name="android:textSize">19sp</item>
<item name="android:textColor">@color/primaryTextContrast</item>
<item name="android:background">@color/primary</item>
</style>
</resources>
</code></pre>
<p>And in the manifest:</p>
<pre><code> <application
android:name=".CustomApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/application_name"
android:theme="@style/CustomTheme">
</code></pre>
<p><code>color/primary</code> is dark blue, and <code>color/primaryTextContrast</code> is white. On Lollipop, the button looks perfect. On a 4.1 device, it's light gray with black text. Every resource I've found for doing this looks exactly like what I'm doing so I don't know what I'm missing here.</p>
<p>I'm having a similar issue with controlling text size in the base style definition as well.</p>
<p>Update: here are the colors.</p>
<pre><code><resources>
<color name="primary">#3F51B5</color>
<color name="dark">#303F9F</color>
<color name="accent">#FFCA28</color>
<color name="background">@android:color/white</color>
<!-- Color for text displayed on top of the primary or dark color -->
<color name="primaryTextContrast">@android:color/white</color>
<!-- Color for text displayed on the background color (which I think will always be white) -->
<color name="basicText">@color/primary</color>
<!-- Color for text displayed on the accent color -->
<color name="accentText">#303F9F</color>
</resources>
</code></pre>
<p>Here's v19/styles.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="FullscreenTheme" parent="MaterialDrawerTheme.Light.DarkToolbar.TranslucentStatus">
<item name="android:windowTranslucentNavigation">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
</resources>
</code></pre>
<p>Here's v21:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="CustomTheme">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</resources>
</code></pre>
<p>I don't think either of these is what's making it work properly on 5.1.</p>
| 1 | 1,404 |
Bootstrap 3.0: Full-Width Color Background, Compact Columns in Center
|
<p>I was looking to make a striped business theme, similar to the one created by W3Schools. The theme can be found <a href="http://www.w3schools.com/bootstrap/bootstrap_theme_company.asp" rel="nofollow">here</a>. It is characterized by horizontal sections, separated by different background colors.</p>
<p>The one issue I had with it was that the columns in Services, Portfolio and Pricing, spanned pretty much the full width of the page, which I did not think looked great, particularly for the three pricing boxes, which i feel should be much narrower and still centered. Let's take those pricing boxes as the example for the purpose of the questions.</p>
<p>So, I embarked upon the task of squeezing these three pricing boxes into a narrower shape, centered on the page, while still maintaining the full-width alternating background color. I came up with three ways to do it:</p>
<h2>1) Place a Container inside a Container-Fluid:</h2>
<pre><code><div id="pricing" class="container-fluid">
<div class="container">
<div class="row">
<div class="col-sm-4 col-xs-12">
BlaBlaBla
</div>
...
</div>
</div>
</div>
</code></pre>
<hr>
<h2>2) Make the following additions/changes to the css and html:</h2>
<pre><code>.fixed-width {
display: inline-block;
float: none;
width: 300px;
}
.row-centered {
text-align: center;
}
</code></pre>
<p>-</p>
<pre><code><div id="pricing" class="container-fluid">
<div class="row row-centered">
<div class="col-sm-4 col-xs-12 fixed-width">
BlaBlaBla
</div>
...
</div>
</div>
</code></pre>
<hr>
<h2>3) 3x col-sm-2, with empty columns on each side</h2>
<p>Keep the container-fluid layout, but instead of having three <code>col-sm-4</code>, I have an empty <code>col-sm-3</code>, three <code>col-sm-2</code>, and finally an empty <code>col-sm-3</code> (for a total of 12 columns).</p>
<hr>
<h2>4) 3x col-sm-2, with offset-3 to center</h2>
<p>Instead of having three col-sm-4, I have one <code>col-sm-2 col-sm-offset-3</code>, then two <code>col-sm-2</code> (this does not add to 12, but i center with offset).**</p>
<hr>
<p>The problem with both (3) and (4) is that once i shrink the browser window, the boxes become too small before they wrap to the next line (i.e. the text flows out of the box). In (4) it seems if i use <code>container</code> (as opposed to <code>container-fluid</code>), the boxes become too narrow in full-screen even.</p>
<p>What is the correct way of doing this? I assume this is an issue almost everyone making business websites stumbles across, yet I was not able to find the answer online having worked on it for hours.</p>
<p>Thanks in advance,</p>
<p>Magnus</p>
| 1 | 1,070 |
Errors while installing python autopy
|
<p>Hey I have looked at and old question here but it doesn't answer my question</p>
<p>I have installed libpng, then try to install autopy and get complie errors.</p>
<p>I am not great at python yet so I am not sure on how to fix them.</p>
<pre><code>Ashley:~ ashleyhughes$ sudo easy_install autopy
Searching for autopy
Reading http://pypi.python.org/simple/autopy/
Reading http://www.autopy.org
Best match: autopy 0.51
Downloading http://pypi.python.org/packages/source/a/autopy/autopy-0.51.tar.gz#md5=b92055aa2a3712a9c3b4c874014b450e
Processing autopy-0.51.tar.gz
Running autopy-0.51/setup.py -q bdist_egg --dist-dir /tmp/easy_install-U9uWoj/autopy-0.51/egg-dist-tmp-hdjtIx
clang: warning: argument unused during compilation: '-mno-fused-madd'
clang: warning: argument unused during compilation: '-mno-fused-madd'
clang: warning: argument unused during compilation: '-mno-fused-madd'
clang: warning: argument unused during compilation: '-mno-fused-madd'
clang: warning: argument unused during compilation: '-mno-fused-madd'
src/screengrab.c:48:26: warning: implicit declaration of function
'CGDisplayBitsPerPixel' is invalid in C99
[-Wimplicit-function-declaration]
bitsPerPixel = (uint8_t)CGDisplayBitsPerPixel(displayID);
^
src/screengrab.c:191:2: warning: 'CGLSetFullScreen' is deprecated
[-Wdeprecated-declarations]
CGLSetFullScreen(glContext);
^
src/screengrab.c:194:2: warning: implicit declaration of function 'glReadBuffer'
is invalid in C99 [-Wimplicit-function-declaration]
glReadBuffer(GL_FRONT);
^
src/screengrab.c:194:15: error: use of undeclared identifier 'GL_FRONT'
glReadBuffer(GL_FRONT);
^
src/screengrab.c:197:2: warning: implicit declaration of function 'glFinish' is
invalid in C99 [-Wimplicit-function-declaration]
glFinish();
^
src/screengrab.c:199:6: warning: implicit declaration of function 'glGetError'
is invalid in C99 [-Wimplicit-function-declaration]
if (glGetError() != GL_NO_ERROR) return NULL;
^
src/screengrab.c:199:22: error: use of undeclared identifier 'GL_NO_ERROR'
if (glGetError() != GL_NO_ERROR) return NULL;
^
src/screengrab.c:207:2: warning: implicit declaration of function
'glPopClientAttrib' is invalid in C99 [-Wimplicit-function-declaration]
glPopClientAttrib(); /* Clear attributes previously set. */
^
src/screengrab.c:223:2: warning: implicit declaration of function
'glPushClientAttrib' is invalid in C99 [-Wimplicit-function-declaration]
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
^
src/screengrab.c:223:21: error: use of undeclared identifier
'GL_CLIENT_PIXEL_STORE_BIT'
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
^
src/screengrab.c:225:2: warning: implicit declaration of function
'glPixelStorei' is invalid in C99 [-Wimplicit-function-declaration]
glPixelStorei(GL_PACK_ALIGNMENT, BYTE_ALIGN); /* Force alignment. */
^
src/screengrab.c:225:16: error: use of undeclared identifier 'GL_PACK_ALIGNMENT'
glPixelStorei(GL_PACK_ALIGNMENT, BYTE_ALIGN); /* Force alignment. */
^
src/screengrab.c:226:16: error: use of undeclared identifier
'GL_PACK_ROW_LENGTH'
glPixelStorei(GL_PACK_ROW_LENGTH, 0);
^
src/screengrab.c:227:16: error: use of undeclared identifier 'GL_PACK_SKIP_ROWS'
glPixelStorei(GL_PACK_SKIP_ROWS, 0);
^
src/screengrab.c:228:16: error: use of undeclared identifier
'GL_PACK_SKIP_PIXELS'
glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
^
src/screengrab.c:235:2: warning: implicit declaration of function 'glReadPixels'
is invalid in C99 [-Wimplicit-function-declaration]
glReadPixels(x, y, width, height,
^
src/screengrab.c:236:30: error: use of undeclared identifier 'GL_BGRA'
MMRGB_IS_BGR ? GL_BGRA : GL_RGBA,
^
src/screengrab.c:236:40: error: use of undeclared identifier 'GL_RGBA'
MMRGB_IS_BGR ? GL_BGRA : GL_RGBA,
^
9 warnings and 9 errors generated.
error: Setup script exited with error: command 'clang' failed with exit status 1
</code></pre>
<p>Can anyone help. I need autopy as it works on multiple platforms</p>
<p>I used ethan.tira-thompson.com/Mac_OS_X_Ports.html to install libpng</p>
<p>Have xcode installed with command line tools as well</p>
| 1 | 1,997 |
AVCodecContext settings for H264 (1080i)
|
<p>I'm trying to configure x264 for 1080i capturing. Most of these settings below are found in different examples. However, compiled together they don't work. ffmpeg API reports no error, but <code>avcodec_encode_video()</code> always returns zero.</p>
<p>Some of the numbers are strange to me... for example, <code>gop_size</code>. Isn't 250 too high?</p>
<p>Event you can't offer the final answer, I'm still interested in any kind of comment on this subject. </p>
<pre><code>pCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecContext->codec_id = CODEC_ID_H264;
pCodecContext->coder_type = FF_CODER_TYPE_AC;
pCodecContext->flags |= CODEC_FLAG_LOOP_FILTER | CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT;
pCodecContext->me_cmp |= 1;
pCodecContext->partitions |= X264_PART_I8X8 | X264_PART_I4X4 | X264_PART_P8X8 | X264_PART_B8X8;
pCodecContext->me_method = ME_UMH;
pCodecContext->me_subpel_quality = 8;
pCodecContext->me_range = 16;
pCodecContext->bit_rate = 10 * 1024 * 1024; // 10 Mbps??
pCodecContext->width = 1920;
pCodecContext->height = 1080;
pCodecContext->time_base.num = 1; // 25 fps
pCodecContext->time_base.den = 25; // 25 fps
pCodecContext->gop_size = 250; // 250
pCodecContext->keyint_min = 25;
pCodecContext->scenechange_threshold = 40;
pCodecContext->i_quant_factor = 0.71f;
pCodecContext->b_frame_strategy = 1;
pCodecContext->qcompress = 0.6f;
pCodecContext->qmin = 10;
pCodecContext->qmax = 51;
pCodecContext->max_qdiff = 4;
pCodecContext->max_b_frames = 3;
pCodecContext->refs = 4;
pCodecContext->directpred = 3;
pCodecContext->trellis = 1;
pCodecContext->flags2 |= CODEC_FLAG2_WPRED | CODEC_FLAG2_MIXED_REFS | CODEC_FLAG2_8X8DCT | CODEC_FLAG2_FASTPSKIP; // wpred+mixed_refs+dct8x8+fastpskip
pCodecContext->weighted_p_pred = 2; // not implemented with interlaced ??
pCodecContext->crf = 22;
pCodecContext->pix_fmt = PIX_FMT_YUV420P;
pCodecContext->thread_count = 0;
</code></pre>
| 1 | 1,304 |
AngularJs datatable dynamic table change
|
<p>I am working on a project and i want to do some things which are new to me. I am new in AngularJS and newer in angular data tables.</p>
<p>I got angular data table from <a href="http://l-lin.github.io/angular-datatables/#/welcome" rel="nofollow"><strong>here</strong></a> and is a little bit tricky for me because i don't really know how to use it. Examples are not very explanatory for me.</p>
<p>What i want to do:</p>
<ul>
<li><p>i have a sigle page with some checkboxes on the left</p></li>
<li><p>on the right i want a data table with data provided by server after user clicks on a checkbox</p></li>
<li><p>data table must change dinamicaly because depends on the request i have other headers for data table. For example when user click on "role" objects returned have only 2 fields id and role, i want to render role column but not id. When user clicks on "users" data returned by server has multiple objects which have much more fields, for example : "accNonExp", "accNonLocked", "email", "username" and others.</p></li>
</ul>
<p>How can i do this ?</p>
<p>here is my conde right now :</p>
<p>js :</p>
<pre><code>depo.controller('masterMainController', ['$scope', '$http', function ($scope, $http) {
$scope.listOfTables = null;
$scope.tableData = {};
$scope.onClick = function(){
$scope.tableData = getTableData($scope.valueSelected);
};
$http.post('/master/listOfTables').success(function (response) {
$scope.listOfTables = response;
console.log(response);
});
function getTableData(table) {
$http.post('/master/tableData/' + table).success(function (response) {
console.log(response);
return response;
});
}
$scope.dataTable = function(DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromJson($scope.tableData)
.withPaginationType('full_numbers');
/* vm.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
DTColumnBuilder.newColumn('lastName').withTitle('Last name').notVisible()
];*/
}
}]);
</code></pre>
<p>JSP:</p>
<pre><code><%@ include file="/WEB-INF/views/includes/onlyForLoggedUsers.jsp" %>
<html>
<head>
<title>Main Master</title>
</head>
<script content="text/javascript" src="/res/custom_script/admin/masterMain.js"></script>
<body ng-app="depo">
<div class="container-fluid" ng-controller="masterMainController">
<p class="logout_paragraph">Logged as <strong>${pageContext.request.userPrincipal.name}</strong> | <a
id="logout_link" onclick="formSubmit()">Logout</a></p>
<form action="/logout" method="post" id="logoutForm" style="display: none;">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<div class="jumbotron">
<h2>Welcome !</h2>
</div>
<div>
<div id="divChkListOfTables" class="admin_left_menu pre-scrollable col-md-2">
<div id="chkListOfTables" class="admin_tables_list radio">
<h4>Tables</h4>
<label ng-repeat="table in listOfTables.tables" class="admin_tables_list_chk_box">
<input type="radio" name="chkTablesRadio" ng-model="$parent.valueSelected" ng-change="onClick()"
ng-value="table" class="radio-button"> {{table}}
</label>
</div>
</div>
<div id="admin_data_table" class="col-md-10">
<table datatable="dataTable" dt-options="masterMainController.dtOptions" dt-columns="masterMainController.dtColumns" class="row-border hover">
</table>
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p>Spring RestController:</p>
<pre><code>@RestController
@RequestMapping(value = "/master")
public class MasterMainRest {
@Autowired
UnitService unitService;
@Autowired
RoleService roleService;
@Autowired
UsersService usersService;
@RequestMapping(value = "/listOfTables", method = RequestMethod.POST)
public MasterTablesDTO getListOfTables(){
List<String> tables = new ArrayList<>();
tables.add("unit");
tables.add("role");
tables.add("users");
MasterTablesDTO masterTablesDTO = new MasterTablesDTO();
masterTablesDTO.setTables(tables);
return masterTablesDTO;
}
@RequestMapping(value = "/tableData/{table}", method = RequestMethod.POST)
public List getTablesData(@PathVariable String table){
List list = null;
switch (table){
case "unit":
list = unitService.findAll();
break;
case "role":
list = roleService.findAll();
break;
case "users":
list = usersService.findAll();
break;
}
return list;
}
}
</code></pre>
<p>When i reach this page i gat this error :</p>
<pre><code>TypeError: Cannot read property 'aDataSort' of undefined
at U (jquery.dataTables.min.js:63)
at xa (jquery.dataTables.min.js:67)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:91)
at Function.n.extend.each (jquery-2.1.3.min.js:2)
at n.fn.n.each (jquery-2.1.3.min.js:2)
at m [as dataTable] (jquery.dataTables.min.js:83)
at h.fn.DataTable (jquery.dataTables.min.js:159)
at Object.g [as renderDataTableAndEmitEvent] (angular-datatables.min.js:6)
at Object.h [as doRenderDataTable] (angular-datatables.min.js:6)
at Object.d.render (angular-datatables.min.js:6)
</code></pre>
<p>Yes i know this error is beause $scope.tableData is empty, or this is what i read on some forums.
How can i make first checkbox checked and $scope.tableData loaded with data acording to that checkbox checked ?</p>
<p>Thank you in advance !</p>
| 1 | 2,654 |
CollectionView Cell size to fit Label
|
<p>I have set up a collection view using which scrolls horizontally and displays the elements in the ‘companies’ array. </p>
<p><a href="https://i.stack.imgur.com/NSAD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NSAD8.png" alt="enter image description here"></a></p>
<p>The cells automatically resize relative to the label width. </p>
<p>I have used the code & storyboard constraints below to achieve this:</p>
<pre class="lang-html prettyprint-override"><code>class addTextStatus: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var companies: [String] = ["Everyone","Limited", "Friends", "Only Me", "Test Length Cells", ]
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var userImage: UIImageView!
override func viewDidLoad(){
collectionView.register(UINib.init(nibName: "statusCompanyCollectionView", bundle: nil), forCellWithReuseIdentifier: "cell4")
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: 1,height: 1)
}
userImage.layer.masksToBounds = false
userImage.layer.cornerRadius = userImage.frame.height/2
userImage.clipsToBounds = true
}
@IBOutlet weak var backButton: UIButton!
@IBAction func backButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.default
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.companies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: "cell4", for: indexPath) as! statusCompanyCollectionView
cell4.company.text = self.companies[indexPath.item]
return cell4
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/tD2Xf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tD2Xf.png" alt="enter image description here"></a></p>
<p>However the issue is that when I add a UIImage view behind the label and assign constraints which dictate that it should be the same size and position as the label do I get the unexpected result below:</p>
<p><a href="https://i.stack.imgur.com/Gtfhj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gtfhj.png" alt="enter image description here"></a></p>
<p>When in actuality I would like to achieve the following:</p>
<p><a href="https://i.stack.imgur.com/mAz1H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mAz1H.png" alt="enter image description here"></a></p>
<p>The constraints I have used to apply the image behind are below:</p>
<p><a href="https://i.stack.imgur.com/YgTdq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YgTdq.png" alt="enter image description here"></a></p>
<p>Interestingly when I use a UIView instead of a UIImage view it works as expected, I do however need to use image views in this instance.</p>
<p>Why is this occurring and how do I resolve this issue? </p>
| 1 | 1,143 |
CSS Bug with inline ul li in IE7
|
<p>I've got a little issue with a inline menu, bug only appears in ie7. The only menu li that has another menu underneath it, is not inline with the rest, the rest seem to appear pushed down.</p>
<p>HTML</p>
<pre><code><div id="topnav">
<ul id="jsddm">
<li id="">
<a id="" href="/">Home</a>
</li>
<li id="">
<a href="/about.aspx">About</a>
<ul style="visibility: hidden;">
<li>
<a href="/about/board.aspx">Board</a>
</li>
<li>
<a href="/about/contact.aspx">Contact</a>
</li>
</ul>
</li>
<li>
<a href="/practices.aspx">Practices</a>
</li>
<li>
<a href="/how-we-work.aspx">How we work</a>
</li>
<li>
<a href="/patients.aspx">Patients</a>
</li>
<li>
<a href="/news-links.aspx">News &amp; Links</a>
</li>
<li>
<a href="/link.aspx">Link</a>
</li>
</ul>
</div>
</code></pre>
<p>CSS</p>
<pre><code> #jsddm
{ margin: 0;
padding: 0;
width: 100%;
}
#jsddm li
{
display: inline-block;
list-style: none;
font: 12px Tahoma, Arial;
width: 100px;
text-align: center;
}
*+html #jsddm li { display:inline }
* html #jsddm li { display:inline }
#jsddm ul li
{
display: block;
font: 12px Tahoma, Arial;
}
#jsddm li ul
{
margin: 0 0 0 0;
padding: 0;
position: absolute;
visibility: hidden;
border-top: 0px solid white;
*margin: 0 0 0 -50px; /* IE 7 and below */
/* margin: 0 0 0 -50px\9; IE 8 and below */
}
#jsddm ul li ul li
{
font: 12px Tahoma, Arial
}
#jsddm li a
{
display: block;
background: #009EE0;
padding: 0;
line-height: 28px;
text-decoration: none;
border-right: 0px solid white;
width: 70px;
color: #EAFFED;
white-space: nowrap;
font-weight: bold;
width: 100%;
}
#jsddm li a:hover
{ background: #1A4473}
#jsddm li ul li
{
float: none;
*margin: -2px 0 0 0;
*padding:0;
}
+html #jsddm li ul li { }
#jsddm li ul li a
{
width: auto;
background: #009EE0
font-weight: bold;
}
#jsddm li ul li a:hover
{ background: #0E559C }
</code></pre>
<p>It uses a jquery function to display the dropdownmenu but it does'nt effect the static html/css.</p>
<p>Thanks.</p>
| 1 | 1,175 |
Could not find goal 'single' with Maven running mvn package
|
<p>I am trying to compile some java classes with maven to produce an executable jar file that is stand alone</p>
<pre><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>grids</groupId>
<artifactId>grids</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MainMap_Challange</name>
<description>Tickets and Events System</description>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</code></pre>
<p>
</p>
<p>I would like to produce a stand alone jar file like explained here
<a href="https://maven.apache.org/plugins/maven-assembly-plugin/usage.html" rel="nofollow noreferrer">https://maven.apache.org/plugins/maven-assembly-plugin/usage.html</a></p>
<p>The error i get is:</p>
<pre><code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MainMap_Challange 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.335 s
[INFO] Finished at: 2017-12-02T20:08:49Z
[INFO] Final Memory: 5M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Could not find goal 'single' in plugin org.apache.maven.plugins:maven-compiler-plugin:3.5.1 among available goals compile, help, testCompile -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1]
http://cwiki.apache.org/confluence/display/MAVEN/MojoNotFoundException
</code></pre>
<p>when running "mvn package" on the command line</p>
| 1 | 1,106 |
setBackgroundColor() doesn't seem to work
|
<p>I have a <code>RelativeLayout</code> and a <code>Button</code> in my <code>Activity</code>
I want to run a code when I click on the <code>Button</code>, so I wrote the following code:</p>
<pre><code><ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="@drawable/flashlight"
android:onClick="NightSwitch" />
</code></pre>
<p>and then I have the following in my <code>Activity.java</code></p>
<pre><code>public void NightSwitch(View v){
String One = "1"; //states day
String Zero = "0"; //states night
int color1 = getResources().getColor(R.color.darkblue);
int color2 = getResources().getColor(R.color.white);
RelativeLayout rele = (RelativeLayout) findViewById(R.id.RelativeLayout1);
String state = getString(R.string.night_switch);
if(state.equals(One)){
rele.setBackgroundColor(color1);
}
if(state.equals(Zero)){
rele.setBackgroundColor(color2);
}
}
</code></pre>
<h2>Everything is ok, but <code>setBackgroundColor()</code> does not work and causes a crash. also, how can I debug program in a VB style? Is it even possible?</h2>
<p>Logcat :</p>
<p>01-27 17:38:45.606: E/AndroidRuntime(21427): at android.view.View$1.onClick(View.java:3838)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.view.View.performClick(View.java:4475)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.view.View$PerformClick.run(View.java:18786)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.os.Handler.handleCallback(Handler.java:730)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.os.Handler.dispatchMessage(Handler.java:92)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.os.Looper.loop(Looper.java:137)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.app.ActivityThread.main(ActivityThread.java:5493)
01-27 17:38:45.606: E/AndroidRuntime(21427): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 17:38:45.606: E/AndroidRuntime(21427): at java.lang.reflect.Method.invoke(Method.java:525)
01-27 17:38:45.606: E/AndroidRuntime(21427): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
01-27 17:38:45.606: E/AndroidRuntime(21427): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
01-27 17:38:45.606: E/AndroidRuntime(21427): at dalvik.system.NativeStart.main(Native Method)
01-27 17:38:45.606: E/AndroidRuntime(21427): Caused by: java.lang.reflect.InvocationTargetException
01-27 17:38:45.606: E/AndroidRuntime(21427): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 17:38:45.606: E/AndroidRuntime(21427): at java.lang.reflect.Method.invoke(Method.java:525)
01-27 17:38:45.606: E/AndroidRuntime(21427): at android.view.View$1.onClick(View.java:3833)
01-27 17:38:45.606: E/AndroidRuntime(21427): ... 11 more
01-27 17:38:45.606: E/AndroidRuntime(21427): Caused by: java.lang.NullPointerException
01-27 17:38:45.606: E/AndroidRuntime(21427): at com.example.jonathanlseagull.NumOneActivity.NightSwitch(NumOneActivity.java:46)
01-27 17:38:45.606: E/AndroidRuntime(21427): ... 14 more</p>
<p>onCreate();</p>
<pre><code> protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_num_one);
}
</code></pre>
| 1 | 1,345 |
Heroku Login fails
|
<p>I'm getting following error while login to the Heroku using CLI:</p>
<pre><code>Enter your Heroku credentials.
Email: *****@gmail.com
Password (typing will be hidden):
! Heroku client internal error.
! Search for help at: https://help.heroku.com
! Or report a bug at: https://github.com/heroku/heroku/issues/new
Error: connect timeout reached (Excon::Errors::Timeout)
Backtrace: /usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/socket.rb:184:in `rescue in block in connect'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/socket.rb:179:in `block in connect'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/socket.rb:167:in `each'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/socket.rb:167:in `connect'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/ssl_socket.rb:97:in `connect'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/socket.rb:28:in `initialize'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/ssl_socket.rb:9:in `initialize'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/connection.rb:410:in `new'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/connection.rb:410:in `socket'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/connection.rb:122:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/middlewares/mock.rb:42:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/middlewares/instrumentor.rb:22:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/middlewares/base.rb:15:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/middlewares/base.rb:15:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/middlewares/base.rb:15:in `request_call'
/usr/local/heroku/vendor/gems/excon-0.31.0/lib/excon/connection.rb:265:in `request'
/usr/local/heroku/vendor/gems/heroku-api-0.3.17/lib/heroku/api.rb:76:in `request'
/usr/local/heroku/vendor/gems/heroku-api-0.3.17/lib/heroku/api/login.rb:9:in `post_login'
/usr/local/heroku/lib/heroku/auth.rb:80:in `api_key'
/usr/local/heroku/lib/heroku/auth.rb:189:in `ask_for_credentials'
/usr/local/heroku/lib/heroku/auth.rb:221:in `ask_for_and_save_credentials'
/usr/local/heroku/lib/heroku/auth.rb:84:in `get_credentials'
/usr/local/heroku/lib/heroku/auth.rb:41:in `login'
/usr/local/heroku/lib/heroku/command/auth.rb:31:in `login'
/usr/local/heroku/lib/heroku/command.rb:218:in `run'
/usr/local/heroku/lib/heroku/cli.rb:28:in `start'
/usr/local/heroku/bin/heroku:25:in `<main>'
Command: heroku login
HTTP Proxy: http://proxy:8080/
HTTPS Proxy: https://proxy:8080/
Version: heroku-toolbelt/3.6.0 (i686-linux) ruby/1.9.3
</code></pre>
| 1 | 1,522 |
Qt Plugins: :-1: error: cannot find -lpnp_basictools
|
<p>I have been trying for days now to use third party libraries in my simple Qt projects, but to no success so far.</p>
<p>I have tried the <a href="http://doc.qt.io/qt-5/qtwidgets-tools-plugandpaint-app-example.html" rel="nofollow noreferrer">Plug & Paint Example</a> and the <a href="http://doc.qt.io/qt-5/qtwidgets-tools-plugandpaint-plugins-basictools-example.html" rel="nofollow noreferrer">Plug & Paint Basic Tools Example</a>. The <em>tools/plugandpaint/plugins/basictools/basictools.pro</em> compiles OK, but the <em>tools/plugandpaint/app/app.pro</em> fails to compile:</p>
<pre><code>:-1: error: cannot find -lpnp_basictools
collect2.exe:-1: error: error: ld returned 1 exit status
</code></pre>
<p>I have practically copy-pasted the sources from the website to my computer. What could I be missing.</p>
<p><strong>Windows 10</strong></p>
<p><strong>Qt Creator 3.6.0</strong> </p>
<blockquote>
<p><em>Based on Qt 5.5.1 (MSVC 2013, 32 bit)<br>
Built on Dec 15 2015 01:01:38<br>
From revision b52c2f91f5</em> </p>
</blockquote>
<pre><code>LIBS += your_lib_path/your_lib linux:LIBS += -L your_lib_path -lyour_lib win32:LIBS += your_lib_path/your_lib LIBS += -L lib/pcsc/ -lpcsclite LIBS += lib/pcsc/libpcsclite.a 2.add headers INCLUDEPATH += your_include_path INCLUDEPATH += . /usr/local/include)
</code></pre>
<p><a href="http://doc.qt.io/qt-5/qtwidgets-tools-plugandpaint-app-example.html" rel="nofollow noreferrer">app.pro</a></p>
<pre><code>TARGET = plugandpaint
DESTDIR = ..
QT += widgets
HEADERS = interfaces.h \
mainwindow.h \
paintarea.h \
plugindialog.h
SOURCES = main.cpp \
mainwindow.cpp \
paintarea.cpp \
plugindialog.cpp
LIBS = -L../plugins -lpnp_basictools
if(!debug_and_release|build_pass):CONFIG(debug, debug|release) {
mac:LIBS = $$member(LIBS, 0) $$member(LIBS, 1)_debug
win32:LIBS = $$member(LIBS, 0) $$member(LIBS, 1)d
}
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tools/plugandpaint
INSTALLS += target
CONFIG += install_ok # Do not cargo-cult this!
</code></pre>
<p><a href="http://doc.qt.io/qt-5/qtwidgets-tools-plugandpaint-plugins-basictools-example.html" rel="nofollow noreferrer">basictoolsplugin.pro</a></p>
<pre><code>TEMPLATE = lib
CONFIG += plugin static
QT += widgets
INCLUDEPATH += ../../app
HEADERS = basictoolsplugin.h
SOURCES = basictoolsplugin.cpp
TARGET = $$qtLibraryTarget(pnp_basictools)
DESTDIR = ../../plugins
# install
target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tools/plugandpaint/plugins
INSTALLS += target
CONFIG += install_ok # Do not cargo-cult this!
</code></pre>
| 1 | 1,205 |
how can i publish my application in app brain market?
|
<p>i develop one application in android i want to see my app in app brain please help me tell me how can i publish my application in appbrain i.e.., below link.</p>
<pre><code>http://www.appbrain.com/
</code></pre>
<p>i didn't use any permissions in android manifest file</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.org.mmts"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/mmts_icon"
android:label="myproject"
>
<activity
android:label="myproject"
android:name=".AndroidtabActivity"
>
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity" >
<intent-filter >
<action android:name="com.org.mmts.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Touch" >
<intent-filter >
<action android:name="com.org.mmts.Touch" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".InfoPage" >
<intent-filter >
<action android:name="com.org.mmts.InfoPage" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.org.mmts.Display" >
<intent-filter >
<action android:name="com.org.mmts.Display" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
</code></pre>
<p>thanks in advance</p>
| 1 | 1,263 |
Posting JSON from ajax to Struts2 Action
|
<p>Hey I am trying to post JSON from Ajax to Struts2 action class method. Little more info: I am running client on WAMP server and Struts2 on Eclipse Tomcat.</p>
<p>My client side code:</p>
<pre><code><html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var dataObj = {
"data": [{
"id": "1",
"name": "Chris"
}, {
"id": "2",
"name": "Kate"
}, {
"id": "3",
"name": "Blade"
}, {
"id": "4",
"name": "Zack"
}]
};
var data1 = JSON.stringify(dataObj);
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://localhost:8080/Core/add",type: "post", data: data1, dataType: 'json', contentType:"application/json;charset=utf-8",async: true,success:function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
</code></pre>
<p>And this is my Java application stuff:</p>
<p><strong><code>struts.xml</code>:</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="addMenu" namespace="/" extends="json-default">
<action name="registrate" class="com.coreRestaurant.menu.MenuAction">
<result type="json" >
<param name="root">json</param>
</result>
</action>
<action name="read" class="com.coreRestaurant.menu.MenuAction" method="readMenuById">
<result type="json" >
<param name="root">json</param>
</result>
</action>
<action name="add" class="com.coreRestaurant.menu.MenuAction" method="addMenu">
<result type="json" >
<param name="root">data</param>
</result>
</action>
</package>
</struts>
</code></pre>
<p>And this is my java code (<code>MenuAction.java</code>):</p>
<pre><code> package com.coreRestaurant.menu;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class MenuAction extends ActionSupport implements ModelDriven<Menu>, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Menu menu = new Menu();
private String json;
private List<Menu> data = new ArrayList<Menu>();
public String execute(){
MenuService menuService = new MenuService();
setJson(new Gson().toJson(menuService.getMenuNames()));
if(menuService.isDatabaseConnectionDown()==false){
return SUCCESS;
}else{
setJson(new Gson().toJson("Failed to connect to Database"));
return ERROR;
}
}
public String readMenuById(){
MenuService menuService = new MenuService();
setJson(new Gson().toJson(menuService.getSpecificalMenuNameById(menu.getId())));
return SUCCESS;
}
public String addMenu(){
MenuService menuService = new MenuService();
System.out.println(data);
for(int i=0; i<data.size(); i++){
System.out.println(data.get(i));
}
menu.setName("Postitus");
menuService.addMenu(menu);
return SUCCESS;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
@Override
public Menu getModel() {
return menu;
}
public List<Menu> getData() {
System.out.println("Getter Call");
return data;
}
public void setData(List<Menu> data) {
System.out.println("Setter Call Flow");
this.data = data;
}
}
</code></pre>
<p>And the <code>Menu.java</code> itself:</p>
<pre><code>package com.coreRestaurant.menu;
import java.io.Serializable;
public class Menu implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
</code></pre>
<p>All the time when I run my client side code, I can see the following input only from Eclipse console:</p>
<pre><code>[]
Getter Call
</code></pre>
<p>Why is it empty? I expect to have that JSON array from client side but no success. </p>
| 1 | 2,127 |
Insert HTML Table cell values into MySQL
|
<p>I have a HTML Table with Dynamic Columns which increase or decrease as per the user's selection.
I need to Insert this HTML Table in a MySQL Database table after taking inputs from the users in the front end.</p>
<p><a href="https://i.stack.imgur.com/zdeZl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zdeZl.png" alt="HTML Table Output"></a></p>
<p>The columns from Category to Product Name are constant post that the location column changes depending upon the user requirement.</p>
<p>Once the input is made and clicked on save i need to insert this data into production table in the below format:</p>
<p><a href="https://i.stack.imgur.com/uBKze.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uBKze.png" alt="enter image description here"></a></p>
<p>The code that i have completed so far kindly guide me with a proper direction:</p>
<pre><code><?php
if(isset($_POST['for_post_market'])){ $market = $_POST['for_post_market']; }
if(isset($_POST['for_post_prod_date'])){ $date_prod = $_POST['for_post_prod_date']; }
if(isset($_POST['for_post_sale_date'])){ $date_sale = $_POST['for_post_sale_date']; }
$query = 'SELECT * FROM product WHERE prod_status="Active"';
$stmt = $DB_con->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['prod_cat_name']][] = $row['prod_id'];
}
?>
<form method="post">
<table id="invoices" border="1" class="table table-striped table-bordered">
<thead>
<col width="65">
<col width="65">
<th>Category</th>
<th>Product ID</th>
<th>Product Name</th>
<th hidden="true">Production Date</th>
<th hidden="true">Sales Date</th>
<?php
$a=count($market);
for($i=0;$i<$a;$i++) {
echo '<th><input type="hidden" value="'. $market[$i] . '">'. $market[$i] .'</th>';
}
?>
</thead>
<tbody>
<?php
foreach($result as $id => $invoices) {
echo '<tr>';
echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
$count = 0;
foreach ($invoices as $invoice) {
if ($count != 0) {
echo '<tr>';
}
$count++;
echo '<td>' . $invoice . '</td>';
?>
<?php
$psql = $DB_con->prepare("SELECT * FROM product WHERE prod_id='$invoice'");
$psql->execute();
$resultpro = $psql->fetchall(PDO::FETCH_ASSOC);
foreach($resultpro as $line) {
}
?>
<td><?php echo $line['prod_name']; ?></td>
<?php
echo '<td hidden="true">' . $date_prod . '</td>';
echo '<td hidden="true">' . $date_sale . '</td>';
$a=count($market);
for($j=0;$j<$a;$j++) {
echo '<td><input type="text" name="'. $market[$j] .' "class="form-control" maxlength="6" size="4"></td>';
}
}
}
echo '</tbody>';
echo '</table>';
?>
<button type="submit" class="btn btn-default waves-effect waves-light" name="btn-saveforcast" id="btn-saveforcast">Save</button>
</form>
<?php
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
?>
</code></pre>
<p>Complete Code <a href="http://clean.omegakart.com/createforcast.txt" rel="nofollow noreferrer">Link</a></p>
| 1 | 1,817 |
Symfony2 choice field not working
|
<p>I asked a question here <a href="https://stackoverflow.com/questions/16441771/how-to-use-repository-custom-functions-in-a-formtype">How to use Repository custom functions in a FormType</a> but nobody anwsered, so i did a little digging and advanced a little but i still get this error:</p>
<pre><code>Notice: Object of class Proxies\__CG__\Kpr\CentarZdravljaBundle\Entity\Category
could not be converted to int in /home/kprhr/public_html/CZ_Symfony/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 457
</code></pre>
<p>Now this is how my CategoryType looks like:</p>
<pre><code><?php
namespace Kpr\CentarZdravljaBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Bridge\Doctrine\RegistryInterface;
class CategoryType extends AbstractType
{
private $doctrine;
public function __construct(RegistryInterface $doctrine)
{
$this->doctrine = $doctrine;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kpr\CentarZdravljaBundle\Entity\Category',
'catID' => null,
));
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$someId = $builder->getData()->getId();
$param = ($someId) ? $someId : 0;
$catID = $options['catID'];
$builder->add('name', 'text', array('attr' => array('class' => 'span6')));
$builder->add('file', 'file', array('image_path' => 'webPath', 'required' => false));
$builder->add('parent', 'choice', array(
'choices' => $this->getAllChildren($catID),
'required' => false,
'attr' => array('data-placeholder' => '--Izaberite Opciju--'),
));
$builder->add('tags', 'tag_selector', array(
'required' => false,
));
$builder->add('status', 'choice', array(
'choices' => array('1' => 'Aktivna', '0' => 'Neaktivna'),
'required' => true,
));
$builder->add('queue', 'text', array('attr' => array('class' => 'span3')));
}
private function getAllChildren($catID)
{
$choices = array();
$children = $this->doctrine->getRepository('KprCentarZdravljaBundle:Category')->findByParenting($catID);
foreach ($children as $child) {
$choices[$child->getId()] = $child->getName();
}
return $choices;
}
public function getName()
{
return 'category';
}
}
</code></pre>
<p>I am accessing the CategoryRepository function findByParenting($parent) from the CategoryType and I am getting the array populated with accurate data back from the function getAllChildren($catID) but the error is there, i think that Symfony framework is expecting an entity field instead of choice field, but dont know how to fix it.
I also changet the formCreate call in the controller giving $this->getDoctrine() as an argument to CategoryType():</p>
<pre><code>$form = $this->createForm(new CategoryType($this->getDoctrine()), $cat, array('catID' => $id));
</code></pre>
| 1 | 1,434 |
d3 bar chart using rangeRoundBands - why is there outer padding?
|
<p>I'm creating a bar chart using an ordinal scale for the x axis, and using rangeRoundBands. I'm following this example: <a href="https://bl.ocks.org/mbostock/3885304" rel="nofollow noreferrer">https://bl.ocks.org/mbostock/3885304</a></p>
<p>However, my chart has outer padding -- big spaces at the beginning and end of the axis, where I'd like the bars to fully extend. The screen shot below shows the spaces I'm referring to circled in red.</p>
<p><a href="https://i.stack.imgur.com/Jl58Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jl58Y.png" alt="screenshot of bar chart"></a></p>
<p>How can I remove these spaces? I need my margins and the svg width and height to remain the same.</p>
<p>Here is a Plunker with the chart as it is now:
<a href="https://plnkr.co/edit/gMw7jvieKSlFbHLTNY9o?p=preview" rel="nofollow noreferrer">https://plnkr.co/edit/gMw7jvieKSlFbHLTNY9o?p=preview</a></p>
<p>Code is also below:</p>
<pre><code><!doctype html>
<html>
<head>
<style>
.axis path{
fill: none;
stroke: #cccccc;
stroke-width: 2px;
}
.x.axis text{
display:none;
}
.bar{
fill: blue;
}
body{
font-family:Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<div id="barchart"></div>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 0, bottom: 50, left: 300},
width = 800 - margin.left - margin.right;
height = 465 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .5);
var y = d3.scale.linear().range([height, 0]);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");
var barsvg = d3.select("#barchart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("class", "barchartbox")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.json("population.json", function(error, data1) {
x.domain(data1.map(function(d) { return d.country; }));
y.domain([0, d3.max(data1, function(d) { return d.value; })]);
barsvg.selectAll(".axis").remove();
// Add the Y Axis
barsvg.append("g")
.attr("class", "y axis")
.call(yAxis);
// Add the X Axis
barsvg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var bars = barsvg.selectAll(".bar")
.data(data1);
bars.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.country); })
.attr("width", x.rangeBand())
.attr("y", function(d) {return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });
bars.exit().remove();
});
</script>
</body>
</html>
</code></pre>
| 1 | 1,598 |
Open html link in a div using jquery
|
<p>I am trying to drag and drop html link into a div element. My requirement here is to open the link in within that div element. I have 2 divisions on my page "left-panel" and "canvas".</p>
<p>Idea here is on my left panel I'll have multiple links, when I drop any of these link in canvas div it should open that html link within the canvas. One thought is to use iframe but I would like to know if this is possible with divs instead of iframe. I tried $.ajax() and load() but none of those seem to work. I'll appreciate your help in this regard. </p>
<p>This is what I have done so far:</p>
<p>
</p>
<pre><code><head>
<link rel="stylesheet" href="../css/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.6.js"></script>
<script type="text/javascript" src="../scripts/jquery-ui.min.js" ></script>
<style>
#canvasWrapper {
border: 1px solid #DDDDDD;
height: 100%;
vertical-align:top;
margin-left: auto;
margin-right: auto;
width: 90%;
}
.Frame {
border: 1px solid #DDDDDD;
height: 500px;
margin-left: auto;
margin-right: auto;
width: 100%;
}
.hFrame {
border: 1px solid #DDDDDD;
height: 50%;
width: 100%;
position:relative;
}
.nonSelectable {
border: 1px solid #DDDDDD;
height: 50%;
width: 100%;
position:relative;
}
.vFrame {
border: 1px solid #DDDDDD;
height: 100%;
width: 50%;
}
div.vFrame {
display:block;
float:left;
}
.buttonBar {
position: relative;
margin-left: auto;
margin-right: auto;
width:90%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="banner"></div>
<div id="content-wrapper">
<div id="content">
<table class="layout-grid" cellspacing="0" cellpadding="0" style="height:100%;">
<tbody>
<tr>
<td class="left-nav">
<dl class="left-nav">
<dt>Available Widgets</dt>
<dd>
<a href="../modules/1.html">I am no. 1</a>
</dd>
<dd>
<a href="../modules/2.html">I am no. 2</a>
</dd>
<dd>
<a href="../modules/3.html">I am no. 3</a>
</dd>
</dl>
</td>
<td class="normal">
<div id="canvasWrapper">
<div id="canvasFrame" class="Frame">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div id="footer"></div>
</div>
<script>
var lnk="",fullLink;
$(function() {
$( ".left-nav dd" ).draggable({
start: function (event,ui) {
var module= $(ui.draggable).html();
lnk= $(this).children().attr("href");
},
revert: "invalid",
helper: "clone"
});
$( "#canvasFrame" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).html(lnk);
}
});
});
</script>
</body>
</code></pre>
<p></p>
| 1 | 3,068 |
Write to CSV and text file
|
<p>In C# can someone teach me how to write the output of this program to a csv and a text file with unique ID each time? Like instead of writing to the console I want everything to go to a csv file and a text file at the same time. And also for the txt file includes a unique ID as record keeping.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Product
{
public string description;
public double price;
public int count;
public Product(string description, double price, int count)
{
this.description = description;
this.price = price * count;
this.count = count;
}
public string GetDetailLine()
{
return String.Format(count + " {0}: {1:c}", description, price);
}
}
class Program
{
static void Main(string[] args)
{
int AdultTicket;
int KidTicket;
int PopcornOrder;
int DrinkOrder;
double tax = .05;
List<Product> products = new List<Product>();
Console.Write("How many adults? ");
int.TryParse(Console.ReadLine(), out AdultTicket);
Product adultTicket = new Product("Adult Ticket(s)", 7.75, AdultTicket);
products.Add(adultTicket);
Console.Write("How many kids? ");
int.TryParse(Console.ReadLine(), out KidTicket);
Product kidTicket = new Product("Kid Ticket(s)", 5.75, KidTicket);
products.Add(kidTicket);
Console.Write("Do you want popcorn? ");
string input = Console.ReadLine();
if (input.ToUpper() == "YES")
{
Console.Write ("How many? ");
int.TryParse(Console.ReadLine (), out PopcornOrder);
Product popcorn = new Product("Small popcorn", 3.50, PopcornOrder );
products.Add(popcorn);
}
Console.Write("Do you want a drink? ");
string input2 = Console.ReadLine();
if (input2.ToUpper() == "YES")
{
Console.Write("How many? ");
int.TryParse(Console.ReadLine(), out DrinkOrder);
Product drink = new Product("Large Soda", 5.50, DrinkOrder);
products.Add(drink);
Console.Clear();
}
int count = 0;
for (int i = 0; i < products.Count; i++)
{
count += products[i].count;
}
double total = 0;
for (int i = 0; i < products.Count; i++)
{
Console.WriteLine("\t\t" + products[i].GetDetailLine());
total += products[i].price;
}
Console.WriteLine("\nYour sub total is: {0:c}", total);
Console.WriteLine("Tax: {0:c}", total * tax);
Console.WriteLine("Your total is: {0:c}", total * tax + total);
Console.ReadLine();
}
}
</code></pre>
<p>}</p>
| 1 | 1,251 |
Leaflet.js and JSON data : optimization and performance
|
<p>I'm currently working on my first real outing using Javascript to build an interactive map of our customer data .</p>
<p>So Far I've got the basics working but the performance starts to drop when I start going above around 500 poi's with markers or 10,000 with circle markers.... if anyone could offer some advise on how to optimize what I've already got or maybe am i best to move to a proper DB like mongo for the json data or do the work server side with Node Js maybe?</p>
<p>Any advice would be much appreciated :)</p>
<p></p>
<pre><code> var apiKey = 'BC9A493B41014CAABB98F0471D759707',
styleID = '108219';
// styleID = '997';
// var map = L.map('map').setView([54.550, -4.433], 7);
var southWest = new L.LatLng(61.029031, 4.746094),
northEast = new L.LatLng(48.786962 ,-13.183594),
bounds = new L.LatLngBounds(southWest, northEast);
var mapcenter = new L.LatLng(53.457393,-2.900391);
var map = new L.Map('map',
{
center: mapcenter,
zoom: 7,
// maxBounds: bounds,
zoomControl: false
});
var cloudmadeUrl = generateTileURL(apiKey, styleID),
attribution = 'Map data &copy; OpenStreetMap contributors.',
tileLayer = new L.TileLayer(
cloudmadeUrl,
{
maxZoom: 18,
attribution: attribution,
});
tileLayer.addTo(map);
var zoomControl = new L.Control.Zoom({ position: 'topleft'} );
zoomControl.addTo(map);
var scaleControl = new L.Control.Scale({ position: 'bottomleft' });
scaleControl.addTo(map);
geojsonLayer = L.geoJson(geojson, {
pointToLayer: function(feature, latlng) {
return new L.CircleMarker(latlng, {fillColor: feature.properties.MarkerColour, fillOpacity: 0.5, stroke: false, radius: 6});
// return new L.Marker(latlng, {icon: L.AwesomeMarkers.icon({icon: feature.properties.MarkerIcon, color: feature.properties.MarkerColour, iconColor: 'white'}) });
},
onEachFeature: function (feature, layer) {
layer.bindPopup( '<strong><b>Customer Data</b></strong><br />' + '<b>Result : </b>' + feature.properties.Result + '<br />' + '<b>Postcode : </b>' + feature.properties.Postcode + '<br />' );
}
});
console.log('starting: ' + window.performance.now());
map.addLayer(geojsonLayer);
console.log('ending: ' + window.performance.now());
function generateTileURL(apiKey, styleID) {
return 'http://{s}.tile.cloudmade.com/' + apiKey + '/' + styleID + '/256/{z}/{x}/{y}.png';
}
</code></pre>
<p></p>
<p>and some sample data : </p>
<pre><code>{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-0.213467,
51.494815
]
},
"properties": {
"DateTime": "1372719435.39",
"Result": "Cable Serviceable",
"MarkerIcon": "ok-sign",
"MarkerColour": "green",
"Postcode": "W14 8UD"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-0.389445,
51.512121
]
},
"properties": {
"DateTime": "1372719402.083",
"Result": "Refer for National Serviceability",
"MarkerIcon": "minus-sign",
"MarkerColour": "red",
"Postcode": "UB1 1NJ",
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-0.411291,
51.508012
]
},
"properties": {
"DateTime": "1372719375.725",
"Result": "Cable Serviceable",
"MarkerIcon": "ok-sign",
"MarkerColour": "green",
"Postcode": "UB3 3JJ"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-2.11054,
53.500752
]
},
"properties": {
"DateTime": "1372719299.088",
"Result": "Cable Serviceable",
"MarkerIcon": "ok-sign",
"MarkerColour": "green",
"Postcode": "OL7 9LR",
}
}
</code></pre>
| 1 | 2,365 |
At which phase is managed bean constructed and which constructor is used
|
<p>Consider example of JSF based web-app <code>hello1</code> from official tutorial with addition constructor in managed bean. The follow <code>index.xhtml</code> facelet</p>
<pre><code><html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelets Hello Greeting</title>
</h:head>
<h:body>
<h:form>
<h:graphicImage url="#{resource['images:duke.waving.gif']}"
alt="Duke waving his hand"/>
<h2>Hello hui, my name is Duke. What's yours?</h2>
<h:inputText id="username"
title="My name is: "
value="#{hello.name}"
required="true"
requiredMessage="Error: A name is required."
maxlength="25" />
<p></p>
<h:commandButton id="submit" value="Submit" action="response">
</h:commandButton>
<h:commandButton id="reset" value="Reset" type="reset">
</h:commandButton>
</h:form>
<div class="messagecolor">
<h:messages showSummary="true"
showDetail="false"
errorStyle="color: #d20005"
infoStyle="color: blue"/>
</div>
</h:body>
</html>
</code></pre>
<p>and modidfied managed bean <code>Hello.java</code></p>
<pre><code>package javaeetutorial.hello1;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
@Named
@RequestScoped
public class Hello {
private String name;
public Hello() {
}
public Hello(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String user_name) {
this.name = user_name;
}
}
</code></pre>
<p>There are <strong>two</strong> public constructors. Let we deploy this app on server and sent initial request, type the name in <code>inputText</code> and click <code>submit</code>. There is postback request after <code>submit</code> click. Hence, as written in tutroial, we have the following subphase of execute phase:</p>
<ol>
<li>The application view is built or restored.</li>
<li>The request parameter values are applied.</li>
<li>Conversions and validations are performed for component values.</li>
<li>Managed beans are updated with component values.</li>
<li>Application logic is invoked.</li>
</ol>
<p>At what phase instance of managed bean will be created? </p>
<p>What constructor will be invoked for this instance creation and why? I dont understand how it can be observe from the <code>index.xhtml</code> code.</p>
| 1 | 1,296 |
How to create a line in bootstrap grid system like this screenshot
|
<p>The layout would like to achieve:</p>
<p><img src="https://i.stack.imgur.com/cHIsO.png" alt=""></p>
<p>And the actual implement so far
<img src="https://i.stack.imgur.com/ctvG1.png" alt="enter image description here"></p>
<p>The problem is , notice the blue line under those topic , if I use the grid system, the is some padding among those block. How can I achieve the one blue line without breaking the grid?</p>
<p>Here is my code:</p>
<pre><code> <div class="row">
<div class="col-xs-12 col-sm-4 mt10">
<p class="fs22">Latest Video</p>
<hr class="blue_line mt10 mb10"/>
<?php if (isset($latest)) { ?>
<a href='<?= site_url("video/view/" . $latest['id']); ?>'>
<div class="home_block">
<img src="<?= (isset($latest['image_url']) ? site_url("thumbnail/" . $latest['image_url']) : site_url("assets/img/cms/video.png")); ?>">
<div class="txt">
<h3><?= $latest['title']; ?></h3>
<p>By <?= $latest['name']; ?></p>
<p><?= $this->level_list[$latest['level']]; ?></p>
<p class="text-muted"><?= trim_word($latest['description'], 50); ?></p>
</div>
</div>
</a>
<?php } else { ?>
<div class="home_block center">
<img src="<?= site_url("assets/img/cms/video.png"); ?>">
<div class="txt text-center">
<p>No video available.</p>
</div>
</div>
<?php } ?>
</div>
<div class="col-xs-12 col-sm-4 mt10">
<p class="fs22">Popular Video</p>
<hr class="blue_line mt10 mb10"/>
<?php if (isset($popular)) { ?>
<a href='<?= site_url("video/view/" . $popular['id']); ?>'>
<div class="home_block center">
<img src="<?= (isset($popular['image_url']) ? site_url("thumbnail/" . $popular['image_url']) : site_url("assets/img/cms/video.png")); ?>">
<div class="txt">
<h3><?= $popular['title']; ?></h3>
<p>By <?= $popular['name']; ?></p>
<p><?= $this->level_list[$popular['level']]; ?></p>
<p class="text-muted"><?= trim_word($popular['description'], 50); ?></p>
</div>
</div>
</a>
<?php } else { ?>
<div class="home_block">
<img src="<?= site_url("assets/img/cms/video.png"); ?>">
<div class="txt text-center">
<p>No video available.</p>
</div>
</div>
<?php } ?>
</div>
<div class="col-xs-12 col-sm-4 mt10">
<p class="fs22">Community Image</p>
<hr class="blue_line mt10 mb10"/>
<div class="home_block">
<img src="<?= isset($post['image_url']) ? site_url("community/" . $post['image_url']) : site_url("assets/img/front/discuss.png"); ?>">
<div class="txt">
<p class="text-muted" style="margin-top: 15px;"><?= trim_word($post['comment'], 150); ?></p>
<p class="text-right"><?= $post['create_date']; ?></p>
</div>
</div>
</div>
</div>
</code></pre>
<p>Thanks a lot for helping.</p>
<p><strong>Update :</strong> To clearify, what would like to achieve is </p>
<p>when it is full width e.g. col-lg </p>
<p>it should like this:</p>
<p><img src="https://i.stack.imgur.com/cHIsO.png" alt=""></p>
<p>And when it is mobile width e.g. col-xs</p>
<p>then it should like this:
<img src="https://i.stack.imgur.com/VBLow.png" alt="enter image description here"></p>
| 1 | 2,907 |
Having trouble with ellipsis with angularjs
|
<p>I am having issue with ellipsis and angularjs. I want to update max-width dynamically from parent as TD element width. I tried for 2 approach. One is updating dom after printing the table structure. Another is to provide directive. But nothing works.</p>
<p><strong>HTML:</strong></p>
<pre><code><table class="table data-table cvcTable sort display">
<thead>
<tr>
<th ng-repeat="column in tableOptions.columnDefs"
ng-style="{'width': column.width}"><a href
ng-click="tableEvents.sort('{{column.field}}',$event)">{{column.label}}
<i class="pull-left" ng-class="column.orderType"></i>
</a></th>
</tr>
</thead>
<tbody>
<tr ng-class-odd="'row-odd'" ng-class-even="'row-even'" ng-repeat="item in tableOptions.data">
<td>{{item.key}}</td>
<td><span title="{{item.value}}" ellipsisSpan
class="ellipsis">{{item.value}}</span></td>
<td><span title="{{item.comments}}" ellipsisSpan
class="ellipsis">{{item.comments}}</span></td>
<td>{{item.updated}}</td>
<td>{{item.updatedBy}}</td>
</tr>
</tbody>
</code></pre>
<p></p>
<p><strong>Directive: I am not getting alert message.</strong></p>
<pre><code>app.directive('ellipsisSpan', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs, ctrl) {
alert("Im inside call");
// Do calculation
}
};
});
</code></pre>
<p><strong>Dynamic Call: I can see following line working perfectly but don't see updated in DOM.</strong></p>
<p>"a.css('max-width', width + 'px');"</p>
<pre><code>angular.element(document).ready(function () {
var element = angular.element(document.querySelector('.ellipsis'));
angular.forEach(element, function(value, key){
var a = angular.element(value);
var width = a.parent()[0].clientWidth;
a.css('max-width', width + 'px');
});
scope.$apply();
});
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.ellipsis {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
max-width: inherit;
}
</code></pre>
| 1 | 1,043 |
webpack-bundle-analyzer shows webpack -p does not remove development dependency react-dom.development.js
|
<p>This is my webpack setup</p>
<pre><code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const SOURCE_DIR = './src';
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: SOURCE_DIR + '/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = env => {
console.log(`Environment Configs: ${JSON.stringify(env) || 'Default'}`);
console.log(`
Available Configs:
--env.watch = true / false //for allow webpack to watch build
`)
let environment = env || {};
const {
watch,
analyze,
} = environment;
const configedAnalyzer = new BundleAnalyzerPlugin({
// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
analyzerMode: 'static',//was server
// Host that will be used in `server` mode to start HTTP server.
analyzerHost: '127.0.0.1',
// Port that will be used in `server` mode to start HTTP server.
analyzerPort: 9124,
// Path to bundle report file that will be generated in `static` mode.
// Relative to bundles output directory.
reportFilename: './../report/bundle_anlaysis.html',
// Module sizes to show in report by default.
// Should be one of `stat`, `parsed` or `gzip`.
// See "Definitions" section for more information.
defaultSizes: 'stat',
// Automatically open report in default browser
openAnalyzer: Boolean(analyze),
// If `true`, Webpack Stats JSON file will be generated in bundles output directory
generateStatsFile: Boolean(analyze),
// Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// Relative to bundles output directory.
statsFilename: 'stats.json',
// Options for `stats.toJson()` method.
// For example you can exclude sources of your modules from stats file with `source: false` option.
// See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
statsOptions: null,
// Log level. Can be 'info', 'warn', 'error' or 'silent'.
logLevel: 'info'
});
return {
entry: SOURCE_DIR + '/index.js',
output: {
path: path.resolve(__dirname, "dist"),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
}
]
},
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
watch: Boolean(watch),
plugins: [HtmlWebpackPluginConfig, configedAnalyzer], //
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: false,
port: 9123,
}
};
}
</code></pre>
<p>When I do <code>webpack -p</code> file size is a lot smaller but this react-dom.development.js take over almost 50% of the size, in my case 500ish KB out of 1.1ish MB.</p>
<p>Report here:</p>
<p><a href="https://i.stack.imgur.com/13v4O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/13v4O.png" alt="enter image description here"></a></p>
<p>To see a demo of the report and how it got run you can check <a href="https://github.com/adamchenwei/webpack-playground/tree/master/modularization/app" rel="nofollow noreferrer">this</a> repository.</p>
<p>NOTE: even I add <code>NODE_ENV=production</code>, size is smaller but the development JavaScript file is still there!</p>
| 1 | 1,408 |
How to convert Action to Func<Task> without running the Task?
|
<p>I have code that works precisely as desired. However, our corporate build server rejects any check-in that has a compiler warning.</p>
<p>The following warning is (as expected) displayed for the Action constructor with the Action to Func conversions, since I am not using an await statement.</p>
<blockquote>
<p>This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.</p>
</blockquote>
<pre><code>public class TransactionOperation
{
private readonly Func<Task> _operation;
private readonly Func<Task> _rollback;
public OperationStatus Status { get; private set; }
public TransactionOperation(Func<Task> operation, Func<Task> rollback)
{
_operation = operation;
_rollback = rollback;
Status = OperationStatus.NotStarted;
}
public TransactionOperation(Action operation, Action rollback)
{
_operation = async () => operation.Invoke();
_rollback = async () => rollback.Invoke();
Status = OperationStatus.NotStarted;
}
public async Task Invoke()
{
try
{
Status = OperationStatus.InProcess;
await _operation.Invoke();
Status = OperationStatus.Completed;
}
catch (Exception ex)
{
//...
}
}
}
</code></pre>
<p>What is a correct way to rewrite that code so that the Action is correctly converted to Func without being executed yet or creating a new thread (i.e. await Task.Run())?</p>
<hr />
<p><strong>Update - Proposed Answer #1</strong></p>
<blockquote>
<p>_operation = () => new Task(operation.Invoke);</p>
<p>_rollback = () => new Task(rollback.Invoke);</p>
</blockquote>
<p>I tried this before. It causes this unit test to never return.</p>
<pre><code>[TestMethod, TestCategory("Unit Test")]
public async Task Transaction_MultiStepTransactionExceptionOnFourthAction_CorrectActionsRolledBack()
{
var operation = new TransactionOperation(PerformAction, () => RollbackOperation(1));
var operation2 = new TransactionOperation(PerformAction, () => RollbackOperation(2));
var operation3 = new TransactionOperation(PerformAction, () => RollbackOperation(3));
var operation4 = new TransactionOperation(ExceptionAction, () => RollbackOperation(4));
var operation5 = new TransactionOperation(PerformAction, () => RollbackOperation(5));
var transaction = new Transaction(new[] { operation, operation2, operation3, operation4, operation5 });
await IgnoreExceptions(transaction.ExecuteAsync);
AssertActionsPerformedThrough(4);
AssertActionsRolledBackThrough(4);
}
</code></pre>
<hr />
<p><strong>Update - Accepted Answer</strong></p>
<pre><code>private async Task ConvertToTask(Action action)
{
action.Invoke();
await Task.FromResult(true);
}
</code></pre>
<p>Here's the updated Action constructor:</p>
<pre><code>public TransactionOperation(Action operation, Action rollback)
{
_operation = () => ConvertToTask(operation);
_rollback = () => ConvertToTask(rollback);
Status = OperationStatus.NotStarted;
}
</code></pre>
| 1 | 1,111 |
Store checked checkbox value in javascript
|
<p>MY each div contain multiple checkbox and I have such several div . iwant to keep a track of which checkbox selected and their respective div . I am trying to store it inside a multidimensional array but it's not proper ..
If you have any other idea then plz share with me.</p>
<pre><code><html>
<head>
<style type="text/css" >
div{
width:50%;
height:500px;
border:2px solid black;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var count = 0;
function selectradiobutn(frmname){
formfield=document.forms[frmname].first_ques;
for(i=0;i<formfield.length;i++){
if(formfield[i].checked==true){
var value1 = formfield[i].value;
alert(value1);
var value = new Array;
value[i]=value1;
var myarray = new Array("A. Aluminium","B. Commodities that is available according to their demand","C. to remove salts","D. 1970 in Bangkok","D. None of the above");
if(myarray[i]==value[i]){
count++;
//alert(count);
}
}
}
return count;
}
function create_array1(){
alert("Your score is"+count);
document.getElementById('main').innerHTML = "Your score is"+count;
}
</script>
</head>
<body>
<div id="main" style="width:50%; height:500px; border:2px solid black;">
<center><p style="padding:70px;"><h1>Click the button to start test</h1></p>
<input type="button" value="Start test." id="btn_start" onclick="show_div('main','first1')">
</div>
</center>
<div id="first1" style="display:none; ">
<p style="padding:50px;">1. For galvanizing iron which of the following metals is used ?
</br>
<form name="f1">
<input type=Checkbox name=first_ques value="A. Aluminium" onclick="selectradiobutn('f1')">A. Aluminium </br></br>
<input type=Checkbox name=first_ques value="B. Copper" onclick="selectradiobutn('f1')">B. Copper</br></br>
<input type=Checkbox name=first_ques value="C. Lead" onclick="selectradiobutn('f1')">C. Lead</br></br>
<input type=Checkbox name=first_ques value="D. Zinc" onclick="selectradiobutn('f1')">D. Zinc</br></p>
<center><input type="button" value="Next" onclick="show_div('first1','first2')"></center>
</code></pre>
<p>
</p>
<pre><code> <div id="first2" style="display:none;">
<p style="padding:50px;"> 2. Economic goods are </br>
<form name=f2>
<input type="Checkbox" name=first_ques value="first" onclick="selectradiobutn('f2')">A. all commodities that are limited in quantity as compared to their demand</br></br>
<input type="Checkbox" name=first_ques value="B. Commodities that is available according to their demand" onclick="selectradiobutn('f2')">B. Commodities that is available according to their demand</br></br>
<input type="Checkbox" name=first_ques value="C. Commodities that is available more as compared to demand" onclick="selectradiobutn('f2')">C. Commodities that is available more as compared to demand</br></br>
<input type="Checkbox" name=first_ques value="D. None of the above" onclick="selectradiobutn('f2')">D. None of the above</br></br></p>
<center><input type="button" value="Next" onclick="show_div('first2','first3')"></center>
</code></pre>
<p>
</p>
<pre><code> <div id="first3" style="display:none;">
<p style="padding:50px;">3. For purifying drinking water alum is used
<form name="f3">
<input type="Checkbox" value="A. for coagulation of mud particles" name=first_ques onclick="selectradiobutn('f3')">A. for coagulation of mud particles</br> </br>
<input type="Checkbox" value="B. to kill bacteria" name=first_ques onclick="selectradiobutn('f3')">B. to kill bacteria</br></br>
<input type="Checkbox" value="C. to remove salts" name=first_ques onclick="selectradiobutn('f3')">C. to remove salts</br></br>
<input type="Checkbox" value="D. to remove gases" name=first_ques onclick="selectradiobutn('f3')">D. to remove gases</br></br></p>
<center><input type="button" value="Next" onclick="show_div('first3','first4')"></center>
</form>
</div>
<div id="first4" style="display:none;">
<p style="padding:50px;">4. Hockey was introduced in the Asian Games in
<form name="f4">
<input type="Checkbox" value="A. 1958 in Tokyo" name=first_ques value="first_forth" onclick="selectradiobutn('f4')">A. 1958 in Tokyo</br></br>
<input type="Checkbox" value="B. 1962 in Jakarta" name=first_ques onclick="selectradiobutn('f4')">B. 1962 in Jakarta</br></br>
<input type="Checkbox" value="B. 1962 in Jakarta" name=first_ques onclick="selectradiobutn('f4')">B. 1962 in Jakarta</br></br>
<input type="Checkbox" value="D. 1970 in Bangkok" name=first_ques onclick="selectradiobutn('f4')">D. 1970 in Bangkok</br></br></p>
<center><input type="button" value="Next" onclick="show_div('first4','first5')"></center>
</form>
</div>
<div id="first5" style="display:none;">
<p style="padding:50px;">5.ESCAP stands for
<form name="f5">
<input type="Checkbox" value="A. Economic and Social Commission for Asia and Pacific" name=first_ques onclick="selectradiobutn('f5')">A. Economic and Social Commission for Asia and Pacific</br></br>
<input type="Checkbox" value="B. European Society Council for Africa and Pacific" name=first_ques onclick="selectradiobutn('f5')">B. European Society Council for Africa and Pacific</br></br>
<input type="Checkbox" value="C. Economic and Social Commission for Africa and Pacific" name=first_ques onclick="selectradiobutn('f5')">C. Economic and Social Commission for Africa and Pacific</br></br>
<input type="Checkbox" value="D. None of the above" name=first_ques onclick="selectradiobutn('f5')">D. None of the above</br></br></p>
</code></pre>
<p>
</p>
| 1 | 3,266 |
C++ Protected Variables Not Inherited
|
<p>I have written some code to calculate the RSA cryptographic algorithm. The program uses classes and inheritance because I want to calculate a public and private key for multiple users. There is a parent class <code>rsa</code> and child classes <code>public_key</code> and <code>private_key</code>.</p>
<p>When compiling the code below, I get many errors. All of them are about the derived classes not having the available fields in their respective constructors (see error message below code). However, these variables are defined with the <code>protected</code> access modifier in the parent class, so they should be accessible to the child class.</p>
<p>One side note: I had the function <code>key</code> in both of the child classes, but I thought it would be better to put it once in the parent class, is this right?</p>
<p>Here is the code:</p>
<pre><code>#include <iostream>
#include <math.h>
using namespace std;
class rsa
{
protected:
int p, q, d, m, n, f, e, c, end, k;
public:
rsa() : n(0), e(0), c(0), k(0), end(0), f(0)
{ }
void set(int , int , int, int);
int key()
{
n = p * q;
f = (p - 1) * (q - 1);
for (k; end < 1; k++)
{
if ((1 + k * f) % d == 0)
{
end = 2;
e = (1 + k * f) / d;
}
}
c = int(pow(m, e)) % n;
return c;
}
};
void rsa::set(int p_, int q_, int d_, int m_)
{
p = p_;
q = q_;
d = d_;
m = m_;
}
class public_key : public rsa
{
public:
public_key() : n(0), e(0), c(0), k(0), end(0), f(0)
{ }
};
class private_key : public rsa
{
public:
private_key() : n(0), e(0), c(0), k(0), end(0), f(0)
{ }
};
int main()
{
public_key usr1, usr2;
private_key usr1r, usr2r;
usr1.set(11, 5, 23, 9);
usr2.set(13, 7, 97, 6);
usr1r.set(17, 7, 51, 8);
usr2r.set(11, 17, 51, 4);
cout << "Public key of user 1: " << usr1.key() << endl;
cout << "Public key o user 2: " << usr2.key() << endl;
cin.get();
return 0;
}
</code></pre>
<p>One of the errors:</p>
<pre><code>error: class ‘private_key’ does not have any field named ‘e’
private_key () : n(0), e(0), c(0), k(0), end(0), f(0) {} ;
</code></pre>
<p>All the other errors are the same but the field name changes.</p>
| 1 | 1,067 |
sap.m.MessageBox.confirm working sap.m.MessageBox.error or sap.m.MessageBox.warning not working
|
<p>In my sapui5 project i am using <code>sap.m.MessageBox.confirm</code> its working fine but when i use <code>sap.m.MessageBox.error</code> or <code>sap.m.MessageBox.warning</code> it shows error </p>
<pre><code>Uncaught TypeError: undefined is not a function
</code></pre>
<p>I have added <code>jQuery.sap.require("sap.m.MessageBox");</code> still the issue is not solved. please give solution for this problem</p>
<p>Thanks</p>
<p>Sorry for not posting the code earlier</p>
<p><strong>Edited 1</strong></p>
<p><strong>View</strong></p>
<pre><code> <core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
controllerName="trial.S1" xmlns:html="http://www.w3.org/1999/xhtml">
<Page title="Title">
<content>
</content>
<footer>
<OverflowToolbar>
<ToolbarSpacer />
<Button id="errorId" text="Error" type="Accept"
press="fnOnerror" />
<Button id="confirmId" text="Confirm" type="Accept"
press="fnOnconfirm" />
</OverflowToolbar>
</footer>
</Page>
</core:View>
</code></pre>
<p><strong>Conroller</strong></p>
<pre><code>jQuery.sap.require("sap.m.MessageBox");
sap.ui.controller("trial.S1", {
fnOnerror : function(oEvent){
sap.m.MessageBox.error("My error message");
},
fnOnconfirm : function(oEvent){
sap.m.MessageBox.confirm("My Confirm message")
}
});
</code></pre>
<p><strong>index.html</strong></p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.m"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->
<script>
sap.ui.localResources("trial");
var app = new sap.m.App({initialPage:"idS11"});
var page = sap.ui.view({id:"idS11", viewName:"trial.S1", type:sap.ui.core.mvc.ViewType.XML});
app.addPage(page);
app.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
</code></pre>
| 1 | 1,350 |
How to work with System.Web.UI.DataVisualization.Charting
|
<p>This is what i did so far. Please go through the entire description to know my requirement</p>
<pre><code> System.Web.UI.DataVisualization.Charting.ChartArea chartArea1 = new System.Web.UI.DataVisualization.Charting.ChartArea();
System.Web.UI.DataVisualization.Charting.Legend legend1 = new System.Web.UI.DataVisualization.Charting.Legend();
System.Web.UI.DataVisualization.Charting.Series series1 = new System.Web.UI.DataVisualization.Charting.Series();
System.Web.UI.DataVisualization.Charting.Series series2 = new System.Web.UI.DataVisualization.Charting.Series();
System.Web.UI.DataVisualization.Charting.Chart chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
//((System.ComponentModel.ISupportInitialize)(chart1)).BeginInit();
//this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
chart1.ChartAreas.Add(chartArea1);
legend1.Name = "Legend1";
chart1.Legends.Add(legend1);
//chart1.Location = new System.Drawing.Point(49, 62);
//chart1.Name = "chart1";
series1.ChartArea = "ChartArea1";
series1.ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.StackedBar;
series1.Legend = "Legend1";
series1.Name = "Series2";
series2.ChartArea = "ChartArea1";
series2.ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.StackedBar;
series2.Legend = "Legend1";
series2.Name = "Series3";
chart1.Series.Add(series1);
chart1.Series.Add(series2);
//chart1.Size = new System.Drawing.Size(534, 300);
chart1.TabIndex = 0;
//chart1.Text = "chart1";
chart1.Series["Series2"].Points.Add(new DataPoint(1, 1));
chart1.Series["Series2"].Points.Add(new DataPoint(2, 4));
chart1.Series["Series2"].Points.Add(new DataPoint(3, 5));
chart1.Series["Series3"].Points.Add(new DataPoint(2, 3));
chart1.Series["Series2"].IsValueShownAsLabel = true;
chart1.Series["Series3"].IsValueShownAsLabel = true;
using (MemoryStream ms = new MemoryStream())
{
chart1.SaveImage(ms, ChartImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
</code></pre>
<p>And this will give the following chart. </p>
<p><a href="https://i.stack.imgur.com/NiT7a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NiT7a.png" alt="enter image description here"></a></p>
<p>But what i need is a chart like the following with Start and End values</p>
<p><a href="https://i.stack.imgur.com/HfMbK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HfMbK.png" alt="enter image description here"></a></p>
<p>How do i get it?</p>
<p>UPDATE:
The data i wish to display is stored in a list which looks like following</p>
<pre><code> List<dummyGraph> objGraphList = new List<dummyGraph>();
dummyGraph objDummyGraph = new dummyGraph();
objDummyGraph.RiskCategories = "Compliance,Law,Legislation";
objDummyGraph.HighImpactRisks = "4";
objDummyGraph.MediumImpactRisks = "1";
objDummyGraph.LowImpactRisks = "0";
objDummyGraph.NoImpactRisks = "5";
objDummyGraph.index = 1;
objGraphList.Add(objDummyGraph);
objDummyGraph = new dummyGraph();
objDummyGraph.RiskCategories = "Construction";
objDummyGraph.HighImpactRisks = "5";
objDummyGraph.MediumImpactRisks = "1";
objDummyGraph.LowImpactRisks = "4";
objDummyGraph.NoImpactRisks = "0";
objDummyGraph.index = 2;
objGraphList.Add(objDummyGraph);
</code></pre>
| 1 | 1,571 |
How to use backBehavior: 'history' on my bottomtabnaviagor
|
<p>I have a BottomTabNavigator in my Expo app as the initial page. Whenever I navigator to another screen and go back I want to have the last opened tab on the tabnavigator open. I have read that: 'backBehavior: 'history' does just that, but it doesn't work for me, it instead goes to the initialtab. This is my Tabnavigator code: </p>
<pre><code>class MainTabNavigator extends React.Component {
const DiscoverStack = createStackNavigator(
{
Discover: DiscoverScreen
},
{ backBehavior: 'history' }
);
DiscoverStack.navigationOptions = {
tabBarLabel: 'Ontdek',
backBehavior: 'history',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={`${focused ? 'md-bulb' : 'ios-bulb'}`}
/>
)
};
const TodoStack = createStackNavigator(
{
Todo: TodoScreen
},
{ backBehavior: 'history' }
);
TodoStack.navigationOptions = {
tabBarLabel: 'Wat te doen',
backBehavior: 'history',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={'md-calendar'} />
)
};
const ShopStack = createStackNavigator(
{
Shop: ShopScreen
},
{ backBehavior: 'history' }
);
ShopStack.navigationOptions = {
tabBarLabel: 'Shop',
backBehavior: 'history',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={'md-cart'} />
)
};
const WinStack = createStackNavigator(
{
Win: WinScreen
},
{ backBehavior: 'history' }
);
WinStack.navigationOptions = {
tabBarLabel: 'Win',
backBehavior: 'history',
tabBarIcon: ({ focused }) => (
<Icon2
focused={focused}
size={26}
style={{ marginBottom: -3 }}
color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
name={'ticket'}
/>
)
};
const UserStack = createStackNavigator(
{
User: UserScreen
},
{ backBehavior: 'history' }
);
UserStack.navigationOptions = {
tabBarLabel: 'Account',
backBehavior: 'history',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={'md-person'} />
)
};
export default createBottomTabNavigator(
{
DiscoverStack,
TodoStack,
ShopStack,
WinStack,
UserStack
},
{ backBehavior: 'history' }
);
</code></pre>
| 1 | 1,036 |
Does base64 encoding has any string length limit to encode?
|
<p>I have tab application which converts password using Base64 encoding. It is send to web application via web service where it gets decoded. Code for decoding is,</p>
<pre><code>public static string DecryptStringPassword(string base64StringToDecrypt)
{
//Set up the encryption objects
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(Key)))
{
byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
ICryptoTransform ictD = acsp.CreateDecryptor();
//RawBytes now contains original byte array, still in Encrypted state
//Decrypt into stream
MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
//csD now contains original byte array, fully decrypted
//return the content of msD as a regular string
return (new StreamReader(csD)).ReadToEnd();
}
}
private static AesCryptoServiceProvider GetProvider(byte[] key)
{
AesCryptoServiceProvider result = new AesCryptoServiceProvider();
result.BlockSize = 128;
result.KeySize = 128;
result.Mode = CipherMode.CBC;
result.Padding = PaddingMode.PKCS7;
result.GenerateIV();
result.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
// result.IV = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}
</code></pre>
<p>Is there any maximum character limit for base64 encoding? For one of the passwords "xwYgqg8+xnynU7MpceOoJw==" is the encrypted string which gives exception "padding is invalid and can not be removed" while decoding using above code.
In the DecryptStringPassword() function, last line,
return (new StreamReader(csD)).ReadToEnd(); gives the exception.</p>
<p>Same password I encrypted using AES encryption, it gives me
"xwYgqg8+xnynU7MpceOoJ70HuRIIw+OkcDPBVa18mLw=" such a big encrypted password compared to base64 encoding which does not give any exception while decoding.</p>
<p>Is there any limit that base64 encoding gives always 24 characters long encrypted string or any length restriction on the string to be encrypted.</p>
<p>Our one of the users facing this issue while decoding the password. Rest all users have no problem while decoding.</p>
| 1 | 1,223 |
Adding directive makes controller undefined in angular js code
|
<p>Here is my angular js app with html code</p>
<pre><code><html>
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
angular.module("demo", []).controller('DemoController', function ($scope) {
$scope.user = {
dateOfBirth: new Date(1970, 0, 1)
}
});
</script>
</head>
<body>
<div ng-app="demo" ng-controller="DemoController">
Date Of Birth:
<my-datepicker type="text" ng-model="user.dateOfBirth" />
<br />
Current user's date of birth: <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span>
</div>
</body>
</html>
</code></pre>
<p>It works fine.But the moment i add a directive to it, it shows error</p>
<pre><code>Error: Argument 'DemoController' is not a function, got undefined
</code></pre>
<p>Here is the full code with directive</p>
<pre><code><html>
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
angular.module("demo", []).controller('DemoController', function ($scope) {
$scope.user = {
dateOfBirth: new Date(1970, 0, 1)
}
});
angular.module("demo", []).directive('myDatepicker', function ($parse) {
return {
restrict: "E",
replace: true,
transclude: false,
compile: function (element, attrs) {
var modelAccessor = $parse(attrs.ngModel);
var html = "<input type='text' id='" + attrs.id + "' >" +
"</input>";
var newElem = $(html);
element.replaceWith(newElem);
return function (scope, element, attrs, controller) {
var processChange = function () {
var date = new Date(element.datepicker("getDate"));
scope.$apply(function (scope) {
// Change bound variable
modelAccessor.assign(scope, date);
});
};
element.datepicker({
inline: true,
onClose: processChange,
onSelect: processChange
});
scope.$watch(modelAccessor, function (val) {
var date = new Date(val);
element.datepicker("setDate", date);
});
};
}
};
});
</script>
</head>
<body>
<div ng-app="demo" ng-controller="DemoController">
Date Of Birth:
<my-datepicker type="text" ng-model="user.dateOfBirth" />
<br />
Current user's date of birth: <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span>
</div>
</body>
</html>
</code></pre>
<p>i'm following the tutorial from this link <a href="http://henriquat.re/directives/advanced-directives-combining-angular-with-existing-components-and-jquery/angularAndJquery.html" rel="nofollow">http://henriquat.re/directives/advanced-directives-combining-angular-with-existing-components-and-jquery/angularAndJquery.html</a></p>
| 1 | 1,989 |
Facebook iOS SDK 3.1 post image on friends wall error
|
<p>I am using the latest Facebook iOS SDK 3.1.1
while trying to post UIImage on friends wall i`m getting error 5 (Error: HTTP status code: 403).</p>
<p>if i try to post the image on MY wall its working well, but not of one of my friends.</p>
<p>My Code:
1. before posting i am checking if the user has the right permissions, when he does i am making </p>
<pre><code>-(void)postImageOnFriendsWall:(UIImage*)image FriendsArray:(NSArray*)friends
{
// if we don't have permission to announce, let's first address that
if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound)
{
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// re-call assuming we now have the permission
[self postImageOnFriendsWall:image FriendsArray:friends];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
}
else
{
// can post image
for (id<FBGraphUser> user in friends)
{
NSString *userID = user.id;
NSLog(@"trying to post image of %@ wall",userID);
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:UIImagePNGRepresentation(image) forKey:@"picture"];
[postVariablesDictionary setObject:@"my image" forKey:@"message"];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"%@/photos",userID] parameters:postVariablesDictionary HTTPMethod:@"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Facebook" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
//showing an alert for success
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Shared the photo successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}];
}
}
}
</code></pre>
<p>to mention, if i change </p>
<p><code>startWithGraphPath:[NSString stringWithFormat:@"%@/photos",userID]</code> </p>
<p>to</p>
<pre><code>startWithGraphPath:[NSString stringWithFormat:@"me/photos",userID]
</code></pre>
<p>its working ok.</p>
<p>what am i doing wrong?
i have been trying to look for answers but nothing helped.
Thank you!</p>
| 1 | 1,772 |
Trouble with client side validation using Struts 2. Xml based validation rules not recognized
|
<p>My issue is that when I don't see a client side validation error message when I don't enter any values for that field even when it is configured as required. The page is reloaded and goes to the result page and client validation fails. I am not sure what I am doing wrong.</p>
<p>I have a simple form where I have a pull down menu called selection criterion. A value must be selected. If a value is not selected, then the page should reload with configured error message. My input form action_item_search.jsp is given below:</p>
<pre><code><%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Action Item Search</title>
</head>
<body>
<s:actionerror/>
<s:fielderror />
<s:form action="action_item_search" validate="true">
<s:select label="Search Criterion" name="searchCriterion"
list="#{'': 'Select One', 'creatorName':'creator name',
assignedTo':'assigned to'}" required="true" />
<s:submit name="search" value="Search"></s:submit>
</s:form>
</body>
</code></pre>
<p>I have add validators.xml in my WEB-INF/classes directory of exploded war file as given below:</p>
<pre><code><!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="required"
class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring"
class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int"
class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long"
class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short"
class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double"
class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date"
class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression"
class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression"
class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email"
class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="url"
class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor"
class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion"
class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength"
class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex"
class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor"
class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
</validators>
</code></pre>
<p>ActionItemTrackingAction-findByCriteria-validation.xml in WEB-INF/classes directory is given below:</p>
<pre><code><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="searchCriterion" >
<field-validator type="required">
<message>You must enter a search criterion.</message>
</field-validator>
</field>
</validators>
</code></pre>
<p>My struts mapping xml:</p>
<pre><code><struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<!-- <include file="example.xml"/> -->
<package name="action-item" extends="struts-default">
<action name = "action_item_search_input">
<result name = "success">/action-item-search.jsp</result>
</action>
<action name="action_item_search" class="gov.nasa.spacebook.ActionItemTrackingAction" method="fetchByCriteria">
<result name = "success">/action-item-result.jsp</result>
<result name = "input">/action-item-search.jsp</result>
<result name = "error">/action-item-search.jsp</result>
</action>
</package>
</struts>
</code></pre>
<p>My action class</p>
<pre><code>public class ActionItemTrackingAction extends ActionSupport {
private List<ActionItem> actionItems;
public List<ActionItemTracking> getActionItems() {
return actionItems;
}
public void setActionItems(List<ActionItemTracking> actionItems) {
this.actionItems = actionItems;
}
private String searchCriterion;
public String getSearchCriterion() {
return searchCriterion;
}
public void setSearchCriterion(final String criterion) {
this.searchCriterion = criterion;
}
public String fetchByCriteria() throws Exception {
final ActionItemTrackingService service =
new ActionItemTrackingService();
this.actionItems = service.getByField(this.actionItem);
return super.execute();
}
}
</code></pre>
| 1 | 2,373 |
Updating Text in UI from Async Task using onProgressUpdate
|
<p>I am using <code>AsyncTask</code> to do a http request. But the code is crashing while trying to update UI elements.</p>
<pre><code>class ServerRequest extends AsyncTask<String,String,String> {
private View rootView;
private Activity rootAct;
private String result;
public ServerRequest(View view,Activity act) {
// TODO Auto-generated constructor stub\
rootView = view;
rootAct = act;
}
protected String doInBackground(String... params) {
String URL=params[0];
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString="DEFAULT";
try {
response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = responseString;
publishProgress(responseString);
return responseString;
}
@Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
EditText tt = (EditText) rootView.findViewById(R.id.codeResult);
tt.setText("Sample Text"); //Causing APP TO CRASH
}
protected void onPostExecute(String result) {
Log.d("retval",result);
}
}
</code></pre>
<p>The <code>setText</code> in <code>onProgressUpdate</code> is causing my application to crash. I have gone through most of the threads on this but couldn't find a solution.</p>
<p>LOG</p>
<pre><code>12-27 18:32:00.163: E/AndroidRuntime(24685): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:1)
12-27 18:32:00.163: E/AndroidRuntime(24685): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:69)
12-27 18:32:00.163: E/AndroidRuntime(24685): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
12-27 18:32:00.163: E/AndroidRuntime(24685): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 18:32:23.253: E/AndroidRuntime(24801): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:69)
12-27 18:32:23.253: E/AndroidRuntime(24801): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:1)
12-27 18:32:23.253: E/AndroidRuntime(24801): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
12-27 18:35:00.233: E/AndroidRuntime(24888): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:69)
12-27 18:35:00.233: E/AndroidRuntime(24888): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:1)
12-27 18:35:00.233: E/AndroidRuntime(24888): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
12-27 18:35:00.233: E/AndroidRuntime(24888): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 19:02:05.643: E/AndroidRuntime(25128): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:69)
12-27 19:02:05.643: E/AndroidRuntime(25128): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:1)
12-27 19:02:05.643: E/AndroidRuntime(25128): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
12-27 19:02:05.643: E/AndroidRuntime(25128): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 19:02:22.373: E/AndroidRuntime(25192): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:69)
12-27 19:02:22.373: E/AndroidRuntime(25192): at com.trueeduc.qrcode.ServerRequest.onProgressUpdate(ServerRequest.java:1)
12-27 19:02:22.373: E/AndroidRuntime(25192): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
12-27 19:02:22.373: E/AndroidRuntime(25192): at android.os.Handler.dispatchMessage(Handler.java:99)
</code></pre>
| 1 | 1,797 |
ESP-12 wifi module's the GPIO pin is HIGH on turning it on but should be LOW
|
<p>I need help. I am using ESP-12 WiFi module to automate lights of my room and controlling it. But when I turn on my ESP-12 WiFi module the GPIO2 pin, which I set for relay input, is going HIGH (by default it should be LOW) and then freezing. But if I connect GPIO pin after turning ESP on then its working fine. How can I avoid this problem. It is connection problem or related to code??</p>
<p>This is my circuit diagram<img src="https://i.stack.imgur.com/2oG3f.jpg" alt="This is my circuit diagram"></p>
<p>This is my Arduino code:</p>
<pre class="lang-cpp prettyprint-override"><code>/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/gpio/0 will set the GPIO2 low,
* http://server_ip/gpio/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/
#include <ESP8266WiFi.h>
const char* ssid = "myssid";
const char* password = "mypassword";
IPAddress ip(192, 168, 1, 10); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 254); // set gateway to match your network
IPAddress subnet(255, 255, 255, 255); // set subnet mask to match your network
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
int status = LOW;
const int pin = 2;
void setup() {
Serial.begin(115200);
delay(100);
// prepare GPIO2
pinMode(pin, OUTPUT);
pinMode(pin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
delay(3000);
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('$');
Serial.println(req);
client.flush();
// Match the request
if (req.indexOf("status") != -1 || req.indexOf("/status") != -1)
Serial.println("Switch is: "+ status);
else if (req.indexOf("on") != -1 || req.indexOf("/on") != -1)
status = HIGH;
else if (req.indexOf("off") != -1 || req.indexOf("/off") != -1)
status = LOW;
else {
Serial.println("invalid request");
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(pin, status);
// Prepare the response
String response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nSwitch is now ";
response += status;
response += "</html>\n";
// Send the response to the client
client.print(response);
client.flush();
delay(1);
Serial.println("Client disonnected"+ status);
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}
</code></pre>
| 1 | 1,119 |
Open USB host communication on a device already connected at the launch of the application
|
<p>I'm developping an application and I need to manage a device using the usb host mode of my tablette.</p>
<p>At this point, I could only activate the USB, at the connection of the device.
Process step :</p>
<ol>
<li>No application launch, connection of the device.<br></li>
<li>Android ask me if I wan't to launch my application<br></li>
<li>I accept<br>
Then the application start, and I could use the USB connection.</li>
</ol>
<p>But, it is not that I want to do :</p>
<ol>
<li>Tablet off, connect the device<br></li>
<li>switch tablet on<br></li>
<li>Launch manualy the application<br></li>
<li>Initialise the usb connection with the device.<br></li>
</ol>
<p>The fact is, that actualy, I need to unconnect/connect manualy the usb on my tablet to have the connection, but me, in my case, the device will be already connected to the tablet, then i need to initialise the connection without unconnect/reconnect the usb.</p>
<p>I have tryed the example provided by Google on the USB Host connexion page that speak about Broadcast receiver, but that don't work, or I don't understant it very well.</p>
<p>My questions is:<br>
Is there any method to open the connection to an usb host device, that is already connected ?
<br>By witch way I need to search to find this dammed solution :D</p>
<p>Here the code that is already implemented to help at understand my problem :</p>
<p>manifest.xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="..."
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="13" />
<application
android:allowBackup="true"
android:icon="@drawable/..."
android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" >
<activity
android:name="...Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>
</application>
</manifest>
</code></pre>
<p>The file res/xml/device_filter.xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device vendor-id="5455" product-id="8238" />
</resources>
</code></pre>
<p>Then the onResume() in my Activity :</p>
<pre><code>@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
UsbManager usbManager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
}
}
</code></pre>
<p>And at the end my method that allow to make the connection :</p>
<pre><code>protected void open(Object o) throws DeviceException {
if (device != null && device.getVendorId() == 5455 && device.getProductId() == 8238) {
int nbEndPoint = 0;
for (int i = 0; i < device.getInterfaceCount(); i++) {
UsbInterface usbInterface = device.getInterface(i);
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint usbEndPoint = usbInterface.getEndpoint(j);
nbEndPoint++;
switch (nbEndPoint) {
case 1:
this.pipeWriteData = usbEndPoint;
case 2:
this.pipeReadCommandResult = usbEndPoint;
case 3:
this.pipeReadAutoStatus = usbEndPoint;
case 4:
this.pipeReadImageData = usbEndPoint;
}
}
}
usbConnection = manager.openDevice(device);
if (usbConnection == null || !usbConnection.claimInterface(device.getInterface(0), true)) {
usbConnection = null;
throw new DeviceException(DeviceException.UNKNOW_ERROR);
}
}
}
</code></pre>
| 1 | 2,004 |
phpmyadmin ignores config.inc.php
|
<p>I have a phpmyadmin installation on a Debian Server and it seems to me like phpmyadmin is ignoring the /etc/phpmyadmin/config.inc.php.</p>
<p>I created a user which should only be able to read one database. When I login to phpmyadmin I get the error message:</p>
<pre><code>Connection for controluser as defined in your configuration failed.
</code></pre>
<p>So I checked the configuration file. In my case it should be /etc/phpmyadmin/config.inc.php</p>
<p>Right now (after many changes) this file contains this:</p>
<pre><code>$i = 0;
$i++;
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['controluser'] = 'phpmyadmin';
$cfg['Servers'][$i]['controlpass'] = 'secret_password';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['hide_db'] = '^(information_schema|performance_schema|mysql|phpmyadmin)$';
</code></pre>
<p>The access permission to this file is set like this:</p>
<pre><code>-rw-r--r-- 1 root root config.inc.php
</code></pre>
<p>I changed the ownership of this file to www-data:www-data without success.
I am able to login as user phpmyadmin and edit the database via phpmyadmin, so the credentials should be ok.
I created and inserted the user pma with no success.</p>
<p>In /var/lib/phpmyadmin/ there is another empty config.inc.php</p>
<pre><code>-rw-r----- 1 root www-data 0 Jan 28 2014 config.inc.php
</code></pre>
<p>The problem is now, that when I login as the user with read access only, I am not able to browse any database. If I try I get the error:</p>
<pre><code>#1142 - INSERT,DELETE command denied to user xxx for table 'pma__recent'
</code></pre>
<p>I have to give the user access to the db phpmyadmin to be able to read the database. Which I do not want to.</p>
<p>After giving access to phpmyadmin database I tried to at least hide the database. Without success.</p>
<p>I read the whole internet, I tried everything, I checked everything. Or apparently not.</p>
<p>Is there a way (log file, debug mode, whatever) to check if the config file and which config file is proceeded by phpmyadmin?</p>
<p>Does anybody find my mistake in this configuration?</p>
<p>Debian version is 7.11.
Server version: 5.5.53-0+deb8u1 - (Debian)
phpmyadmin version: 4.2.12deb2+deb8u2</p>
<p>Thanks,</p>
<p>Jaroslaw</p>
| 1 | 1,436 |
MVC5 app not working in IIS 7 - Error 404 - File or directory not found
|
<p>there! </p>
<p>After some comings and goings, I finally got my very first MVC app working in my dev machine. </p>
<p>The scenario is as following: </p>
<ul>
<li>it's an intranet app (therefore I'm using Windows Authentication)</li>
<li>it's a MVC 5 app (with Bootstrap and jQuery stuff - no .aspx pages)</li>
<li>Entity Framework 6 (Code First)</li>
<li>SQL Server Compact Edition</li>
<li>VS 2013 Express Edition </li>
<li>Server: Windows 2008 R2, running IIS 7 </li>
<li>Hotfix KB980368 installed </li>
<li>IIS registered with asp.net (command aspnet_regiis.exe -i ran) </li>
</ul>
<p>I have some administrative rights on server, so I created a folder to hold the app. Then, using the VS2013, I published the app according to the following configuration:</p>
<ul>
<li>Publish method: File System</li>
<li>Target location: the folder created on server</li>
<li>Configuration: Release</li>
<li>Databases: database publishing is not supported for this publish method</li>
</ul>
<p>The target on server was filled with the following folders: </p>
<ul>
<li>bin (System.Web.MVC, System.Web.Razor, etc )</li>
<li>Content</li>
<li>fonts</li>
<li>Scripts</li>
<li>Views</li>
</ul>
<p>and the following files: </p>
<ul>
<li>Global.asax </li>
<li>packages.config </li>
<li>web.config </li>
</ul>
<p>In IIS 7 I added a Virtual Directory with the Physical Path pointing to that folder previously created. After that I converted the virtual directory to Application. </p>
<p>Tried to run the app and got a weird startIndex error. Then I noticed the App_Data folder was not created. So i corrected that, re-run the app and by this time the databases were created and the default route was properly executed, rendering the main View. </p>
<p>All the views in the app are based upon this _Layout.cshtml, where there is a navbar with some navigating links and dropdown menus. One of these is a simple element that links to the Contact View: </p>
<pre><code><a href="/Home/Contact">Contact</a>
</code></pre>
<p>Well, when I click this element I get a <em>404 - File or directory not found</em> error. And so with all others links. I tried to explicitly write the route at the address bar of the browser and the Contact view was rendered. Of course, user is not supposed to know how to write the routes. For this we create the <em>navbars</em>, links and so on. </p>
<p>Then I began to <em>google</em> for this issue and since then I've read hundreds of articles, posts, pages ... On many of them it was mentioned that this issue would be simply solved adding a couple of lines on web.config, like <a href="https://stackoverflow.com/questions/12495346/asp-net-4-5-mvc-4-not-working-on-windows-server-2008-iis-7/16577694#16577694">this one</a>. I tried. Didn't work. </p>
<p>So, in IIS 7 the configuration is the following:</p>
<ul>
<li>Application Pool: <em>Framework</em>: v4.0.30319, <em>Managed Pipeline</em>: Integrated, <em>Identity</em>: ApplicationPoolApplication</li>
<li>.NET Authorization Rules: Allow All Users</li>
<li>.NET Trust Levels: Full (internal)</li>
<li>Application Settings: <em>ClientValidationEnabled</em>: true, <em>UnobtrusiveJavaScriptEnabled</em>: true, <em>webpages:Enabled</em>: false, <em>webpages:Version</em>: 3.0.0.0</li>
<li>Connection Strings: <em>DbControleDeAcesso</em>: Data Source=|DataDirectory|\ControleDeAcesso.sdf; <em>DbOrcamento</em>: Data Source=|Data Directory|\Orcamento.sdf</li>
<li>Authentication: <em>Anonymous Authentication</em>: Disabled, <em>ASP.NET Impersonation</em>: Disabled, <em>Forms Authentication</em>: Disabled, <em>Windows Authentication</em>: Enabled</li>
<li>Handler Mappings
<ul>
<li>ExtensiolessUrlHandler-Integrated-4.0
<ul>
<li>Path: *.</li>
<li>State: Enabled</li>
<li>Path Type: Unspecified</li>
<li>Handler: System.Web.Handlers.TransferRequestHandler</li>
<li>Entry Type: Local</li>
</ul></li>
<li>ExtensiolessUrlHandler-ISAP-4.0_32bit/64bit
<ul>
<li>Path: *.</li>
<li>State: Enabled</li>
<li>Path Type: Unspecified</li>
<li>Handler: IsapiModule</li>
<li>Entry Type: Inherited</li>
</ul></li>
</ul></li>
<li>Modules
<ul>
<li>UrlRoutingModule-4.0
<ul>
<li>Code: System.Web.RoutingModule</li>
<li>Module Type: Managed</li>
<li>Entry Type: Local</li>
</ul></li>
</ul></li>
</ul>
<p>Bellow I present my <em>web.config</em> file: </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation defaultLanguage="vb" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="DbControleDeAcesso" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=|DataDirectory|\ControleDeAcesso.sdf" />
<add name="DbOrcamento" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=|DataDirectory|\Orcamento.sdf" />
</connectionStrings>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
<modules runAllManagedModulesForAllRequests="true">
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<defaultDocument>
<files>
<remove value="default.aspx" />
<remove value="iisstart.htm" />
<remove value="index.html" />
<remove value="index.htm" />
<remove value="Default.asp" />
<remove value="Default.htm" />
</files>
</defaultDocument>
<!-- <handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers> -->
</system.webServer>
</configuration>
</code></pre>
<p>I don't know whether it's relevant or not, but follows my <em>RouteConfig</em> class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Orcamento.UI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Orcamento", action = "Index", id = UrlParameter.Optional }
);
}
}
}
</code></pre>
<p>I believe I've showed all the significant informations regarding my issue. If I've omitted any, please, just let me know. </p>
<p>I've invested a lot of time and effort to learn how to build a MVC app with EF, jQuery and so on. I got it working on my dev machine. I'm very frustrated that it's not working on production environment. </p>
<p>I'm really hopeful that I'll get some valuable help in here. </p>
<p>Best regards. </p>
<p>Paulo Ricardo Ferreira</p>
| 1 | 4,342 |
Change input shape dimensions for ResNet model (pytorch)
|
<p>I want to feed my <strong>3,320,320 pictures</strong> in an existing ResNet model. The model actually <strong>expects input of size 3,32,32</strong>. As I am afraid of loosing information I don't simply want to resize my pictures.
What is the best way to preprocess my images, so that they are able to run on the ResNet34?
Should I add additional layers in the forward method of ResNet? If yes, what would be a suitable combination in my case?</p>
<pre><code>import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_fitmodule import FitModule
from torch.autograd import Variable
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(FitModule):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(in_planes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion * planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, self.expansion * planes,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(self.expansion * planes)
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out += self.shortcut(x)
out = F.relu(out)
return out
class ResNet(FitModule):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = conv3x3(3, 64)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
self.linear = nn.Linear(512 * block.expansion, num_classes)
def _make_layer(self, block, planes, num_blocks, stride):
strides = [stride] + [1] * (num_blocks - 1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
def forward(self, x): # add additional layers here?
x = x.float()
out = F.relu(self.bn1(self.conv1(x).float()).float())
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
def ResNet34():
return ResNet(BasicBlock, [3, 4, 6, 3])
</code></pre>
<p>Thanks plenty!</p>
<p>Regards,
Fabian</p>
| 1 | 1,737 |
How can I call a WebMethod to return json with ajax?
|
<p>I get 404 every time I try this. I can't find the error in my code. I have other webmethod to delete and it works. I am using a WebForm , ADO.NET with a connection string, .NET 4.5.</p>
<pre><code>[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
//Return a DataTable from database with a stored procedure
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
return DataTableToJSONWithJavaScriptSerializer(dt);
}
public static string DataTableToJSONWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
</code></pre>
<p>This is the ajax call:</p>
<pre><code>$(document).ready(function () {
$("#obtenerLicencias").click(function () {
$.ajax({
type: "POST",
url: "CnfListaTipoLicencias.aspx/ListarTiposLicencia",
data: '{ }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
alert(JSON.parse(data));
},
failure: function (response) {
alert("Error");
},
error: function (error) {
alert("error");
}
});
});
});
</code></pre>
<p>Edit:
I have tried this, but it doesnot work, I get 404 again:</p>
<pre><code>[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ListarTiposLicencia()
{
TipoLicenciaBL objTipoLicencia = new TipoLicenciaBL();
DataTable dt = objTipoLicencia.DevolverListaTipoLicencia(String.Empty, String.Empty);
string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}
</code></pre>
| 1 | 1,040 |
error occur on HttpTransportSE call method in android
|
<p>i am making one example of calling wsdl webservice made in Zend (framework of php) and i am using ksoap api(jar file) and i got this error </p>
<p><code>org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <definitions name='Ccc_Core_Model_Api_Server' targetNamespace='http://gsmadmin.com/zendtest/api'>@2:385 in java.io.InputStreamReader@40539078)</code> </p>
<p>i read all questions of stackoverflow related to this error, but i am not able to solve this error.</p>
<p>what is the real solution of this error ?</p>
<p>please help me.</p>
<p>my wsdl xml file is :</p>
<pre><code><?xml version="1.0"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://gsmadmin.com/zendtest/api" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" name="Ccc_Core_Model_Api_Server" targetNamespace="http://gsmadmin.com/zendtest/api">
<types>
<xsd:schema targetNamespace="http://gsmadmin.com/zendtest/api"/>
</types>
<portType name="Ccc_Core_Model_Api_ServerPort">
<operation name="addition">
<documentation> This method is used for addition of two numbers</documentation>
<input message="tns:additionIn"/>
<output message="tns:additionOut"/>
</operation>
<operation name="substraction">
<documentation> This method is used for substraction of two numbers</documentation>
<input message="tns:substractionIn"/>
<output message="tns:substractionOut"/>
</operation>
<operation name="multiple">
<documentation>This method is used for multiple of two numbers</documentation>
<input message="tns:multipleIn"/>
<output message="tns:multipleOut"/>
</operation>
<operation name="division">
<documentation>This method is used for division of two numbers</documentation>
<input message="tns:divisionIn"/>
<output message="tns:divisionOut"/>
</operation>
</portType>
<binding name="Ccc_Core_Model_Api_ServerBinding" type="tns:Ccc_Core_Model_Api_ServerPort">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="addition">
<soap:operation soapAction="http://gsmadmin.com/zendtest/api#addition"/>
<input>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</input>
<output>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</output>
</operation>
<operation name="substraction">
<soap:operation soapAction="http://gsmadmin.com/zendtest/api#substraction"/>
<input>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</input>
<output>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</output>
</operation>
<operation name="multiple">
<soap:operation soapAction="http://gsmadmin.com/zendtest/api#multiple"/>
<input>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</input>
<output>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</output>
</operation>
<operation name="division">
<soap:operation soapAction="http://gsmadmin.com/zendtest/api#division"/>
<input>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</input>
<output>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://gsmadmin.com/zendtest/api"/>
</output>
</operation>
</binding>
<service name="Ccc_Core_Model_Api_ServerService">
<port name="Ccc_Core_Model_Api_ServerPort" binding="tns:Ccc_Core_Model_Api_ServerBinding">
<soap:address location="http://gsmadmin.com/zendtest/api"/>
</port>
</service>
<message name="additionIn">
<part name="param1" type="xsd:int"/>
<part name="param2" type="xsd:int"/>
</message>
<message name="additionOut">
<part name="return" type="xsd:float"/>
</message>
<message name="substractionIn">
<part name="param1" type="xsd:int"/>
<part name="param2" type="xsd:int"/>
</message>
<message name="substractionOut">
<part name="return" type="xsd:float"/>
</message>
<message name="multipleIn">
<part name="param1" type="xsd:int"/>
<part name="param2" type="xsd:int"/>
</message>
<message name="multipleOut">
<part name="return" type="xsd:float"/>
</message>
<message name="divisionIn">
<part name="param1" type="xsd:float"/>
<part name="param2" type="xsd:float"/>
</message>
<message name="divisionOut">
<part name="return" type="xsd:float"/>
</message>
</definitions>
</code></pre>
<p>exception stack trace: </p>
<pre><code>06-14 15:45:49.527: D/AndroidRuntime(2055): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
06-14 15:45:49.527: D/AndroidRuntime(2055): CheckJNI is ON
06-14 15:45:50.587: D/AndroidRuntime(2055): Calling main entry com.android.commands.pm.Pm
06-14 15:45:50.637: D/AndroidRuntime(2055): Shutting down VM
06-14 15:45:50.657: D/dalvikvm(2055): GC_CONCURRENT freed 101K, 71% free 297K/1024K, external 0K/0K, paused 1ms+1ms
06-14 15:45:50.657: I/AndroidRuntime(2055): NOTE: attach of thread 'Binder Thread #3' failed
06-14 15:45:50.669: D/jdwp(2055): Got wake-up signal, bailing out of select
06-14 15:45:50.677: D/dalvikvm(2055): Debugger has detached; object registry had 1 entries
06-14 15:45:51.247: D/AndroidRuntime(2065): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
06-14 15:45:51.247: D/AndroidRuntime(2065): CheckJNI is ON
06-14 15:45:52.147: D/AndroidRuntime(2065): Calling main entry com.android.commands.am.Am
06-14 15:45:52.197: I/ActivityManager(61): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.phpwebservice/.PhpwebservicedemoActivity } from pid 2065
06-14 15:45:52.267: D/AndroidRuntime(2065): Shutting down VM
06-14 15:45:52.317: D/dalvikvm(2065): GC_CONCURRENT freed 103K, 69% free 319K/1024K, external 0K/0K, paused 2ms+1ms
06-14 15:45:52.389: V/Adapter(1868): URL = http://gsmadmin.com/zendtest/api?wsdl
06-14 15:45:52.389: D/jdwp(2065): Got wake-up signal, bailing out of select
06-14 15:45:52.389: D/dalvikvm(2065): Debugger has detached; object registry had 1 entries
06-14 15:45:52.447: V/Adapter(1868): NAMESPACE = http://gsmadmin.com/zendtest/api
06-14 15:45:52.447: V/Adapter(1868): METHOD_NAME = addition
06-14 15:45:52.447: V/Adapter(1868): SOAP_ACTION = http://gsmadmin.com/zendtest/api#addition
06-14 15:45:52.447: V/Adapter(1868): request = addition{param1=10; param2=2; }
06-14 15:45:52.487: V/Adapter(1868): param1 = 10 param2 = 2
06-14 15:45:53.737: W/System.err(1868): org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <definitions name='Ccc_Core_Model_Api_Server' targetNamespace='http://gsmadmin.com/zendtest/api'>@2:385 in java.io.InputStreamReader@40541998)
06-14 15:45:53.757: W/System.err(1868): at org.kxml2.io.KXmlParser.exception(KXmlParser.java:273)
06-14 15:45:53.757: W/System.err(1868): at org.kxml2.io.KXmlParser.require(KXmlParser.java:1424)
06-14 15:45:53.757: W/System.err(1868): at org.ksoap2.SoapEnvelope.parse(SoapEnvelope.java:127)
06-14 15:45:53.766: W/System.err(1868): at org.ksoap2.transport.Transport.parseResponse(Transport.java:63)
06-14 15:45:53.766: W/System.err(1868): at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:100)
06-14 15:45:53.766: W/System.err(1868): at com.phpwebservice.Adapter.addition(Adapter.java:59)
06-14 15:45:53.777: W/System.err(1868): at com.phpwebservice.PhpwebservicedemoActivity.onCreate(PhpwebservicedemoActivity.java:53)
06-14 15:45:53.777: W/System.err(1868): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-14 15:45:53.787: W/System.err(1868): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
06-14 15:45:53.787: W/System.err(1868): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-14 15:45:53.787: W/System.err(1868): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-14 15:45:53.787: W/System.err(1868): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-14 15:45:53.809: W/System.err(1868): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 15:45:53.809: W/System.err(1868): at android.os.Looper.loop(Looper.java:123)
06-14 15:45:53.809: W/System.err(1868): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-14 15:45:53.809: W/System.err(1868): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 15:45:53.817: W/System.err(1868): at java.lang.reflect.Method.invoke(Method.java:507)
06-14 15:45:53.817: W/System.err(1868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-14 15:45:53.817: W/System.err(1868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-14 15:45:53.817: W/System.err(1868): at dalvik.system.NativeStart.main(Native Method)
06-14 15:45:53.817: V/log_tag(1868): total addition = 0.0
06-14 15:45:54.069: I/ActivityManager(61): Displayed com.phpwebservice/.PhpwebservicedemoActivity: +1s835ms
06-14 15:45:59.297: D/dalvikvm(126): GC_EXPLICIT freed 4K, 50% free 3003K/5895K, external 5903K/7371K, paused 63ms
</code></pre>
<p>thanks in advance</p>
| 1 | 4,597 |
Not able to play live video through ExoPlayer
|
<p>I am using ExoPlayer for playing video in Android,. We are using the ExoPlayer for playing mp4 and live videos. But sometime we are getting the exception described below.</p>
<pre><code>> 12-01 14:15:09.388 12080-12517/com.mse.monumentalsnetwork
> E/ExoPlayerImplInternal: Source error.
> com.google.android.exoplayer2.source.UnrecognizedInputFormatException:
> Input does not start with the #EXTM3U header.
> at
> com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistParser.parse(HlsPlaylistParser.java:119)
> at
> com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistParser.parse(HlsPlaylistParser.java:43)
> at
> com.google.android.exoplayer2.upstream.ParsingLoadable.load(ParsingLoadable.java:115)
> at
> com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:315)
> at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
> at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
> at java.lang.Thread.run(Thread.java:818)
</code></pre>
<p>So Please help me on it.</p>
| 1 | 1,114 |
Android: ListView Multiple Selection
|
<p>Problem:</p>
<p>When i click on the 2nd checkbox item in the listview then automatically 10th item is checked. I can not understand what's happen?</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
public class ItemAdapter extends ArrayAdapter<MyItem> {
private int resId;
Context context;
private ArrayList<MyItem> itemList;
public ItemAdapter(Context context, int textViewResourceId,
List<MyItem> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.resId = textViewResourceId;
this.itemList = new ArrayList<MyItem>();
this.itemList.addAll(objects);
}
private class ViewHolder {
public boolean needInflate;
public TextView txtItemName;
public CheckBox chkItem;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
MyItem cell = (MyItem) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.txtItemName = (TextView) convertView
.findViewById(R.id.tvItemName);
holder.chkItem = (CheckBox) convertView.findViewById(R.id.chkItem);
holder.chkItem
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//Log.i("Pos", "" + position);
//cell.setSelected(buttonView.isChecked());
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(cell.getName());
return convertView;
}
}
</code></pre>
<p>"MyItem" is my pojo Class.</p>
<p>OnCreate Code:</p>
<pre><code> lvItemName = (ListView) findViewById(R.id.lvItemName);
List<MyItem> myItemsList = new ArrayList<MyItem>();
for (int i = 0; i < items.length; i++) {
MyItem item = new MyItem(items[i], false);
myItemsList.add(item);
}
ItemAdapter adapter = new ItemAdapter(this, R.layout.listitem,
myItemsList);
lvItemName.setAdapter(adapter);
lvItemName.setOnItemClickListener(this);
</code></pre>
<p>"items" is my String Array.</p>
<p>Thanks in Advance.</p>
| 1 | 1,208 |
Unhandled Exception Error in Java even with try-catch
|
<p>I am quite new to Java and started learning on YouTube. To practice GUI Programs, I decided to make my own and am now trying to resize an image to add to a button in my aplication. I searched how to resize images and found some source code online which I decided to test and put in my own program, but when I call the method I get an <code>unreported exception java.io.IOException; must be caught or declared to be thrown</code> error and the IntelliJ IDE says <code>Unhandled exception: java.io.IOException</code>. I have the <code>try-catch</code> blocks in my code, but this still comes up. How can I fix this? Here is some of my code:</p>
<p><code>Images.java</code> (class with the resizer method I found online) the <code>try-catch</code> I put in myself.</p>
<pre><code>import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Images {
//Image resizer method for scaling images
void resizeImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException {
//reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
//creates output image
BufferedImage outputImage = new BufferedImagee(scaledWidth, scaledHeight, inputImage.getType());
//scales the inputImage to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1);
//writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
try {
inputFile = null;
inputImage = ImageIO.read(inputFile);
}
catch(IOException e){
e.printStackTrace();
System.out.println("image file path is null");
}
}
}
</code></pre>
<p><code>GUI.java</code> (where the error appears when I try to call the method). The error appears at <code>plus.resizeImage</code>.</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.company.Images;
public class GUI extends JFrame {
//This will be used for dimensions of the window
private int height, width;
GUI(int w, int h) {
super("OS Control");
setWidth(w);
setHeight(h);
setSize(getWidth(), getHeight());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setContent();
setVisible(true);
}
//Gets and sets for height and width of window
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return width;
}
////////////////////////////////////////////////
/*Method with the actual contents of the aplication
i.e buttons, text fields, etc.
*/
void setContent() {
//variables used in the methods for ease of changing if needed
int buttonWidth, buttonHeight;
int searchBarWidth, searchBarHeight;
buttonWidth = 200;
buttonHeight = 100;
searchBarWidth = 350;
searchBarHeight = 25;
//Panel for the two center buttons
JPanel buttons = new JPanel();
//flow layout to center horizontally
buttons.setLayout(new FlowLayout());
buttons.setBackground(Color.decode("#9E9E9E"));
JButton mechanicButton = new JButton("Mecanicos");
mechanicButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
mechanicButton.setFocusable(false);
mechanicButton.addActionListener(new MechanicButtonEventHandling());
buttons.add(mechanicButton);
JButton osButton = new JButton("Ordens de Servico");
osButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
osButton.setFocusable(false);
osButton.addActionListener(new OSButtonEventHandling());
buttons.add(osButton);
JPanel center = new JPanel();
//gridbag layout to center vertically
center.setLayout(new GridBagLayout());
center.setBackground(Color.decode("#9E9E9E"));
//combine the two to center horizontally and vertically
center.add(buttons);
JPanel search = new JPanel();
search.setLayout(new FlowLayout());
search.setBackground(Color.decode("#9E9E9E"));
search.setSize(new Dimension(getWidth(), searchBarHeight));
JTextField searchBar = new JTextField("Pesquisar: ");
searchBar.setPreferredSize(new Dimension(searchBarWidth, searchBarHeight));
searchBar.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 10));
search.add(searchBar);
JPanel plusPanel = new JPanel();
plusPanel.setLayout(new BorderLayout());
plusPanel.setSize(new Dimension(10, 10));
Images plus = new Images();
plus.resizeImage("plus.png","plusButton.png", 10, 10);
ImageIcon plusButtonImage = new ImageIcon("plusButton.png");
JButton plusButton = new JButton(plusButtonImage);
plusButton.setSize(new Dimension(10, 10));
plusPanel.add(plusButton, BorderLayout.SOUTH);
//add to jframe
add(search);
add(center);
add(plusPanel);
}
private class MechanicButtonEventHandling implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame mechanicList = new JFrame("Lista de Mecanicos");
mechanicList.setSize(getWidth(), getHeight());
mechanicList.setLocation(100, 100);
mechanicList.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
mechanicList.setVisible(true);
}
}
private class OSButtonEventHandling implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame osList = new JFrame("Lista de ordens de servico");
osList.setSize(getWidth(), getHeight());
osList.setLocation(700, 100);
osList.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
osList.setVisible(true);
}
}
}
</code></pre>
| 1 | 2,469 |
algorithm - Coin change in java
|
<p>I have seen quite many coin change problems and this one is quite unique. I tried using DP and recursion but I wasn't able to solve it. </p>
<p>This is the problem:</p>
<p>Let's say given a price, X, where X is in cents and I have 5 finite coin denominations, 1,5,10,20,50. I have different number of 1,5,10,20,50-cent coins. I want to make price X with the maximum number of coins. How do I do it?(Assuming X can always be made with the coins at hand)</p>
<p>For example, if price X = 52 and</p>
<p>i have 3 of 1-cent coins</p>
<p>I have 4 of 5-cent coins</p>
<p>I have 8 of 10-cent coins</p>
<p>I have 6 of 20-cent coins</p>
<p>I have 4 of 50-cent coins</p>
<p>I want to find the maximum number of coins and number of ways that can be used to make this price, in this case: two 1-cent, four 5-cent, 3 10-cent coins will be the answer. </p>
<p>I have thought of a usable algorithm where first, I put the number and value of each coin into an arraylist, then I pass the array list into a recursive function that will:</p>
<p>First, deduct the price with the smallest denomination, then add 1 to int max, where max = number of coins currently used. Then, recursively call the function with price=price-smallest denomination.</p>
<p>Second, I'll recursively call the function by taking the next smallest available denomination. </p>
<p>My base cases are that if</p>
<pre><code>1) price <0, return 0
2) if price ==0 and max=currMax, return 1
3) if price>0, recursively call the 2 recursions listed above
</code></pre>
<p>EDIT: to add in code.</p>
<p>I modified the question a little bit. </p>
<pre><code> 1 import java.util.*;
2 public class CountingChange{
3 int max = 0; //maximum number of way to pay price
4 int way = 0; //number of ways to make price
5 private void run(){
6 Scanner sc = new Scanner(System.in);
7 int price = sc.nextInt();
8 ArrayList<Integer> coins = new ArrayList<Integer>(); //kinds of coins. assumed to be 1,5,10,20,50
9 for (int i = 0; i <5; i++){
10 int coin = sc.nextInt();
11 coins.add(i,coin);
12 }
13 int currMax = 0;
14 counter(price,coins,currMax);
15 System.out.println(String.valueOf(max) + " " + String.valueOf(way)); //output eg: 10 5, where 10 = max coins, 5 = ways
16 }
17 private void counter(int price,ArrayList<Integer> coins,int currMax){
18 currMax += 1;
19 if (coins.size()==0) return;
else if((coins.get(0)<0)||(price<0)){
20 //check if AL is empty(no way to make change), smallest coin < 0(invalid), price<0(invalid)
21 return;
22 }
23 else if (price==0){//successful change made
24 if (currMax==max){ //check max coins used
25 way+=1;
26 }
27 else if (currMax>max){
28 way = 1;
29 max = currMax;
30 }
31 }
32 else if(price>0){
33 coins.set(0,coins.get(0)-1);//use smallest coin
34 counter(price-coins.get(0),coins,currMax);
35 coins.remove(0);//use other coins except smallest
36 counter(price,coins,currMax);
37 }
38 }
39 public static void main(String[] args){
40 CountingChange myCountingChange = new CountingChange();
41 myCountingChange.run();
42 }
43 }
</code></pre>
<p>I believe my problem is that I was deducting the number of coins(instead of the value of coin) used to make the price. But I really have no idea how to use a suitable//what kind of data structure to store my coins and its value.</p>
| 1 | 1,518 |
How to make Python Dict from JSON data using BeautifulSoup
|
<p>I am scraping a website from which I need certain information. The information I need is the dictionary after <code>Sw.preloadedData["overview"] =</code>:</p>
<pre><code><script type="text/javascript">
Sw.preloadedData = {};
Sw.preloadedData["overview"] = {"Title":"Facebook","Description":"A social utility that connects people, to keep up with friends, upload photos, share links and videos.","GlobalRank":[1,28115594,0],"Country":840,"CountryRanks":{"12":[1,830254,0],"818":[1,463162,0],"604":[1,599566,0],"608":[1,986465,0],"484":[1,1329484,0],"504":[1,672216,0],"862":[1,724854,0],"688":[1,534093,0],"702":[1,427637,0],"703":[1,341310,0],"756":[1,903074,0],"840":[1,5142062,0],"250":[1,1887449,0],"724":[2,1432992,0],"764":[1,857348,0],"76":[1,2733763,0],"784":[1,564929,0],"376":[1,390754,0],"792":[1,979507,0],"804":[8,1073943,1],"344":[1,284415,0],"348":[1,471458,0],"643":[8,1424933,1],"682":[1,692392,0],"380":[1,1441457,0],"392":[3,979893,1],"170":[1,1048409,0],"191":[1,348589,0],"620":[1,841554,0],"642":[1,814441,0],"356":[2,2356839,1],"528":[1,1092022,0],"616":[2,1430485,0],"360":[1,1541560,0],"372":[1,361215,0],"458":[1,851821,0],"36":[1,857177,0],"578":[1,349987,0],"586":[1,553155,0],"704":[2,918752,0],"710":[2,439567,1],"826":[1,2062694,0],"124":[1,1950051,0],"752":[1,577990,0],"300":[1,654931,0],"203":[1,623702,0],"208":[1,350294,0],"32":[1,1223765,0],"100":[1,473283,0],"554":[1,268216,0],"56":[1,1124680,0],"152":[1,725504,0],"156":[25,375144,-1],"158":[1,408462,0],"276":[1,2752131,0],"40":[1,700209,0],"410":[1,327519,0],"246":[1,387528,0]},"Category":"Internet_and_Telecom/Social_Network","CategoryRank":[1,27564,0],"TrafficReach":[0.32364475161620337,0.32385066912312122,0.32476481437213323,0.31948943452696626,0.310612833573507,0.30867420840432391,0.30666509584041279,0.31334128772658171,0.33551546090119239,0.3260064922555041,0.33396164810609369,0.33999592327084549,0.33711315799626795,0.32152719433964483,0.31986157880865085,0.32069766148623413,0.3306823871380894,0.32266565637788247,0.29034777869603251,0.29286953998372667,0.29969130766646174,0.3071060984450904,0.28517166164955293,0.29038329556338477,0.2845053957123595],"TrafficReachStart":1346457600,"TrafficReachEnd":1362096000,"Engagments":[{"Year":2012,"Month":9,"Reach":[0.32364839148251978,0.012621437484750864],"Time":[1225.8536260294338,0.00090266734593069664],"PPV":[21.312597646825566,0.034059623863791355],"Bounce":[0.18813037420762707,0.043481349041723627]},{"Year":2012,"Month":10,"Reach":[0.31325536305080282,-0.032112096661782052],"Time":[1308.5613956266043,0.0674695313053506],"PPV":[25.612224490959978,0.20174109770119109],"Bounce":[0.17672838267013638,-0.060606861520974054]},{"Year":2012,"Month":11,"Reach":[0.33350274816471975,0.064635398151613677],"Time":[1300.8263833937028,-0.0059110808699942563],"PPV":[24.020971463806184,-0.062128653749518592],"Bounce":[0.186024790640559,0.052602801145837264]},{"Year":2012,"Month":12,"Reach":[0.32441610872340648,-0.027246070658540122],"Time":[1331.3137947173564,0.023436956470790138],"PPV":[24.916914500937356,0.03729836815638965],"Bounce":[0.18107629094748873,-0.026601291559208651]},{"Year":2013,"Month":1,"Reach":[0.29998222452228729,-0.075316494909170029],"Time":[1334.5042854365543,0.0023964979044441836],"PPV":[25.52485794831804,0.024398825438752159],"Bounce":[0.18097482510209897,-0.00056034859593612207]},{"Year":2013,"Month":2,"Reach":[0.2842911869016958,-0.052306557982157109],"Time":[1281.8427161473487,-0.039461521303379321],"PPV":[23.201378273544368,-0.091028113828417134],"Bounce":[0.18673378186827794,0.031821866731629678]}],"TrafficSources":{"Search":0.12679771428369516,"Social":0.0095590714393366649,"Mail":0.018352638254343783,"Paid Referrals":0.0010665044954870533,"Direct":0.60148809501325917,"Referrals":0.24273597651387802},"RedirectUrl":"facebook.com"};
Sw.period = { month:2 ,year:2013,period:6 };
Sw.siteDomain = "Facebook.com";
Sw.siteCategory = "Internet_and_Telecom/Social_Network";
Sw.siteCountry = "840";
</script>
</code></pre>
<p>If I have the script tag selected with beautifulsoup, how then can I get that (JSON ?) dictionary as a Python Dict?</p>
<p>First I would need to select only that JSON object - <strong>how can I do that?</strong></p>
<p>And than I would need to translate that JSON object to a Python Dict.</p>
| 1 | 1,922 |
snmpget : Unknown user name
|
<p>I am trying to install <code>net-snmp</code> from scratch to make <code>snmpv3</code> to work on my computer.</p>
<p>I did install <code>net-snmp</code> and create the user, but when I want to make <code>snmpget</code> it reject me with <code>snmpget: Unknown user name</code></p>
<hr>
<ul>
<li>To install net-snmp I followed the <a href="http://net-snmp.sourceforge.net/wiki/index.php/Net-Snmp_on_Ubuntu" rel="nofollow noreferrer">official guide</a></li>
<li><p>I did install the packages <code>libperl-dev</code>, <code>snmp-mibs-downloader</code> and <code>snmp</code> too using <code>sudo apt-get install</code></p></li>
<li><p>Here is my <code>/usr/local/share/snmp</code> configuration where you can find the particular line <code>rouser neutg</code></p></li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code>###############################################################################
#
# EXAMPLE.conf:
# An example configuration file for configuring the Net-SNMP agent ('snmpd')
# See the 'snmpd.conf(5)' man page for details
#
# Some entries are deliberately commented out, and will need to be explicitly activated
#
###############################################################################
#
# AGENT BEHAVIOUR
#
# Listen for connections from the local system only
# agentAddress udp:127.0.0.1:161
# Listen for connections on all interfaces (both IPv4 *and* IPv6)
agentAddress udp:161,udp6:[::1]:161
###############################################################################
#
# SNMPv3 AUTHENTICATION
#
# Note that these particular settings don't actually belong here.
# They should be copied to the file /var/lib/snmp/snmpd.conf
# and the passwords changed, before being uncommented in that file *only*.
# Then restart the agent
# createUser authOnlyUser MD5 "remember to change this password"
# createUser authPrivUser SHA "remember to change this one too" DES
# createUser internalUser MD5 "this is only ever used internally, but still change the password"
# If you also change the usernames (which might be sensible),
# then remember to update the other occurances in this example config file to match.
###############################################################################
#
# ACCESS CONTROL
#
# system + hrSystem groups only
view systemonly included .1.3.6.1.2.1.1
view systemonly included .1.3.6.1.2.1.25.1
# Full access from the local host
#rocommunity public localhost
# Default access to basic system info
rocommunity public default -V systemonly
# rocommunity6 is for IPv6
rocommunity6 public default -V systemonly
# Full access from an example network
# Adjust this network address to match your local
# settings, change the community string,
# and check the 'agentAddress' setting above
#rocommunity secret 10.0.0.0/16
# Full read-only access for SNMPv3
rouser authOnlyUser
# Full write access for encrypted requests
# Remember to activate the 'createUser' lines above
#rwuser authPrivUser priv
# It's no longer typically necessary to use the full 'com2sec/group/access' configuration
# r[ow]user and r[ow]community, together with suitable views, should cover most requirements
###############################################################################
#
# SYSTEM INFORMATION
#
# Note that setting these values here, results in the corresponding MIB objects being 'read-only'
# See snmpd.conf(5) for more details
sysLocation Sitting on the Dock of the Bay
sysContact Me <me@example.org>
# Application + End-to-End layers
sysServices 72
#
# Process Monitoring
#
# At least one 'mountd' process
proc mountd
# No more than 4 'ntalkd' processes - 0 is OK
proc ntalkd 4
# At least one 'sendmail' process, but no more than 10
proc sendmail 10 1
# Walk the UCD-SNMP-MIB::prTable to see the resulting output
# Note that this table will be empty if there are no "proc" entries in the snmpd.conf file
#
# Disk Monitoring
#
# 10MBs required on root disk, 5% free on /var, 10% free on all other disks
disk / 10000
disk /var 5%
includeAllDisks 10%
# Walk the UCD-SNMP-MIB::dskTable to see the resulting output
# Note that this table will be empty if there are no "disk" entries in the snmpd.conf file
#
# System Load
#
# Unacceptable 1-, 5-, and 15-minute load averages
load 12 10 5
# Walk the UCD-SNMP-MIB::laTable to see the resulting output
# Note that this table *will* be populated, even without a "load" entry in the snmpd.conf file
###############################################################################
#
# ACTIVE MONITORING
#
# send SNMPv1 traps
trapsink localhost public
# send SNMPv2c traps
#trap2sink localhost public
# send SNMPv2c INFORMs
#informsink localhost public
# Note that you typically only want *one* of these three lines
# Uncommenting two (or all three) will result in multiple copies of each notification.
#
# Event MIB - automatically generate alerts
#
# Remember to activate the 'createUser' lines above
iquerySecName internalUser
rouser internalUser
# generate traps on UCD error conditions
defaultMonitors yes
# generate traps on linkUp/Down
linkUpDownNotifications yes
###############################################################################
#
# EXTENDING THE AGENT
#
#
# Arbitrary extension commands
#
extend test1 /bin/echo Hello, world!
extend-sh test2 echo Hello, world! ; echo Hi there ; exit 35
#extend-sh test3 /bin/sh /tmp/shtest
# Note that this last entry requires the script '/tmp/shtest' to be created first,
# containing the same three shell commands, before the line is uncommented
# Walk the NET-SNMP-EXTEND-MIB tables (nsExtendConfigTable, nsExtendOutput1Table
# and nsExtendOutput2Table) to see the resulting output
# Note that the "extend" directive supercedes the previous "exec" and "sh" directives
# However, walking the UCD-SNMP-MIB::extTable should still returns the same output,
# as well as the fuller results in the above tables.
#
# "Pass-through" MIB extension command
#
#pass .1.3.6.1.4.1.8072.2.255 /bin/sh PREFIX/local/passtest
#pass .1.3.6.1.4.1.8072.2.255 /usr/bin/perl PREFIX/local/passtest.pl
# Note that this requires one of the two 'passtest' scripts to be installed first,
# before the appropriate line is uncommented.
# These scripts can be found in the 'local' directory of the source distribution,
# and are not installed automatically.
# Walk the NET-SNMP-PASS-MIB::netSnmpPassExamples subtree to see the resulting output
#
# AgentX Sub-agents
#
# Run as an AgentX master agent
master agentx
# Listen for network connections (from localhost)
# rather than the default named socket /var/agentx/master
#agentXSocket tcp:localhost:705
rouser neutg</code></pre>
</div>
</div>
</p>
<ul>
<li>Here is my persistant configuration file <code>/var/net-snmp/snmpd.conf</code></li>
</ul>
<hr>
<pre><code>createUser neutg SHA "password" AES passphrase
</code></pre>
<hr>
<p>The command I run is :</p>
<pre><code>snmpget -u neutg -A password -a SHA -X 'passphrase'
-x AES -l authPriv localhost -v 3 1.3.6.1.2.1.1
</code></pre>
<p><a href="https://i.stack.imgur.com/PskFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PskFE.png" alt="enter image description here"></a></p>
<hr>
<p>I don't understand why it do not take in count my user. <em>(I did restart the snmpd after entering the user - multiple times!)</em></p>
<p><a href="https://i.stack.imgur.com/IGkC5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IGkC5.png" alt="enter image description here"></a></p>
<hr>
<p>The version of <code>net-snmp</code> I use :</p>
<p><a href="https://i.stack.imgur.com/YpjfI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YpjfI.png" alt="enter image description here"></a></p>
<p>Thanks in advance :)</p>
| 1 | 3,714 |
Python: How can we smooth a noisy signal using moving average?
|
<p>For an evaluation of a random forest regression, I am trying to improve a result using a <code>moving average filter</code> after fitting a model using a <code>RandomForestRegressor</code> for a dataset found in <a href="https://drive.google.com/open?id=0B2Iv8dfU4fTUdlE0VUJKUnctSkE" rel="nofollow noreferrer">this link</a></p>
<pre><code>import pandas as pd
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import r2_score, mean_squared_error, make_scorer
from sklearn.model_selection import train_test_split
from math import sqrt
from sklearn.cross_validation import train_test_split
n_features=3000
df = pd.read_csv('cubic32.csv')
for i in range(1,n_features):
df['X_t'+str(i)] = df['X'].shift(i)
print(df)
df.dropna(inplace=True)
X = df.drop('Y', axis=1)
y = df['Y']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40)
X_train = X_train.drop('time', axis=1)
X_test = X_test.drop('time', axis=1)
parameters = {'n_estimators': [10]}
clf_rf = RandomForestRegressor(random_state=1)
clf = GridSearchCV(clf_rf, parameters, cv=5, scoring='neg_mean_squared_error', n_jobs=-1)
model = clf.fit(X_train, y_train)
model.cv_results_['params'][model.best_index_]
math.sqrt(model.best_score_*-1)
model.grid_scores_
#####
print()
print(model.grid_scores_)
print("The best score: ",model.best_score_)
print("RMSE:",math.sqrt(model.best_score_*-1))
clf_rf.fit(X_train,y_train)
modelPrediction = clf_rf.predict(X_test)
print(modelPrediction)
print("Number of predictions:",len(modelPrediction))
meanSquaredError=mean_squared_error(y_test, modelPrediction)
print("Mean Square Error (MSE):", meanSquaredError)
rootMeanSquaredError = sqrt(meanSquaredError)
print("Root-Mean-Square Error (RMSE):", rootMeanSquaredError)
fig, ax = plt.subplots()
index_values=range(0,len(y_test))
y_test.sort_index(inplace=True)
X_test.sort_index(inplace=True)
modelPred_test = clf_rf.predict(X_test)
ax.plot(pd.Series(index_values), y_test.values)
smoothed = np.convolve(modelPred_test, np.ones(10)/10)
PlotInOne=pd.DataFrame(pd.concat([pd.Series(smoothed), pd.Series(y_test.values)], axis=1))
plt.figure(); PlotInOne.plot(); plt.legend(loc='best')
</code></pre>
<p>However, the plot of the predicted values seems (as shown below) to be very coarse (the blue line) even if i am smoothing the prediction values like the following</p>
<pre><code>smoothed = np.convolve(modelPred_test, np.ones(10)/10)
</code></pre>
<p>The orange line is a plot of the actual value.</p>
<p><a href="https://i.stack.imgur.com/oXDN0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oXDN0.png" alt="enter image description here"></a></p>
<p>Is there any way that we can penalize the prediction error (or smooth the noise of the signal using a moving average or other smoothing techniques) so that we get a plot closer to the actual value? I am also trying to increase the number of estimators for the random forest tree (<code>n_estimators</code>), but it doesn't seem to improve much. If we plot the actual value alone, it looks like the following.</p>
<p><a href="https://i.stack.imgur.com/zIR9o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zIR9o.png" alt="enter image description here"></a></p>
| 1 | 1,252 |
How to update the same component with different params in Angular
|
<p>I've done the <a href="https://angular.io/tutorial" rel="nofollow noreferrer">tour of heroes</a> from angular. It works perfectly. </p>
<p>Now I want to put the dashboard component in the hero detail view. So it shows me the top of heroes, and after that, the hero detail view.
<a href="https://i.stack.imgur.com/yGDt1.png" rel="nofollow noreferrer">Image</a> </p>
<p>I have a Router link that loads the same component, but with different params. I want to know, what to do so that when I click on any element from the dashboard this one load a different hero. </p>
<p><strong>This is the code of the hero-detail.component.html</strong></p>
<pre><code><app-dashboard></app-dashboard>
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
</label>
<div><span>name: </span>{{hero.name}}</div>
</div>
<button (click)="goBack()">go back</button>
<button (click)="save()">save</button>
</div>
</code></pre>
<p><strong>hero detail class</strong></p>
<pre><code>export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
save(): void {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
}
</code></pre>
<p><strong>The dashboard code</strong></p>
<pre><code><a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>
</code></pre>
<p><strong>The router is the same as the tutorial.</strong> </p>
<pre><code>const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'heroes', component: HeroesComponent },
{ path: 'detail/:id', component: HeroDetailComponent }
];
</code></pre>
<p><strong>A bad solution:</strong></p>
<p>After research a little i found the possibility to add the <em>(click)="reloadRoute()"</em> to the link, but this one refresh all the page. </p>
<pre><code><a *ngFor="let hero of heroes" class="col-1-4" routerLink="/detail/{{hero.id}}" (click)="reloadRoute()">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>
</code></pre>
<p><a href="https://github.com/josuevalrob/tour-of-heroes" rel="nofollow noreferrer"><strong>Github</strong></a></p>
| 1 | 1,275 |
opencv python is faster than c++?
|
<p>I am trying to time the houghcircle in python and c++ to see if c++ gives edge over processing time (intuitively it should!)</p>
<h3>Versions</h3>
<ul>
<li>python: 3.6.4</li>
<li>gcc compiler: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609</li>
<li>cmake : 3.5.1</li>
<li>opencv : 3.4.1 </li>
</ul>
<blockquote>
<p>I actually installed opencv using anaconda. Surprisingly c++ version
also worked</p>
</blockquote>
<p>The image I am using is given here:
<a href="https://i.stack.imgur.com/1sKj7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1sKj7.png" alt="enter image description here"></a></p>
<h1>Python code</h1>
<pre><code>import cv2
import time
import sys
def hough_transform(src,dp,minDist,param1=100,param2=100,minRadius=0,maxRadius=0):
gray = cv2.cvtColor(src,cv2.COLOR_RGB2GRAY)
start_time = time.time()
circles=cv2.HoughCircles(gray,
cv2.HOUGH_GRADIENT,
dp = dp,
minDist = minDist,
param1=param1,
param2=param2,
minRadius=minRadius,
maxRadius=maxRadius)
end_time = time.time()
print("Time taken for hough circle transform is : {}".format(end_time-start_time))
# if circles is not None:
# circles = circles.reshape(circles.shape[1],circles.shape[2])
# else:
# raise ValueError("ERROR!!!!!! circle not detected try tweaking the parameters or the min and max radius")
#
# a = input("enter 1 to visualize")
# if int(a) == 1 :
# for circle in circles:
# center = (circle[0],circle[1])
# radius = circle[2]
# cv2.circle(src, center, radius, (255,0,0), 5)
#
# cv2.namedWindow("Hough circle",cv2.WINDOW_NORMAL)
# cv2.imshow("Hough circle",src)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
#
return
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError("usage: python hough_circle.py <path to image>")
image = cv2.imread(sys.argv[1])
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
hough_transform(image,1.7,100,50,30,690,700)
</code></pre>
<h1>C++ code</h1>
<pre><code>#include <iostream>
#include <opencv2/opencv.hpp>
#include <ctime>
using namespace std;
using namespace cv;
void hough_transform(Mat src, double dp, double minDist, double param1=100, double param2=100, int minRadius=0, int maxRadius=0 )
{
Mat gray;
cvtColor( src, gray, COLOR_RGB2GRAY);
vector<Vec3f> circles;
int start_time = clock();
HoughCircles( gray, circles, HOUGH_GRADIENT, dp, minDist, param1, param2, minRadius, maxRadius);
int end_time = clock();
cout<<"Time taken hough circle transform: "<<(end_time-start_time)/double(CLOCKS_PER_SEC)<<endl;
// cout<<"Enter 1 to visualize the image";
// int vis;
// cin>>vis;
// if (vis == 1)
// {
// for( size_t i = 0; i < circles.size(); i++ )
// {
// Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
// int radius = cvRound(circles[i][2]);
// circle( src, center, radius, Scalar(255,0,0), 5);
// }
// namedWindow( "Hough Circle", WINDOW_NORMAL);
// imshow( "Hough Circle", src);
// waitKey(0);
// destroyAllWindows();
// }
return;
}
int main(int argc, char** argv)
{
if( argc != 2 ){
cout<<"Usage hough_circle <path to image.jpg>";
return -1;
}
Mat image;
image = imread(argv[1]);
cvtColor(image,image,COLOR_BGR2RGB);
hough_transform(image,1.7,100,50,30,690,700);
return 0;
}
</code></pre>
<p>I was hoping for C++ hough transform to ace python but what happened was actually opposite.</p>
<h1>Python result:</h1>
<p><a href="https://i.stack.imgur.com/fuA55.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fuA55.png" alt="enter image description here"></a></p>
<h1>C++ result:</h1>
<p><a href="https://i.stack.imgur.com/mO46Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mO46Y.png" alt="enter image description here"></a></p>
<p>Even though C++ ran the complete program ~2X faster it is very slow in hough transform. Why is it so? This is very counter intuitive. What am I missing here?</p>
| 1 | 1,992 |
Dagger 2: multi-module project, inject dependency but get "lateinit property repository has not been initialize" error at runtime
|
<p>Dagger version is 2.25.2.</p>
<p>I have two Android project modules: <code>core</code> module & <code>app</code> module. </p>
<p>In <code>core</code> module, I defined for dagger <code>CoreComponent</code> , </p>
<p>In <code>app</code> module I have <code>AppComponent</code> for dagger.</p>
<p><code>CoreComponet</code> in core project module:</p>
<pre><code>@Component(modules = [MyModule::class])
@CoreScope
interface CoreComponent {
fun getMyRepository(): MyRepository
}
</code></pre>
<p>In core project module, I have a repository class, it doesn't belong to any dagger module but I use <code>@Inject</code> annotation next to its constructor:</p>
<pre><code>class MyRepository @Inject constructor() {
...
}
</code></pre>
<p>My app component:</p>
<pre><code>@Component(modules = [AppModule::class], dependencies = [CoreComponent::class])
@featureScope
interface AppComponent {
fun inject(activity: MainActivity)
}
</code></pre>
<p>In <code>MainActivity</code>:</p>
<pre><code>class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val coreComponent = DaggerCoreComponent.builder().build()
DaggerAppComponent
.builder()
.coreComponent(coreComponent)
.build()
.inject(this)
}
}
</code></pre>
<p>My project is MVVM architecture, In general:</p>
<ul>
<li><p><code>MainActivity</code> hosts <code>MyFragment</code></p></li>
<li><p><code>MyFragment</code> has a reference to <code>MyViewModel</code> </p></li>
<li><p><code>MyViewModel</code> has dependency <code>MyRepository</code> (as mentioned above <code>MyRepository</code> is in <code>core</code> module)</p></li>
</ul>
<p>Here is <code>MyViewModel</code> :</p>
<pre><code>class MyViewModel : ViewModel() {
// Runtime error: lateinit property repository has not been initialize
@Inject
lateinit var repository: MyRepository
val data = repository.getData()
}
</code></pre>
<p><code>MyViewModel</code> is initialized in MyFragment:</p>
<pre><code>class MyFragment : Fragment() {
lateinit var viewModel: MyViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
...
}
}
</code></pre>
<p>When I run my app, it crashes with runtime error:</p>
<pre><code>kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialize
</code></pre>
<p>The error tells me dagger dependency injection does't work with my setup. So, what do I miss? How to get rid of this error?</p>
<p><strong>==== update =====</strong></p>
<p>I tried :</p>
<pre><code>class MyViewModel @Inject constructor(private val repository: MyRepository): ViewModel() {
val data = repository.getData()
}
</code></pre>
<p>Now when I run the app, I get new error:</p>
<pre><code>Caused by: java.lang.InstantiationException: class foo.bar.MyViewModel has no zero argument constructor
</code></pre>
<p><strong>====== update 2 =====</strong></p>
<p>Now, I created <code>MyViewModelFactory</code>:</p>
<pre><code>class MyViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>,
@JvmSuppressWildcards Provider<ViewModel>>): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
</code></pre>
<p>I updated MyFragment to be :</p>
<pre><code>class MyFragment : Fragment() {
lateinit var viewModel: MyViewModel
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
override fun onAttach(context: Context) {
// inject app component in MyFragment
super.onAttach(context)
(context.applicationContext as MyApplication).appComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// I pass `viewModelFactory` instance here, new error here at runtime, complaining viewModelFactory has not been initialized
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
...
}
}
</code></pre>
<p>Now I run my app, I get new error:</p>
<pre><code>kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
</code></pre>
<p>What's still missing?</p>
| 1 | 1,850 |
IOError: [Errno 13] Permission denied: 'Test.xlsx'
|
<p>the goal of my program is to read the sheet SNR_COPY1 from the Test.xlsx file, using the data to do some computations and then write those to a new sheet within Test.xlsx... Now yesterday my code worked perfectly, but then when I reran it, I got the above mentioned error.. Both the python script and the xlsx file are placed within Documents (Not sure how much it matters, but I'm working on Windows). My code:</p>
<pre><code> import numpy as np
from numpy import pi, r_
import matplotlib.pyplot as plt
from scipy import optimize
from scipy.optimize import curve_fit
import pandas as pd
from pandas import DataFrame
import copy
#version in which all data will be read from the excelfile. The resulting fitparameters will be written into the excisting excelfile.
def snr_fitting_excel(number_of_altitude_points, row_begin_position_of_data, number_of_wavelengths):
# (0,0) in python = (2,1) in excel
n_alt = number_of_altitude_points
n_lambda = number_of_wavelengths
begin = row_begin_position_of_data
end = begin + n_alt
xlsx = pd.ExcelFile('Test.xlsx')
df = pd.read_excel(xlsx, 'SNR-COPY1')
xlsx_copy = copy.deepcopy(xlsx)
#print the beginning point of your data. This ensures that you are working at the correct position in the excel file
print(df.iat[11,2])
d = (n_alt, n_lambda)
#each row of height will represent the data for a given alltitude (height[0] = 5km data,...)
height = np.zeros(d, dtype=int)
# print(height)
for j in range(begin, end):
for i in range(2,10):
height[j-begin][i-2] = (np.around(df.iat[j,i], decimals =0))
height = np.array(height)
#array with the different wavelengths at which the data was taken
wavelengths = np.array([400, 450, 500, 550, 600, 650, 700, 800])
parameter_values = []
#fit the points with the desired function from above
for i in range(0, len(height)):
popt, pcov = curve_fit(fitfunc_polynome_OP_BL, wavelengths, height[i])
fig = plt.figure()
plt.plot(wavelengths, height[i], 'o')
plt.plot(wavelengths, fitfunc_polynome_OP_BL(wavelengths, *popt), 'r-', label ='fit: a=%5.3f, b=%5.3f, c=%5.3f, d=%5.3f, e=%5.3f, g=%5.3f, h=%5.3f, i=%5.3f' % tuple(popt))
plt.xlabel("Wavelength (nm)")
plt.ylabel("SNR")
plt.title("OP-BL-SNR fitting without data cut-off alltitude: " + str((i+1)*5) + "km")
fig.savefig("snr_op_fit_bl" + str((i+1)*5) +".pdf")
parameter_values.append(popt)
print(str((i+1)*5))
print(popt)
parameter_values_to_export = {'a': [parameter_values[0][0], parameter_values[1][0], parameter_values[2][0], parameter_values[3][0], parameter_values[4][0], parameter_values[5][0], parameter_values[6][0], parameter_values[7][0], parameter_values[8][0], parameter_values[9][0], parameter_values[10][0], parameter_values[11][0], parameter_values[12][0], parameter_values[13][0], parameter_values[14][0], parameter_values[15][0], parameter_values[16][0], parameter_values[17][0]],
'b': [parameter_values[0][1], parameter_values[1][1], parameter_values[2][1], parameter_values[3][1], parameter_values[4][1], parameter_values[5][1], parameter_values[6][1], parameter_values[7][1], parameter_values[8][1], parameter_values[9][1], parameter_values[10][1], parameter_values[11][1], parameter_values[12][1], parameter_values[13][1], parameter_values[14][1], parameter_values[15][1], parameter_values[16][1], parameter_values[17][1]],
'c': [parameter_values[0][2], parameter_values[1][2], parameter_values[2][2], parameter_values[3][2], parameter_values[4][2], parameter_values[5][2], parameter_values[6][2], parameter_values[7][2], parameter_values[8][2], parameter_values[9][2], parameter_values[10][2], parameter_values[11][2], parameter_values[12][2], parameter_values[13][2], parameter_values[14][2], parameter_values[15][2], parameter_values[16][2], parameter_values[17][2]],
'd': [parameter_values[0][3], parameter_values[1][3], parameter_values[2][3], parameter_values[3][3], parameter_values[4][3], parameter_values[5][3], parameter_values[6][3], parameter_values[7][3], parameter_values[8][3], parameter_values[9][3], parameter_values[10][3], parameter_values[11][3], parameter_values[12][3], parameter_values[13][3], parameter_values[14][3], parameter_values[15][3], parameter_values[16][3], parameter_values[17][3]],
'e': [parameter_values[0][4], parameter_values[1][4], parameter_values[2][4], parameter_values[3][4], parameter_values[4][4], parameter_values[5][4], parameter_values[6][4], parameter_values[7][4], parameter_values[8][4], parameter_values[9][4], parameter_values[10][4], parameter_values[11][4], parameter_values[12][4], parameter_values[13][4], parameter_values[14][4], parameter_values[15][4], parameter_values[16][4], parameter_values[17][4]],
'g': [parameter_values[0][5], parameter_values[1][5], parameter_values[2][5], parameter_values[3][5], parameter_values[4][5], parameter_values[5][5], parameter_values[6][5], parameter_values[7][5], parameter_values[8][5], parameter_values[9][5], parameter_values[10][5], parameter_values[11][5], parameter_values[12][5], parameter_values[13][5], parameter_values[14][5], parameter_values[15][5], parameter_values[16][5], parameter_values[17][5]],
'h': [parameter_values[0][6], parameter_values[1][6], parameter_values[2][6], parameter_values[3][6], parameter_values[4][6], parameter_values[5][6], parameter_values[6][6], parameter_values[7][6], parameter_values[8][6], parameter_values[9][6], parameter_values[10][6], parameter_values[11][6], parameter_values[12][6], parameter_values[13][6], parameter_values[14][6], parameter_values[15][6], parameter_values[16][6], parameter_values[17][6]],
'i': [parameter_values[0][7], parameter_values[1][7], parameter_values[2][7], parameter_values[3][7], parameter_values[4][7], parameter_values[5][7], parameter_values[6][7], parameter_values[7][7], parameter_values[8][7], parameter_values[9][7], parameter_values[10][7], parameter_values[11][7], parameter_values[12][7], parameter_values[13][7], parameter_values[14][7], parameter_values[15][7], parameter_values[16][7], parameter_values[17][7]],
}
dataframe = DataFrame(parameter_values_to_export, columns= ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i'])
append_df_to_excel('Test.xlsx', dataframe, 'SNR OP BL Parameters')
print(dataframe)
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
truncate_sheet=False,
**to_excel_kwargs):
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
try:
# try to open an existing workbook
writer.book = load_workbook(filename)
# get the last row in the existing Excel sheet
# if it was not specified explicitly
if startrow is None and sheet_name in writer.book.sheetnames:
startrow = writer.book[sheet_name].max_row
# truncate sheet
if truncate_sheet and sheet_name in writer.book.sheetnames:
# index of [sheet_name] sheet
idx = writer.book.sheetnames.index(sheet_name)
# remove [sheet_name]
writer.book.remove(writer.book.worksheets[idx])
# create an empty sheet [sheet_name] using old index
writer.book.create_sheet(sheet_name, idx)
# copy existing sheets
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
except IOError:
# file does not exist yet, we will create it
pass
if startrow is None:
startrow = 0
# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)
# save the workbook
writer.save()
def fitfunc_polynome_OP_BL(x ,a, b, c, d, e, g, h, i):
return a*(np.power(x,7)) + b*(np.power(x,6))+ c*(np.power(x,5)) + d*(np.power(x,4)) + e*(np.power(x,3)) + g*(np.power(x,2)) + h*x +i
if __name__ == '__main__':
print("\nFitting SNR_UV---------------------------------------------\n")
snr_fitting_excel(18,11,8)
</code></pre>
<p>Any tips/remarks/solutions to this error?</p>
| 1 | 3,422 |
Need help in adding a new XML node
|
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mappings>
<mapping>
<aID iskey="true">ABC</aID>
<bID iskey="true">DEF</bID>
<SubAccount>PS</SubAccount>
<Account>PS</Account>
</mapping>
<mapping>
<aID isKey="true">GHI</aID>
<bID isKey="true">PFP</bID>
<SubAccount>MS</SubAccount>
<!-- I want to add a new node here, how can I do this -->
</mapping>
<mapping>
<aID isKey="true">MNO</aID>
<bID isKey="true">BBG</bID>
<SubAccount>MAX</SubAccount>
</mapping>
</mappings>
</code></pre>
<p>I want to add a new node as mentioned in the above XML. I tried a lot but I could not succeed.</p>
<pre><code>XmlDocument xDoc = new XmlDocument();
xDoc.Load(filename);
foreach (XmlNode node in xmlDoc.SelectNodes("/mappings/mapping"))
{
if (boothIDNode.InnerXml == BoothID)
{
chkBoothIDExists = true;
if (clientIDNode.InnerText == ClientID)
{
chkClientIDExists = true;
for (int j = 2; j < nodelist.Count; j++)
{
columnNode = nodelist[j];
if (columnNode.Name == column.ToString())
{
XmlNode elm = xDoc.CreateNode(XmlNodeType.Element,"Account",null);
elm.InnerText = value.ToString();
node.AppendChild(elm); // Error comes here
}
}
}
}
}
xmlDoc.Save(filename);
</code></pre>
<p>The question is solved. The problem occured due to my silly mistake. Basically there are two xml documnets and I'm creating a new node of other xml documnet due to which the error cames.
THanks all,
XmlDocument xDoc = new XmlDocument();
XmlDocument xmlDoc = new XmlDocument();</p>
<p>ERROR: The node to be inserted is from a different document context</p>
| 1 | 1,049 |
WCF and SSL Mutual Authentication 403 - Forbidden: Access is denied
|
<p>I have created a wcf data service and expose it over HTTP, with SSL required.
I am trying to have a setup where both the service and the clients are authenticated through certificates (mutual authentication).
I am using developer certificates.
so, I added the server's certificate to the client's trusted people store.</p>
<p>but I'm still getting an exception : "403 - Forbidden: Access is denied."</p>
<p>1- Here is my server config :</p>
<pre><code> <system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingConfig">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
</behaviors>
<services>
<service behaviorConfiguration="" name="PricingDataService">
<endpoint address="https://MyServiceSecure/MyServiceSecure/MyServiceSecure.svc"
binding="webHttpBinding" bindingConfiguration="webHttpBindingConfig"
name="webHttpEndpoint" contract="System.Data.Services.IRequestHandler" />
</service>
</services>
</code></pre>
<blockquote>
<p>How do I make the server to recognise the client's certificate ? (it should be a developer certificate as well).</p>
</blockquote>
<p>2- Here is my client config :</p>
<pre><code> <system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingConfig">
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="clientCredentialBehavior">
<clientCredentials>
<clientCertificate storeName="TrustedPeople" storeLocation="LocalMachine"
x509FindType="FindBySubjectName" findValue="tempClientcert" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://MyServiceSecure/MyServiceSecure/MyServiceSecure.svc"
binding="webHttpBinding" bindingConfiguration="webHttpBindingConfig"
contract="System.Data.Services.IRequestHandler" name="" kind=""
endpointConfiguration="" behaviorConfiguration="clientCredentialBehavior">
<identity>
<dns value="MyServiceSecure"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
</code></pre>
<p>3- Here's the code I use to call the wcf code :</p>
<pre><code>> MyServiceContext service = new MyServiceContext (
new Uri("https://MyServiceSecure/MyServiceSecure/MyServiceSecure.svc"));
service.SendingRequest += this.OnSendingRequest_AddCertificate;
//
private void OnSendingRequest_AddCertificate(object sender, SendingRequestEventArgs args)
{
if (null != ClientCertificate)
(args.Request as HttpWebRequest).ClientCertificates.Add(X509Certificate.CreateFromCertFile(@"C:\Localhost.cer"););
}
</code></pre>
<blockquote>
<p>do I create a certificate on the server and then install it on the client ? </p>
</blockquote>
| 1 | 1,527 |
Passing a dictionary key value in payload for a python request API
|
<p>I am trying to create a script for an API request for a vmware application. I need to pass a variable from a dictionary in payload . </p>
<p>Here is the code which was able to develop from postman and output is taken as "python requests" :- </p>
<pre><code>import requests
url = "url@domain/api-path"
payload = "{\r\n \"name\" : \"VC Adapter Instance\",\r\n \"description\" : \"A vCenter Adapter Instance\",\r\n \"collectorId\" : \"1\",\r\n \"adapterKindKey\" : \"VMWARE\",\r\n \"resourceIdentifiers\" : [ {\r\n \"name\" : \"AUTODISCOVERY\",\r\n \"value\" : \"true\"\r\n }, {\r\n \"name\" : \"PROCESSCHANGEEVENTS\",\r\n \"value\" : \"true\"\r\n }, {\r\n \"name\" : \"VCURL\",\r\n \"value\" : \"vcenter_name\" \r\n } ],\r\n \"credential\" : {\r\n \"id\" : null,\r\n \"name\" : \"Added Credential\", \r\n \"adapterKindKey\" : \"VMWARE\",\r\n \"credentialKindKey\" : \"PRINCIPALCREDENTIAL\",\r\n \"fields\" : [ {\r\n \"name\" : \"USER\",\r\n \"value\" : \"administrator@vsphere.local\" \r\n }, {\r\n \"name\" : \"PASSWORD\",\r\n \"value\" : \"Hidden-Password \" \r\n } ],\r\n \"others\" : [ ],\r\n \"otherAttributes\" : { }\r\n },\r\n \"monitoringInterval\" : 1,\r\n \"others\" : [ ],\r\n \"otherAttributes\" : { }\r\n}\r\n"
headers = {
'Accept': 'application/json',
'Authorization': 'Hidden Token',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
</code></pre>
<p><a href="https://i.stack.imgur.com/LGJKc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGJKc.png" alt="enter image description here"></a></p>
<p>However I need I want to pass the highlighted vcenter_name as a dictionary value something like this:- </p>
<pre><code>import requests
url = "url@domain/api-path"
Inputs = {‘vcenterkey’ : ‘vcenter_name’}
payload = "{\r\n \"name\" : \"VC Adapter Instance\",\r\n \"description\" : \"A vCenter Adapter Instance\",\r\n \"collectorId\" : \"1\",\r\n \"adapterKindKey\" : \"VMWARE\",\r\n \"resourceIdentifiers\" : [ {\r\n \"name\" : \"AUTODISCOVERY\",\r\n \"value\" : \"true\"\r\n }, {\r\n \"name\" : \"PROCESSCHANGEEVENTS\",\r\n \"value\" : \"true\"\r\n }, {\r\n \"name\" : \"VCURL\",\r\n \"value\" : \"inputs[‘vcenterkey’] \" \r\n } ],\r\n \"credential\" : {\r\n \"id\" : null,\r\n \"name\" : \"Added Credential\", \r\n \"adapterKindKey\" : \"VMWARE\",\r\n \"credentialKindKey\" : \"PRINCIPALCREDENTIAL\",\r\n \"fields\" : [ {\r\n \"name\" : \"USER\",\r\n \"value\" : \"administrator@vsphere.local\" \r\n }, {\r\n \"name\" : \"PASSWORD\",\r\n \"value\" : \"Hidden-Password \" \r\n } ],\r\n \"others\" : [ ],\r\n \"otherAttributes\" : { }\r\n },\r\n \"monitoringInterval\" : 1,\r\n \"others\" : [ ],\r\n \"otherAttributes\" : { }\r\n}\r\n"
headers = {
'Accept': 'application/json',
'Authorization': 'Hidden Token',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8')
</code></pre>
<p>)</p>
<p><a href="https://i.stack.imgur.com/H5oiJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H5oiJ.png" alt="enter image description here"></a></p>
<p>Attaching screen shots for reference. </p>
<p>After adding inputs[‘vcenterkey’] in the payload , instead of the value in vcenter_name i am getting the exact `inputs[‘vcenterkey’] displayed in the payload which causes the API to fail in the script. </p>
| 1 | 1,494 |
AHK: Assign hotkey only for one specific active window and not for others
|
<p>I have just done a piece of code that does the following thing. When I make a selection by mouse in Firefox or EndNote, the script sents a Ctrl+c and checks the clipboard for a regex match. If there is a match, it changes the clipboard contents and shows a tooltip. It works fine for these two programs. Adobe Acrobat sometimes shows an error when a Ctrl+c is sent (even if a user presses a ctrl-c Acrobat sometimes shows famous "There was an error while copying to the Clipboard. An internal error occurred). So it decided to assign an F9 hotkey, but it works for all programs and not just for Acrobat. How do I assign an hotkey for only one window – Acrobat? Here's my code. I know it's lame – I am a newbie to programming in general, and in AHK in particular.</p>
<pre><code>#If WinActive("ahk_exe firefox.exe") || WinActive("ahk_exe EndNote.exe") || WinActive("ahk_exe Acrobat.exe")
if WinActive("ahk_exe Acrobat.exe")
F9::
{
Clipboard:=""
send,^c
ClipWait, 1
ToolTip % Clipboard := RegExReplace(Clipboard, "\r\n", " ")
SetTimer, ToolTipOff, -1000
}
return
~LButton::
now := A_TickCount
while GetKeyState("LButton", "P")
continue
if (A_TickCount-now > 500 )
{
Send ^c
if WinActive("ahk_exe firefox.exe")
{
If RegExMatch(Clipboard, "[0-9]\.\s[A-Za-z,]*\s[A-Za-z]*")
{
regex := "[0-9]\.\s*|\s?\([^)]*\)|\."
replace := ""
}
else If RegExMatch(Clipboard,"[0-9]{2}[-\/][0-9]{2}[-\/][0-9]{4}")
{
Clipboard := RegExReplace(Clipboard, "^0", "")
regex := "\/"
replace := "."
}
else return
}
else if WinActive("ahk_exe EndNote.exe")
{
If RegExMatch(Clipboard, "[a-z]+\,\s[A-Z0-9‘“]")
{
regex := "\??!?\:|\?|!"
replace := "."
}
else return
}
ToolTip % Clipboard := RegExReplace(Clipboard, regex, replace)
SetTimer, ToolTipOff, -1000
}
return
#If
ToolTipOff:
ToolTip
return
</code></pre>
| 1 | 1,173 |
Add my own bundle sources to pax-exam when building with pax-maven-plugin
|
<p>I'm trying to build my OSGI bundle with <a href="http://www.ops4j.org/projects/pax/construct/maven-pax-plugin/" rel="nofollow noreferrer">pax-maven-build</a> and in the same time test it with <a href="http://team.ops4j.org/wiki/display/paxexam/Pax+Exam" rel="nofollow noreferrer">pax-exam</a>. It have some bundle in provision than I can test with the following pax-exam test configuration:</p>
<pre><code>@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(AllConfinedStagedReactorFactory.class)
public class OSGILoaderTest {
@Inject
protected BundleContext bundleContext;
@Configuration
public Option[] config() throws MalformedURLException {
String projectRoot = // a path to my project
return options(
junitBundles(),
equinox(),
bundle(projectRoot + "libs/org.eclipse.core.variables_3.2.500.v20110511.jar"),
bundle(projectRoot + "libs/org.eclipse.core.contenttype_3.4.100.v20110423-0524.jar"),
bundle(projectRoot + "libs/org.eclipse.core.expressions_3.4.300.v20110228.jar"),
// etc...
);
}
@Test
public void getBundleContext() throws RodinDBException {
IRodinDB rodinDB = RodinCore.getRodinDB();
assertNotNull(rodinDB);
}
}
</code></pre>
<p>Here, I can see I can access to the IRodinDB instance from a jar I have provisonned.</p>
<p>Now I have code my own bundle, which is going to use all the jar provisionned. But I cannot even test my own code, for instance:</p>
<pre><code>@Test
public void checkAccessToRodinDbTest() {
VTGService service = null;
assertTrue(true);
}
</code></pre>
<p>give an error <strong>at compilation time</strong>:</p>
<blockquote>
<p>[ERROR] Failed to execute goal org.ops4j:maven-pax-plugin:1.5:testCompile (default-testCompile) : Compilation failure</p>
<p>[ERROR] cannot find symbol</p>
<p>[ERROR] symbol : class VTGService</p>
</blockquote>
<p>It seems test compilation cannot see 'src/main/java', contrarly as expected by the default behavior of maven-compiler-plugin. But in my case, you can see than maven does not use the compiler plugin but instead maven-pax-plugin.</p>
<p>The question is: how can i test my own bundle with pax-exam ?</p>
<p><strong>update1</strong></p>
<p>It seems that this is a problem with recent version of maven-pax-plugin, as <a href="http://www.ops4j.org/projects/pax/construct/maven-pax-plugin/usage.html" rel="nofollow noreferrer">the basic example available in ops4j pax maven plugin</a> (in section <em>Using the Pax Plugin inside a POM</em>) seems to suffer of the same problem.</p>
<p><strong>update2</strong></p>
<p>As requested by Dmytro, this is the pom.xml of my bundle:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<relativePath>../poms/compiled/</relativePath>
<groupId>fr.xlim.ssd.vtg.build</groupId>
<artifactId>compiled-bundle-settings</artifactId>
<version>0.1-SNAPSHOT</version>
</parent>
<properties>
<bundle.symbolicName>fr.xlim.ssd.vtg.bundle</bundle.symbolicName>
<bundle.namespace>fr.xlim.ssd.vtg.bundle</bundle.namespace>
</properties>
<modelVersion>4.0.0</modelVersion>
<groupId>fr.xlim.ssd.vtg</groupId>
<artifactId>fr.xlim.ssd.vtg.bundle</artifactId>
<version>0.1-SNAPSHOT</version>
<name>${bundle.symbolicName}</name>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<type>pom</type>
<groupId>${project.parent.groupId}</groupId>
<artifactId>provision</artifactId>
<optional>true</optional>
</dependency>
<!-- not needed as equinox bundle are available in provision -->
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi_R4_core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>osgi_R4_compendium</artifactId>
<optional>true</optional>
</dependency-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam-junit4</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam-inject</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.url</groupId>
<artifactId>pax-url-mvn</artifactId>
<version>1.3.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam-container-native</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam-link-mvn</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
</code></pre>
<hr />
<p>I am not sure it is the most elegant solution, but I created a new maven project when I can import my own bundle like in the source code of my question.</p>
<p>Is there an elegant way to add my own java sources directly as new bundle for test in the same Maven project ? It could be not possible (as the bundle assembly operation is done <strong>after</strong> the compilation and tests)...</p>
| 1 | 4,235 |
net.sf.json.JSONException
|
<p>I converted a normal JavaScript <code>array</code> (which is in one JSP page), did a <code>JSON.stringify()</code> to that array and passed it across to another JSP as a parameter. In the other JSP, I'm reading it using <code>request.getParameter()</code>.</p>
<p>Now, while converting the string to a <code>JSONArray</code>, I'm getting an exception like this-</p>
<pre><code>net.sf.json.JSONException: Missing value. at character 2 of [[\"111\", \"1.1.1.1\", \"111\", \"111\", \"111\"]]
at net.sf.json.util.JSONTokener.syntaxError(JSONTokener.java:505)
at net.sf.json.util.JSONTokener.nextValue(JSONTokener.java:377)
at net.sf.json.JSONArray._fromJSONTokener(JSONArray.java:1132)
at net.sf.json.JSONArray.fromObject(JSONArray.java:125)
at net.sf.json.util.JSONTokener.nextValue(JSONTokener.java:350)
at net.sf.json.JSONArray._fromJSONTokener(JSONArray.java:1132)
at net.sf.json.JSONArray._fromString(JSONArray.java:1198)
at net.sf.json.JSONArray.fromObject(JSONArray.java:127)
at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:137)
at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:103)
at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)
at org.apache.jsp.pages.Handler_jsp._jspService(Handler_jsp.java:146)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:274)
at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:320)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1813)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
</code></pre>
<p>This is how my String from request.getParameter() looks like-</p>
<pre><code>[[\"111\", \"1.1.1.1\", \"111\", \"111\", \"111\"]]
</code></pre>
<p>What does <strong><code>net.sf.json.JSONException: Missing value. at character 2 of [[\"111\", \"1.1.1.1\", \"111\", \"111\", \"111\"]]</code></strong> mean? And how do I deal with it?</p>
| 1 | 2,388 |
I keep getting this error on Slim 4 after installing new version 4.12
|
<p>I keep getting this error <code>Slim Application Error</code> after installing the new Slim 4 framework.</p>
<p>I tried switching back to old version of slim but I keep getting the same thing.</p>
<pre><code><?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
/**
* Instantiate App
*
* In order for the factory to work you need to ensure you have installed
* a supported PSR-7 implementation of your choice e.g.: Slim PSR-7 and a supported
* ServerRequest creator (included with Slim PSR-7)
*/
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
/*
* Add Error Handling Middleware
*
* @param bool $displayErrorDetails -> Should be set to false in production
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log
* which can be replaced by a callable of your choice.
* Note: This middleware should be added last. It will not handle any exceptions/errors
* for middleware added after it.
*/
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name");
return $response;
});
// Run app
$app->run();
</code></pre>
<p>Output:</p>
<pre><code>Slim Application Error
The application could not run because of the following error:
Details
Type: Slim\Exception\HttpNotFoundException
Code: 404
Message: Not found.
File: /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php
Line: 91
</code></pre>
<p>Trace:</p>
<pre><code>#0 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(57): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Psr7\Request))
#1 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(Slim\Routing\RouteRunner))
#2 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(89): class@anonymous->handle(Object(Slim\Psr7\Request))
#3 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(132): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(class@anonymous))
#4 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/MiddlewareDispatcher.php(73): class@anonymous->handle(Object(Slim\Psr7\Request))
#5 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/App.php(206): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request))
#6 /opt/lampp/htdocs/MyocappAPI/vendor/slim/slim/Slim/App.php(190): Slim\App->handle(Object(Slim\Psr7\Request))
#7 /opt/lampp/htdocs/MyocappAPI/public/index.php(41): Slim\App->run()
#8 {main}
</code></pre>
| 1 | 1,099 |
Issues getting CasperJS to upload image to file field - tried CasperJS fill() and PhantomJS uploadFile()
|
<p>I'm trying to use CasperJS to upload images to a web-form.</p>
<p>My form looks something like this:</p>
<pre><code><form action="" method="POST" enctype="multipart/form-data" class="form-vertical">
...
<legend>Campaign Banner</legend>
<div class="control-group image-field ">
<label class="control-label">Now Large</label>
<div class="controls">
<div class="file-field"><input id="id_now_large_image" name="now_large_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Medium</label>
<div class="controls">
<div class="file-field"><input id="id_now_medium_image" name="now_medium_image" type="file"></div>
<div class="image-preview"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group image-field ">
<label class="control-label">Now Small</label>
<div class="controls">
<div class="file-field"><input id="id_thumbnail_image" name="thumbnail_image" type="file"></div>
<div class="image-preview now-small"></div>
<div class="clear"></div>
<span class="help-inline"></span>
</div>
</div>
</code></pre>
<p>The submit button looks like this:</p>
<pre><code><div class="form-actions">
<button type="submit" class="btn btn-small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Save changes</span></button>
</div>
</code></pre>
<p>I've put a Gist of the full HTML here: <a href="https://gist.github.com/victorhooi/8277035" rel="nofollow noreferrer">https://gist.github.com/victorhooi/8277035</a></p>
<p>First, I've tried using CasperJS's <a href="http://docs.casperjs.org/en/latest/modules/casper.html#fillxpath" rel="nofollow noreferrer">fill</a> method:</p>
<pre><code> this.fill('form.form-vertical', {
'now_large_image': '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg',
}, false);
this.click(x('//*[@id="content-wrapper"]//button/span'));
</code></pre>
<p>I also did a this.capture(), and I saw that the file field had been filled in:</p>
<p><img src="https://i.stack.imgur.com/o1vF7.png" alt="enter image description here"></p>
<p>I'm not using the fill method's inbuilt submit, but I'm clicking on the submit button myself:</p>
<p>this.click(x('//*[@id="content-wrapper"]//button/span'));</p>
<p>I then do another capture, and I can see that the form has been submitted:</p>
<p><img src="https://i.stack.imgur.com/X9FDl.png" alt="enter image description here"></p>
<p>However, the image doesn't seem to have been uploaded at all.</p>
<p>I've also tried using PhantomJS's <a href="http://phantomjs.org/api/webpage/method/upload-file.html" rel="nofollow noreferrer">uploadFile()</a> method:</p>
<pre><code>this.page.uploadFile('input[name=now_large_image]', '/Users/victor/Dropbox/CMT Test Resources/Test Banners/Default Banners/now_large.jpg');
</code></pre>
<p>and then clicking on the submit button as well.</p>
<p>Same issue - the form field gets filled in - however, the image itself doesn't seem to get submitted.</p>
<p>Any ideas on how I can get the images to upload correctly here?</p>
| 1 | 1,827 |
Verilog ,cannot be assigned more than one value
|
<p>I am New to Verilog, I am trying to make a CPLD power up protection logic, it actually use a bunch of Timer to validate the state machine. I have a CPLD with 1Mhz OSC, and I am trying to make a 15s timer, I figure the code, but it have compile error, says <strong>"cannot be assigned more than one value".</strong> I knew this mean the signal net has been control by two different signal, but it has a error line shows</p>
<p>Error (12014): Net "Fifty_m_second_Devide_Clock_input", which fans out to "Timer[0]", cannot be assigned more than one value
Error (12015): Net is fed by "clk_div:d|clk_out"
Error (12015): Net is fed by "Fifty_m_second_Devide_Clock_input"</p>
<p><strong><code>why "Fifty_m_second_Devide_Clock_input" is connected to itself??</code></strong></p>
<pre><code> module PowerUpProtection(
//---------------------------------------------------------------------------
// Inputs
//---------------------------------------------------------------------------
input wire Fifty_m_second_Devide_Clock_input,
input wire Clock,
input wire Reset,
input wire Input1_Check_precharge_status,
input wire Input2_MainPowerSwitch_relay_status_Check,
input wire Input3_powerUp_validation,
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Outputs
//---------------------------------------------------------------------------
output reg Output1_Relay_Swtich_For_Main_PowerSource,
output reg Output2_Switch_On_and_Charge_CAP,
output reg Output3_Switch_On_and_power_SoM,
output reg Output4_Press_and_hold_the_powerSource,
output reg Output5_Switch_on_relay_when_CPLD_powerup
//---------------------------------------------------------------------------
);
// this is a Module Instantiation, connect the inputs and output from different module within CPLD.
clk_div d(
.Clock (Clock),
.reset(Reset),
.clk_out(Fifty_m_second_Devide_Clock_input)
);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// State Encoding
//---------------------------------------------------------------------------
localparam STATE_0_Initial = 4'd0,
STATE_1_Press_and_hold = 4'd1,
STATE_2_Power_up = 4'd2,
STATE_3_Check_Switches = 4'd3,
STATE_4_SwtichSafe_StartPreCharging = 4'd4,
STATE_5_ERROR = 4'd5,
STATE_6_CAP_is_Charging = 4'd6,
STATE_7_Charging_End_SwitchOn_MainPower = 4'd7,
STATE_8_PowerSupply_Ready = 4'd8,
ERROR_9_TIME_OUT = 4'd9,
STATE_10_Precharge_Switch_is_broken = 4'd10,
STATE_11_Main_power_switch_is_broken = 4'd11,
STATE_12_Both_switches_are_broken = 4'd12,
STATE_13_PlaceHolder = 4'd13,
STATE_14_PlaceHolder = 4'd14,
STATE_15_PlaceHolder = 4'd15;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// State reg Declarations
//---------------------------------------------------------------------------
reg [3:0] CurrentState = 4'd0;
reg [3:0] NextState = 4'd0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Timer reg Declarations
//---------------------------------------------------------------------------
reg [8:0] Timer = 0;
reg enable_the_counter = 0; // the boolean to enbale the counter.
reg clear_the_counter = 0;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Outputs
//---------------------------------------------------------------------------
always@(*) begin
// clear for the initial state.
reg Output1_Relay_Swtich_For_Main_PowerSource = 0;
reg Output2_Switch_On_and_Charge_CAP = 0;
reg Output3_Switch_On_and_power_SoM = 0;
reg Output4_Press_and_hold_the_powerSource = 0;
reg Output5_Switch_on_relay_when_CPLD_powerup = 0;
case (CurrentState)
STATE_1_Press_and_hold : begin
Output4_Press_and_hold_the_powerSource = 1;
end
STATE_2_Power_up : begin
Output5_Switch_on_relay_when_CPLD_powerup = 1;
end
STATE_3_Check_Switches : begin
Output2_Switch_On_and_Charge_CAP = 1;
end
STATE_4_SwtichSafe_StartPreCharging : begin
Output2_Switch_On_and_Charge_CAP = 1;
end
STATE_5_ERROR : begin
// to be determined
end
STATE_6_CAP_is_Charging : begin
// wait for the charging to be complete
end
STATE_7_Charging_End_SwitchOn_MainPower : begin
Output1_Relay_Swtich_For_Main_PowerSource =1;
end
STATE_8_PowerSupply_Ready : begin
Output5_Switch_on_relay_when_CPLD_powerup = 0;
Output3_Switch_On_and_power_SoM = 1;
end
endcase
end
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Synchronous State-Transition always@(posedge Clock) block
//---------------------------------------------------------------------------
always@(posedge Clock) begin
if (Reset) CurrentState <= STATE_0_Initial;
else CurrentState <= NextState;
end
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// conditional State-Trasnsition Always@(*) block
//---------------------------------------------------------------------------
always@(*) begin
NextState = CurrentState;
case (CurrentState)
STATE_0_Initial :begin
NextState = STATE_1_Press_and_hold;
end
STATE_1_Press_and_hold : begin
if (Input3_powerUp_validation) NextState = STATE_2_Power_up;
end
STATE_2_Power_up : begin
if (Input3_powerUp_validation) NextState = STATE_3_Check_Switches;
end
STATE_3_Check_Switches : begin
if (Input1_Check_precharge_status == 0 && Input2_MainPowerSwitch_relay_status_Check == 1 )
begin
NextState = STATE_4_SwtichSafe_StartPreCharging;
enable_the_counter = 1; //Start to count the time.
end
else if (Input1_Check_precharge_status == 1 && Input2_MainPowerSwitch_relay_status_Check == 1)
begin
NextState = STATE_10_Precharge_Switch_is_broken;
end
else if (Input1_Check_precharge_status == 0 && Input2_MainPowerSwitch_relay_status_Check == 0)
begin
NextState = STATE_11_Main_power_switch_is_broken;
end
else
begin
NextState = STATE_12_Both_switches_are_broken;
end
end
STATE_4_SwtichSafe_StartPreCharging : begin
if (Input1_Check_precharge_status == 1 && Timer <= 300) //equals to 15 seconds
NextState = STATE_6_CAP_is_Charging;
else if (Timer > 300)
NextState = STATE_5_ERROR; //Time out Error
clear_the_counter = 1;
enable_the_counter = 0;
end
STATE_6_CAP_is_Charging : begin
if (Input1_Check_precharge_status == 0 && Timer <= 300)
begin
NextState = STATE_7_Charging_End_SwitchOn_MainPower;
clear_the_counter = 1; // timer is over, clear the counter.
enable_the_counter =0;
end
else if (Timer > 300)
begin
NextState = STATE_5_ERROR; //Time out Error
clear_the_counter = 1;
enable_the_counter = 0;
end
end
STATE_7_Charging_End_SwitchOn_MainPower : begin
//enable the counter again, and count for 50 m seconds.
enable_the_counter = 1;
if (Input2_MainPowerSwitch_relay_status_Check ==1)
begin
if (Timer <=1)
NextState = STATE_7_Charging_End_SwitchOn_MainPower; // if time is not 50 ms yet, go back to itself current state
else
NextState = STATE_5_ERROR; //Time out Error
clear_the_counter = 1;
enable_the_counter = 0;
end
else if (Input2_MainPowerSwitch_relay_status_Check == 0) // if the switch is ready right away, that is best.
begin
NextState = STATE_8_PowerSupply_Ready;
end
else
NextState = STATE_5_ERROR; //Time out Error
clear_the_counter = 1;
enable_the_counter = 0;
end
//---------------------------------------------------------------------------
// Place-Holder transition.
//---------------------------------------------------------------------------
STATE_13_PlaceHolder : begin
NextState = STATE_5_ERROR;
end
STATE_14_PlaceHolder : begin
NextState = STATE_5_ERROR;
end
STATE_15_PlaceHolder : begin
NextState = STATE_5_ERROR;
end
endcase
end
//---------------------------------------------------------------------------
// 50 m Seconds counter block, make the osc into 20 HZ by implement the counter
//---------------------------------------------------------------------------
always@(posedge Fifty_m_second_Devide_Clock_input or posedge Reset or posedge clear_the_counter ) begin
if (Reset == 1 || clear_the_counter == 1)
begin
Timer = 0;
end
else
begin
if (enable_the_counter)
Timer <= Timer + 1'b1;
end
end
//---------------------------------------------------------------------------
endmodule
//clock devider, the board has a 10 M hz osc,
//so I create this code to count 200000 times
//for each posedge and that equalle to 50 m-second.
// if count until 50 m-second, this clk_out will output one positive edge.
module clk_div(
input Clock,
input reset,
output reg clk_out
);
parameter diver = 99999;
reg [23:0] count;//just for 99999 or warning
always@(posedge Clock or posedge reset)
begin
if(reset)
begin
count <= 0;
clk_out <= 1'b0;
end
else if(count == diver)
begin
clk_out <= ~clk_out;
count <= 0;
end
else
begin
count <= count + 1'b1;
end
end
endmodule
</code></pre>
| 1 | 5,248 |
Select a single node XML object using VBA
|
<p>Hi I'm trying to access the XML response object below</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<gfi_message version="1.0">
<header>
<transactionId>123</transactionId>
<timestamp>2018-02-08T15:59:41+08:00</timestamp>
<processingTime>0.15</processingTime>
</header>
<body>
<response name="action1" function="PRICING" version="1.0">
<option name="data" ref="price169" />
</response>
<data format="NAME_VALUE" name="price169">
<node name="European Call">
<field name="Scenario" value="Trading" />
<field name="Currency" value="USD" status="input" />
<field name="CtrCcy" value="HKD" status="input" />
<field name="Strategy" value="Call" status="input" />
<field name="Model" value="Analytic" />
<field name="Class" value="European" status="input" />
<field name="Direction" value="Buy" status="input" />
<field name="Spot" value="7.81241/7.82871" />
<field name="Cutoff" value="TOK" />
<field name="Market" value="OTC" />
<field name="HorDate" value="15:59 Thu 8 Feb 18" status="input" />
<field name="ValDate" value="12 Feb 18" />
<field name="SpotDate" value="12 Feb 18" />
<field name="Maturity" value="Odd Date" />
<field name="ExDate" value="8 Feb 18" status="input" />
<field name="ExDays" value="0" />
<field name="ExTime" value="14:00 SGT" />
<field name="DelDate" value="12 Feb 18" />
<field name="DelDays" value="0" />
<field name="PremDate" value="Mon 12 Feb 18" />
<field name="PremType" value="Spot" />
<field name="Strike" value="7.81241" />
<field name="CtrStk" value="0.128001474576987" />
<field name="FwdWealth" value="0\-0.002082079933987" status="input" />
</node>
</data>
</body>
</gfi_message>
</code></pre>
<p>Specifically I just need <code><field name="Spot" value="7.81241/7.82871" /></code></p>
<p>Currently I'm trying to parse and attempt to print the statements in a debugger but I'm not getting any response as well</p>
<pre><code>Dim objXML As MSXML2.DOMDocument30
Dim nodesThatMatter As MSXML2.IXMLDOMElement
Set nodesThatMatter = objXML.SelectNodes("//gfi_message/body/data/node")
For Each Node In nodesThatMatter
Debug.Print nodesThatMatter.SelectSingleNode("field").Text
Next
</code></pre>
| 1 | 1,277 |
Transferring 5 megabytes file using wcf
|
<p>I am trying to use wcf for transferring a file larger then 5 mega.(i cant use streeaming for now it demands major changes to running code). </p>
<p>I configured the server and the client to the maximum settings and still i get the exception of maximum length. </p>
<p>Here is my server web.config: </p>
<pre><code><system.serviceModel>
<diagnostics>
<messageLogging logMalformedMessages="true" logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="true" />
</diagnostics>
<services>
<service name="xxx.xxx.Service">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="xxx"
contract="xxx.xxx.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="b2bservice" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<client />
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</code></pre>
<p> </p>
<p>And here is the client app.config:</p>
<pre><code><system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="xxx"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="BService.IBService" name="BasicHttpBinding_IService" />
</client>
</code></pre>
<p></p>
<p>My trace Logging is: </p>
<blockquote>
<p>Maximum request length exceeded.<br>
System.ServiceModel.CommunicationException, System.ServiceModel,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089`</p>
</blockquote>
<p>Any thoughts?</p>
| 1 | 1,444 |
MVC 3 Get result from partial view into model
|
<p>I'm sure this is easy, but maybe I haven't searched well ...</p>
<p>I want to know how to get results from a partial view back to the model and/or controller.</p>
<p>If the user enters a FirstName, Gender (from drop down) and Grade (from drop down), I only find then FirstName and Gender in the model. I want to know how to get the Grade from the drop down in the partial view all the way back into the model, so I can see it in the controller.</p>
<p>Please look for this question in the controller code:</p>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<p>What do I need to do to get the GradeLevel from the partial class to be here: <<<<<</p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
<p>Note: this is not the exact code. There may be small, insignificant typo's.</p>
<p>EDIT: Apparently you can't add a long comment, so I will add here:</p>
<p>Thank you, Tom and Mystere Man. Tom got me thinking as to why it doesn't work. I didn't think through the model binding. With the design I proposed, the HTML gets rendered and the Grade drop down has this id: "Grade". The property on the model I want to bind to is: "GradeLevelID". If I change the helper in the partial view to be @Html.DropDownList("GradeLevelID" ... it works perfectly. </p>
<p>But that is not a good solution. My idea was to abstract the partial view from the main view. Hard coding the name blows that! I did work up a slightly improved solution. In the main view, I change the @Html.Partial statement to pass the model property name to the partial. Like such:</p>
<pre><code>@Html.Partial("GradeDropDown", (SelectList)Model.GradeSelectList, new ViewDataDictionary { { "modelPropertyName", "GradeLevelID" } })
</code></pre>
<p>Then I could change the partial view to say </p>
<pre><code>@model System.Web.Mvc.SelectList
@Html.DropDownList((string)ViewData["modelPropertyName"], Model)
</code></pre>
<p>But that also seems like a goofy way to approach things. Thanks for the help. I'll look at EditorTemplates.</p>
<hr>
<h2>Here is my model:</h2>
<pre><code>public class RegisterModel{
public MemberRegistration MemberRegistration{
get{
if (HttpContext.Current.Session["MemberRegistration"] == null){
return null;
}
return (MemberRegistration)HttpContext.Current.Session["MemberRegistration"];
}
set{
HttpContext.Current.Session["MemberRegistration"] = value;
}
}
public string FirstName{
get{
return MemberRegistration.FirstName;
}
set{
MemberRegistration.FirstName = value;
}
}
public SelectList GenderSelectList{
get{
List<object> tempList = new List<object>();
tempList.Add(new { Value = "", Text = "" });
tempList.Add(new { Value = "M", Text = "Male" });
tempList.Add(new { Value = "F", Text = "Female" });
return new SelectList(tempList, "value", "text", MemberRegistration.Gender);
}
}
[Required(ErrorMessage = "Gender is required")]
public string Gender{
get{
return MemberRegistration.MemberPerson.Gender;
}
set{
MemberRegistration.MemberPerson.Gender = value;
}
}
public SelectList GradeLevelSelectList{
get{
List<object> tempList = new List<object>();
tempList.Add(new { Value = "", Text = "" });
tempList.Add(new { Value = "1", Text = "1st" });
tempList.Add(new { Value = "2", Text = "2nd" });
tempList.Add(new { Value = "3", Text = "3rd" });
tempList.Add(new { Value = "4", Text = "4th" });
return new SelectList(tempList, "value", "text", MemberRegistration.GradeLevel);
}
}
[Required(ErrorMessage = "Grade is required")]
public Int32 GradeLevel{
get{
return MemberRegistration.GradeLevel;
}
set{
MemberRegistration.GradeLevel = value;
}
}
}
</code></pre>
<hr>
<h2>Here is my main view:</h2>
<pre><code>@model RegisterModel
@using (Html.BeginForm())
{
<p class="DataPrompt">
<span class="BasicLabel">First Name:</span>
<br />
@Html.EditorFor(x => x.FirstName)
</p>
<p class="DataPrompt">
<span class="BasicLabel">Gender:</span>
<br />
@Html.DropDownListFor(x => x.Gender, Model.GenderSelectList)
</p>
<p class="DataPrompt">
<span class="BasicLabel">Grade:</span><span class="Required">*</span>
<br />
@Html.Partial("GradeDropDown", (SelectList)Model.GradeLevelSelectList)
</p>
<p class="DataPrompt">
<input type="submit" name="button" value="Next" />
</p>
}
</code></pre>
<hr>
<h2>Here is my partial view (named "GradeDropDown"):</h2>
<pre><code>@model System.Web.Mvc.SelectList
@Html.DropDownList("Grade", Model)
</code></pre>
<hr>
<h2>Here is my controller:</h2>
<pre><code>[HttpPost]
public ActionResult PlayerInfo(RegisterModel model)
{
string FirstName = model.Registration.FirstName;
string Gender = model.Registration.Gender;
>>>>> What do I need to do to get the GradeLevel from the partial class to be here: <<<<<
Int32 GradeLevel = model.Registration.GradeLevel;
return RedirectToAction("Waivers");
}
</code></pre>
| 1 | 2,297 |
iphone EXC_BAD_ACCESS with NSMutableArray
|
<p>Ok so I have a UIViewTable and a UISearchBar with two scope buttons. The idea being that when I press a scope button the datasource for UIViewTable gets changed but I am getting
EXC_BAD_ACCESS error.</p>
<p>I have the following code in my UIViewController SearchViewController.m:</p>
<pre><code>- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange: (NSInteger) selected scope
{
MyAppDelegate *delegate = (MyAppDelegate *) [[UIApplicationsharedApplication] delegate];
if (self.listData != nil) {
[self.listData release];
}
if (selectedScope == 0) {
self.listData = [delegate.data getListOne];
}
else {
self.listData = [delegate.data getListTwo];
}
}
- (void) viewDidLoad {
MyAppDelegate *delegate = (MyAppDelegate*) [[UIApplication sharedApplication] delegate];
self.listData = [delegate.data getListOne];
//some other unrelated code
}
</code></pre>
<p>in my SearchViewController.h I have:</p>
<pre><code>@property (nonatomic,retain) NSMutableArray *listData;
</code></pre>
<p>in my Data.m I have:</p>
<pre><code>-(NSMutableArray *) getListOne {
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:@"test1",
@"test2",
nil];
[list autorelease];
return list;
}
-(NSMutableArray *) getListTwo {
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:@"test3",
@"test4",
nil];
[list autorelease];
return list;
}
</code></pre>
<p>It crashes on:</p>
<pre><code>self.listData = [delegate.data getListTwo];
</code></pre>
<p>I checked that its when I am setting the property that it crashes. My understanding is that when I create the new NSMutableArray in Data.m I assign it autorelease as I should. </p>
<p>When the view loads I assign it to my listData and since I am accessing the property which has retain then the reference count is incremented (so its now 2 pending auto release).</p>
<p>When I press the button to change the data source I check too see if listData exists (which it always will), release it so that the old NSMutableArray counter will be 0 (assuming autorelease has occured). </p>
<p>Then I get a new NSMutableArray and set it to this property... is my understanding correct? I have spent far too long on this simple problem :(</p>
<p>oh also I did create another NSMutableArray that was not connected to the tableView and still get the same problem, also if I don't release it in my if statement the problem does not exist but I will then have a memory leak?? I could always just keep the array and remove/add objects but I want to know why this is not working :)
cheers</p>
| 1 | 1,146 |
Docker and libseccomp
|
<p>I'm running into a problem with docker. I've got here OpenSuse 13.2 with a self-built version of libseccomp library. it's fresh version 2.3.1 from couple of weeks ago. If i'm running any docker container, i get the following error:</p>
<pre><code>hostname:/usr/lib/docker # docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
78445dd45222: Pull complete
Digest: sha256:c5515758d4c5e1e838e9cd307f6c6a0d620b5e07e6f927b07d05f6d12a1ac8d7
Status: Downloaded newer image for hello-world:latest
container_linux.go:247: starting container process caused "conditional filtering requires libseccomp version >= 2.2.1"
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "conditional filtering requires libseccomp version >= 2.2.1".
ERRO[0002] error getting events from daemon: net/http: request canceled
</code></pre>
<p>Of course i can use an option --security-opt seccomp:unconfined when starting a container, but this is not my purpose.</p>
<pre><code># rpm -qa libseccomp
libseccomp-2.3.1-1.x86_64
</code></pre>
<p>docker info:</p>
<pre><code>Containers: 1
Running: 0
Paused: 0
Stopped: 1
Images: 1
Server Version: 1.13.0
Storage Driver: devicemapper
Pool Name: docker-254:2-655361-pool
Pool Blocksize: 65.54 kB
Base Device Size: 10.74 GB
Backing Filesystem: ext4
Data file: /dev/loop0
Metadata file: /dev/loop1
Data Space Used: 307.2 MB
Data Space Total: 107.4 GB
Data Space Available: 20.64 GB
Metadata Space Used: 806.9 kB
Metadata Space Total: 2.147 GB
Metadata Space Available: 2.147 GB
Thin Pool Minimum Free Space: 10.74 GB
Udev Sync Supported: true
Deferred Removal Enabled: false
Deferred Deletion Enabled: false
Deferred Deleted Device Count: 0
Data loop file: /var/lib/docker/devicemapper/devicemapper/data
WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
Library Version: 1.03.01 (2011-10-15)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: oci runc
Default Runtime: runc
Init Binary: docker-init
containerd version: (expected: 03e5862ec0d8d3b3f750e19fca3ee367e13c090e)
runc version: N/A (expected: 2f7393a47307a16f8cee44a37b262e8b81021e3e)
init version: N/A (expected: 949e6facb77383876aeff8a6944dde66b3089574)
Security Options:
apparmor
seccomp
Profile: default
Kernel Version: 3.16.7-53-desktop
Operating System: openSUSE 13.2 (Harlequin) (x86_64)
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 3.868 GiB
Name: hostname
ID: DCOH:JZMG:ZUTM:5MSB:DVAG:SQXS:Z36N:5OXU:GQII:YTMO:RWDA:HYBJ
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
WARNING: No swap limit support
WARNING: No kernel memory limit support
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
</code></pre>
| 1 | 1,090 |
ArrayList error - Cannot find symbol
|
<p>I'm working on a final project for school and having some troubles. I have never done any programming in Java or really anything Object Oriented, so my code's likely not going to be that great.</p>
<p>I'm having some issues with my array list. I am getting an error that says cannot find symbol - class studentInfo. What am I doing incorrectly with my code? This is preventing me from compiling the code. All student info is fake. </p>
<p>Also would anyone have any recommendations on how to clean up or optimize my code?</p>
<pre><code>import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Roster
{
private static ArrayList<studentInfo> studentList = new ArrayList<>();
public static void main(String[] args)
{
add(1, "John", "Smith", "John1989@gmail.com", 20, 88, 79, 59);
add(2, "Suzan", "Erickson", "Erickson_1990@gmailcom", 19, 91, 72, 85);
add(3, "Jack", "Napoli", "The_lawyer99yahoo.com", 19, 85, 84, 87);
add(4, "Erin", "Black", "Erin.black@comcast.net", 22, 91, 98, 82);
print_all();
print_invalid_emails();
print_average_grade(2);
remove(3);
remove(3);
}
public static void add (int studentID, String firstName, String lastName, String email, int age, int grade1, int grade2, int grade3)
{
int[] grades = {grade1, grade2, grade3};
studentInfo newStudent = new studentInfo (studentID, firstName, lastName, email, age, grades);
studentList.add(newStudent);
}
public static void remove(int studentID)
{
for (studentInfo i: studentList) {
if (i.getStudentID == studentID) {
studentList.remove(i);
System.out.println("Student Removed");
}
else {
System.out.println("A student with this ID(studentID) was not found.");
return;
}
}
}
public static void print_all (){
for (studentInfo i: studentList) {
studentList.get(i).print();
}
}
public static void print_average_grade(int studentID) {
studentList.get(studentID).getAverageGrade();
}
public static void print_invalid_emails() {
String RFC5322 = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
Pattern pattern = Pattern.compile(RFC5322);
for (studentInfo i: studentList) {
String email = i.getEmail;
Matcher matcher = pattern.matcher(email);
System.out.println(email +":\t"+ matcher.matches());
}
}
}
</code></pre>
<p>My second class</p>
<pre><code>public class Student
{
private int studentID;
private String firstName;
private String lastName;
private String email;
private int age;
private int[] grades;
public Student (int studentID, String firstName, String lastName, String email, int age, int grades[])
{
setStudentID(studentID);
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
setAge(age);
setGrades(grades);
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setAge(int age) {
this.age = age;
}
public void setGrades(int[] grades) {
this.grades = grades;
}
public int getStudentID() {
return studentID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return firstName + lastName;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
public int[] getGrades() {
return grades;
}
public int getAverageGrade() {
int averageGrade = 0;
for (int grade : grades) {
averageGrade += grade;
}
return averageGrade;
}
public void print() {
System.out.println(
"Student Name:\t" + getFullName() + "\n " +
"Student ID:\t" + getStudentID() + "\n" +
"Email:\t" + getEmail() + "\n" +
"Age:\t" + getAge() + "\n" +
"Average Grade:\t" + getAverageGrade()
);
}
}
</code></pre>
| 1 | 1,863 |
Spring Data Repository StackOverflow
|
<p>Found some strange behavoir when working with Spring Data Repositories.</p>
<p>I wrote these classes and interfaces:</p>
<pre class="lang-java prettyprint-override"><code>@Transactional(readOnly = true)
public interface UserRepository extends Repository<User, Integer> {
@Transactional
@Modifying
@Query("DELETE FROM User u WHERE u.id=:id")
int delete(@Param("id") int id);
@Transactional
User save(User user);
User findOne(Integer id);
List<User> findAll();
}
public interface AbstractRepository<T> {
T save(T user);
// false if not found
boolean delete(int id);
// null if not found
T get(int id);
List<T> getAll();
}
@Repository
public class UserRepositoryImpl implements AbstractRepository<User> {
@Autowired
private JpaUserRepository repository;
@Override
public User save(User user) {
return repository.save(user);
}
@Override
public boolean delete(int id) {
return repository.delete(id) != 0;
}
@Override
public User get(int id) {
return repository.findOne(id);
}
@Override
public List<User> getAll() {
return repository.findAll();
}
}
</code></pre>
<p>When I try to test UserRepositoryImpl, java.lang.StackOverflowError is thrown</p>
<pre><code>Caused by: java.lang.StackOverflowError
at org.springframework.data.repository.util.ClassUtils.unwrapReflectionException(ClassUtils.java:166)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:505)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:478)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:115)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy55.save(Unknown Source)
at ru.emitrohin.votingsystem.repository.UserRepositoryImpl.save(RestaurantRepositoryImpl.java:24)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
</code></pre>
<p>I see that there is some problem with save() method. Also stackoverflow is thrown on delete() method.</p>
<p>I've already found the solution. My problem disappears when I change name of interface that extends Repository interface to (for example) JpaUserRepository.</p>
<p>So, the question is "What is going on". Why stackoverflow is thrown when interface name that implements spring data repository matches pattern <em>Classname</em>Repository?</p>
<p>my pom.xml </p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>xxx</name>
<url>xxx</url>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<tomcat.version>8.0.33</tomcat.version>
<spring.version>4.3.4.RELEASE</spring.version>
<spring-security.version>4.2.0.RELEASE</spring-security.version>
<spring-data-jpa.version>1.10.4.RELEASE</spring-data-jpa.version>
<!-- Logging -->
<logback.version>1.1.7</logback.version>
<slf4j.version>1.7.21</slf4j.version>
<!--DB-->
<postgresql.version>9.4.1211</postgresql.version>
<!--Tests-->
<junit.version>4.12</junit.version>
<!-- Hibernate -->
<hibernate.version>5.2.4.Final</hibernate.version>
<hibernate-validator.version>5.3.2.Final</hibernate-validator.version>
<!--Tools-->
<ehcache.version>2.10.3</ehcache.version>
</properties>
<build>
<finalName>xxx</finalName>
<defaultGoal>package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
<!-- http://stackoverflow.com/questions/4305935/is-it-possible-to-supply-tomcat6s-context-xml-file-via-the-maven-cargo-plugin#4417945 -->
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.5.0</version>
<configuration>
<container>
<containerId>tomcat8x</containerId>
<systemProperties>
<file.encoding>UTF-8</file.encoding>
<spring.profiles.active>tomcat,datajpa</spring.profiles.active>
</systemProperties>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
</container>
<configuration>
<configfiles>
<configfile>
<file>src/main/resources/tomcat/context.xml</file>
<todir>conf/Catalina/localhost/</todir>
<tofile>context.xml.default</tofile>
</configfile>
</configfiles>
</configuration>
<deployables>
<deployable>
<groupId>com.xxx</groupId>
<artifactId>xxx</artifactId>
<type>war</type>
<properties>
<context>${project.build.finalName}</context>
</properties>
</deployable>
</deployables>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring security-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!--hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!--Web-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.2.21</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>hsqldb</id>
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.4</version>
</dependency>
</dependencies>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</code></pre>
<p></p>
| 1 | 9,255 |
URL Scheme not working in iOS9
|
<p>I am working on an app in which a user confirmation mail sent to user email.
I am able to receive the mail in this format"<a href="http://www.sample.com//Register.aspx?xxx(with" rel="nofollow">http://www.sample.com//Register.aspx?xxx(with</a> parameters)".
Now on click of this mail i have to launch the register page in iOS9.</p>
<p><strong>Note</strong>: if i type Register.aspx:// in safari app is opening but not from email URL.</p>
<p>I have done the following things in info.plist and in code
1.info.plist</p>
<pre><code><key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>Register.aspx</string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>Register.aspx</string>
</array>
</code></pre>
<p>2.in app delegate i used:</p>
<pre><code>- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL canBeOpened = [[UIApplication sharedApplication]
canOpenURL:[NSURL URLWithString:@"Register.aspx://"]];
if (canBeOpened) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test Message"
message:@"This is a url scheme"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test Message"
message:@"This is not a url scheme"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
</code></pre>
| 1 | 1,158 |
Easy way to add a drawer item with custom onPress?
|
<p>I'm using DrawerNavigator and, as long as I want to navigate to a new screen, all's fine.</p>
<p>Now I want to add a drawer item which does not navigate to a new screen but simply triggers an action (in general). Specifically, I want to use 'react-native' Share functionality.</p>
<p>I got this to work but I think the solution is not a very good one. Here's what I got so far:</p>
<pre class="lang-jsx prettyprint-override"><code>const myContentComponent = props => (
<ScrollView alwaysBounceVertical={false}>
<SafeAreaView style={{ flex: 1 }} forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems {...props} />
<TouchableItem
key="share"
onPress={() => {
Share.share(
{
message: 'YO: this will be the text message',
url: 'http://tmp.com',
title: 'This will be the email title/subject',
},
{
// Android only:
dialogTitle: 'This will be the title in the dialog to choose means of sharing',
},
);
props.navigation.navigate('DrawerClose');
}}
delayPressIn={0}
>
<SafeAreaView forceInset={{ left: 'always', right: 'never', vertical: 'never' }}>
<View style={[{ flexDirection: 'row', alignItems: 'center' }, {}]}>
<View style={[{ marginHorizontal: 16, width: 24, alignItems: 'center' }, { opacity: 0.62 }, {}]}>
<Icon name="share" />
</View>
<Text style={[{ margin: 16, fontWeight: 'bold' }, { color: DrawerItems.defaultProps.inactiveTintColor }]}>Share</Text>
</View>
</SafeAreaView>
</TouchableItem>
</SafeAreaView>
</ScrollView>
);
const RootStack = DrawerNavigator(
{
Settings: {
screen: SettingsScreen,
},
},
{
contentComponent: myContentComponent,
},
);
</code></pre>
<p>Basically, I am creating a new <code>contentComponent</code> based off of the default:</p>
<p><a href="https://github.com/react-navigation/react-navigation/blob/v1.5.8/src/navigators/DrawerNavigator.js#L16-L22" rel="noreferrer">https://github.com/react-navigation/react-navigation/blob/v1.5.8/src/navigators/DrawerNavigator.js#L16-L22</a></p>
<p>I am copying the styles and element structure of a normal drawer item (everything under <code>TouchableItem</code>) - all this so I can define my own <code>onPress</code> which does the share logic and closes the drawer.</p>
<p>There has to be a better way right? What happens if I want the "Share" drawer item somewhere amongst the drawer items rendered by <code>DrawerItems</code> (the ones that support navigation)? Right now I can only work around the items rendered by <code>DrawerItems</code>. Besides, copying so much code from react-navigation seems like really bad form.</p>
<p>I just want an item which does some custom logic instead of rendering a screen.</p>
| 1 | 1,531 |
null value in findcontrol of gridview, item template confusion
|
<p>I have Template Field for gridview as below:</p>
<pre><code><asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
&nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</code></pre>
<p>When i am in <code>gv_RowUpdating</code> event, i wanted to take the value of edited field by findcontrol.</p>
<p>For that i am using following code:</p>
<pre><code>`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
</code></pre>
<p>But each time it is showing me <code>null</code> value in <code>txtUname</code> when i debug the code.</p>
<p>What can be the problem?</p>
<p>Full Event Code:</p>
<pre><code> protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=@eName");
cmd.parameters.AddParametersWithValue("@eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
</code></pre>
| 1 | 2,063 |
ZF2 tutorial Album PHPUnit test failing with Undefined property: AlbumTest\Model\AlbumTableTest::$controller
|
<p>I am building the ZF2 Album tutorial application and when I unit test I am consistently receiving the same error even though I've rebuilt the application again. Can someone tell me what is going on here? I am dumping all relevant information here to assist. The error is:</p>
<pre><code>PHPUnit 3.7.10 by Sebastian Bergmann.
Configuration read from D:\PHP\zf2-tutorial\module\Album\test\phpunit.xml.dist
......E
Time: 0 seconds, Memory: 6.25Mb
There was 1 error:
1) AlbumTest\Model\AlbumTableTest::testGetAlbumTableReturnsAnInstanceOfAlbumTable
Undefined property: AlbumTest\Model\AlbumTableTest::$controller
D:\PHP\zf2-tutorial\module\Album\test\AlbumTest\Model\AlbumTableTest.php:116
FAILURES!
Tests: 7, Assertions: 9, Errors: 1.
</code></pre>
<p>AlbumTableTest.php is as follows and the error is received on the final assertion:</p>
<pre><code><?php
namespace AlbumTest\Model;
use Album\Model\AlbumTable;
use Album\Model\Album;
use Zend\Db\ResultSet\ResultSet;
use PHPUnit_Framework_TestCase;
class AlbumTableTest extends PHPUnit_Framework_TestCase {
public function testFetchAllReturnsAllAlbums() {
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with()
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($resultSet, $albumTable->fetchAll());
}
public function testCanRetrieveAnAlbumByItsId() {
$album = new Album();
$album->exchangeArray(array('id' => 123,
'artist' => 'The Military Wives',
'title' => 'In My Dreams'));
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array($album));
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
$this->assertSame($album, $albumTable->getAlbum(123));
}
public function testCanDeleteAnAlbumByItsId() {
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('delete'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('delete')
->with(array('id' => 123));
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->deleteAlbum(123);
}
public function testSaveAlbumWillInsertNewAlbumsIfTheyDontAlreadyHaveAnId() {
$albumData = array('artist' => 'The Military Wives', 'title' => 'In My Dreams');
$album = new Album();
$album->exchangeArray($albumData);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('insert'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('insert')
->with($albumData);
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->saveAlbum($album);
}
public function testSaveAlbumWillUpdateExistingAlbumsIfTheyAlreadyHaveAnId() {
$albumData = array('id' => 123, 'artist' => 'The Military Wives', 'title' => 'In My Dreams');
$album = new Album();
$album->exchangeArray($albumData);
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array($album));
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select', 'update'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$mockTableGateway->expects($this->once())
->method('update')
->with(array('artist' => 'The Military Wives', 'title' => 'In My Dreams'), array('id' => 123));
$albumTable = new AlbumTable($mockTableGateway);
$albumTable->saveAlbum($album);
}
public function testExceptionIsThrownWhenGettingNonexistentAlbum() {
$resultSet = new ResultSet();
$resultSet->setArrayObjectPrototype(new Album());
$resultSet->initialize(array());
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array('select'), array(), '', false);
$mockTableGateway->expects($this->once())
->method('select')
->with(array('id' => 123))
->will($this->returnValue($resultSet));
$albumTable = new AlbumTable($mockTableGateway);
try {
$albumTable->getAlbum(123);
} catch (\Exception $e) {
$this->assertSame('Could not find row 123', $e->getMessage());
return;
}
$this->fail('Expected exception was not thrown');
}
public function testGetAlbumTableReturnsAnInstanceOfAlbumTable() {
$this->assertInstanceOf('Album\Model\AlbumTable', $this->controller->getAlbumTable());
}
}
?>
</code></pre>
<p>getAlbumTable is in AlbumController as follows: </p>
<pre><code><?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController {
protected $albumTable;
public function indexAction() {
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
public function addAction() {
}
public function editAction() {
}
public function deleteAction() {
}
public function getAlbumTable() {
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
}
?>
</code></pre>
<p>And AlbumTable is:</p>
<pre><code><?php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class AlbumTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);
$id = (int)$album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => $id));
}
}
?>
</code></pre>
<p>Module.php is:</p>
<pre><code><?php
namespace Album;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
?>
</code></pre>
<p>module.config.php is:</p>
<pre><code><?php
return array(
'controllers' => array(
'invokables' => array(
'Album\Controller\Album' => 'Album\Controller\AlbumController',
),
),
// The following section is new and should be added to your file
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
);
?>
</code></pre>
<p>application.config.php is:</p>
<pre><code><?php
return array(
'modules' => array(
'Application',
'Album', // <-- Add this line
),
'module_listener_options' => array(
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'./module',
'./vendor',
),
),
);
?>
</code></pre>
<p>Bootstrap.php:</p>
<pre><code><?php
namespace AlbumTest;//Change this namespace for your test
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use RuntimeException;
error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
class Bootstrap
{
protected static $serviceManager;
protected static $config;
protected static $bootstrap;
public static function init()
{
// Load the user-defined test configuration file, if it exists; otherwise, load
if (is_readable(__DIR__ . '/TestConfig.php')) {
$testConfig = include __DIR__ . '/TestConfig.php';
} else {
$testConfig = include __DIR__ . '/TestConfig.php.dist';
}
$zf2ModulePaths = array();
if (isset($testConfig['module_listener_options']['module_paths'])) {
$modulePaths = $testConfig['module_listener_options']['module_paths'];
foreach ($modulePaths as $modulePath) {
if (($path = static::findParentPath($modulePath)) ) {
$zf2ModulePaths[] = $path;
}
}
}
$zf2ModulePaths = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
$zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS') ? ZF2_MODULES_TEST_PATHS : '');
static::initAutoloader();
// use ModuleManager to load this module and it's dependencies
$baseConfig = array(
'module_listener_options' => array(
'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
),
);
$config = ArrayUtils::merge($baseConfig, $testConfig);
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $config);
$serviceManager->get('ModuleManager')->loadModules();
static::$serviceManager = $serviceManager;
static::$config = $config;
}
public static function getServiceManager()
{
return static::$serviceManager;
}
public static function getConfig()
{
return static::$config;
}
protected static function initAutoloader()
{
$vendorPath = static::findParentPath('vendor');
if (is_readable($vendorPath . '/autoload.php')) {
$loader = include $vendorPath . '/autoload.php';
} else {
$zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH') ? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library') ? $vendorPath . '/ZF2/library' : false));
if (!$zf2Path) {
throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
}
include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
}
AutoloaderFactory::factory(array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true,
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
),
),
));
}
protected static function findParentPath($path)
{
$dir = __DIR__;
$previousDir = '.';
while (!is_dir($dir . '/' . $path)) {
$dir = dirname($dir);
if ($previousDir === $dir) return false;
$previousDir = $dir;
}
return $dir . '/' . $path;
}
}
Bootstrap::init();
?>
</code></pre>
<p>TestConfig.php.dist:</p>
<pre><code><?php
return array(
'modules' => array(
'Album',
),
'module_listener_options' => array(
'config_glob_paths' => array(
'../../../config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'module',
'vendor',
),
),
);
?>
</code></pre>
<p>And, finally, phpunit.xml.dist:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="Bootstrap.php">
<testsuites>
<testsuite name="zf2tutorial">
<directory>./AlbumTest</directory>
</testsuite>
</testsuites>
</phpunit>
</code></pre>
| 1 | 7,340 |
How do I return an array from an array function using groovy?
|
<p>How do I return an array from an array function using Groovy? I am currently trying it with the following code but I am getting errors when I execute the code! I want to be able to get values from an array function where I am extracting the data from excel and I want to be able to use arbitrary values retrieved from the function. Can anyone help?</p>
<p>Code:</p>
<pre><code>package Check
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class Second {
static main(args) {
//def alpo = new String[2][3]
def alpo = getTableArray("KSuite");
println "£34." + alpo[1][2]
}
public static String[][] getTableArray(String xlSheet) throws Exception {
FileInputStream input = new FileInputStream(new File("C:\\Temp\\KSuite.xlsx"));
//System.out.println(input.path);
XSSFWorkbook workbook = new XSSFWorkbook(input);
//System.out.println(xlSheet);
XSSFSheet sheet = workbook.getSheet(xlSheet);
int ci;//,cj;
XSSFRow r = sheet.getRow(sheet.getFirstRowNum());
int jMax=Math.max(r.getLastCellNum()-r.getFirstCellNum(),2);
int iMax=sheet.getLastRowNum()-sheet.getFirstRowNum();
def tabArray= new String[sheet.getLastRowNum()-sheet.getFirstRowNum()][jMax];
//System.out.println(sheet.getLastRowNum()-sheet.getFirstRowNum());
//System.out.println(jMax);
for (int i = sheet.getFirstRowNum()+1; i <= sheet.getLastRowNum(); i++) {
ci = i - 1;
r = sheet.getRow(i);
for (int j = 0; j < jMax; j++) {
XSSFCell c = r.getCell(j, r.CREATE_NULL_AS_BLANK);
if(c.getCellType() == 1) {
tabArray[ci][j]=c.getStringCellValue();
} else {
tabArray[ci][j]=((float)(c.getNumericCellValue()) + "");
}
}
}
input.close();
// return(tabArray);
// return(cj);
return(tabArray);
// return(cj);
}
}
</code></pre>
<p>Error:</p>
<pre><code> Caught: java.lang.ArrayIndexOutOfBoundsException: 2
java.lang.ArrayIndexOutOfBoundsException: 2
at Check.Second.main(Second.groovy:15)
</code></pre>
<p>Table KSuite in KSuite.xlsx:</p>
<pre><code>Script Run
Login, Yes
Workspaces No
Users, Yes
</code></pre>
| 1 | 1,167 |
Two ajax updates with h:selectOneMenu f:ajax
|
<blockquote>
<p>In short, if a component has been updated by Ajax, it can not launch new events Ajax</p>
</blockquote>
<p>I have three h:selectOneMenu: A, B and C.
When I fire change event in A, then update the B h:selectOneMenu.
When I fire change event in B, then update the C h:selectOneMenu.</p>
<p>The problem is that when the content of B h:selectOneMenu is updated, the ajax in B don't work and C never can't be updated.</p>
<pre><code><h:selectOneMenu id="A" value="#{paqueteBean.mes}" label="a">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItem itemLabel="Enero" itemValue="ENERO" />
<f:selectItem itemLabel="Febrero" itemValue="FEBRERO" />
<f:ajax listener="#{paqueteBean.changeMes}" render="B" />
</h:selectOneMenu>
<h:selectOneMenu id="B" value="#{paqueteBean.origen}" label="b">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.origenes}" />
<f:ajax listener="#{paqueteBean.changeOrigen}" render="C"/>
</h:selectOneMenu>
<h:selectOneMenu id="C" value="#{paqueteBean.zona}" label="c">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.zonas}" />
</h:selectOneMenu>
</code></pre>
<p>The ajax response is good, but simply don't work after the update:</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<partial-response id="j_id1"><changes><update id="B"><![CDATA[<select id="B" name="b" size="1" onchange="mojarra.ab(this,event,'valueChange','@this','C')"> <option value="">Seleccione...</option>
<option value="BUE">Ezeiza o Aeroparque</option>
</select>]]></update><update id="j_id1:javax.faces.ViewState:0"><![CDATA[-2984590031183218074:6198891110668113457]]></update></changes></partial-response>
</code></pre>
<p>UPDATE!</p>
<p>With PrimeFaces I have the same behavior:</p>
<pre><code><h:form id="filtro">
<p:selectOneMenu id="A" value="#{paqueteBean.mes}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItem itemLabel="Enero" itemValue="ENERO" />
<f:selectItem itemLabel="Febrero" itemValue="FEBRERO" />
<f:selectItem itemLabel="Marzo" itemValue="MARZO" />
<p:ajax listener="#{paqueteBean.changeMes}" update="B" />
</p:selectOneMenu>
<p:selectOneMenu id="B" value="#{paqueteBean.origen}"
disabled="#{empty paqueteBean.mes}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.origenes}" />
<p:ajax listener="#{paqueteBean.changeOrigen}" update="C"
process="origen mesSalida" />
</p:selectOneMenu>
<p:selectOneMenu id="C" value="#{paqueteBean.zona}"
disabled="#{empty paqueteBean.mes or empty paqueteBean.origen}">
<f:selectItem itemLabel="Seleccione..." itemValue="" />
<f:selectItems value="#{paqueteBean.zonas}" />
</p:selectOneMenu>
</code></pre>
<p></p>
<p>When I change some A values, the method in backing bean is fired, but when I change some B value, the method in backing bean is not fired.</p>
<p>The most strange is that for items that existed in B before the ajax update, the backing bean is called.</p>
<p>Backing Bean, nothing special:</p>
<pre><code> public void changeMes(){
logger.debug("en changeMes el Mes es: " + this.mes);
this.origenes = new HashMap<String, String>();
this.origenes.put("Ezeiza o Aeroparque", "BUE");
}
public void changeOrigen(){
logger.debug("Mes: " + this.mes);
logger.debug("Origen" + this.origen);
this.zonas = new HashMap<String, String>();
this.zonas.put("Argentina", "AR");
this.zonas.put("Brasil", "BR");
}
public void changeZona(){
logger.debug("Mes: " + this.mes);
logger.debug("Origen" + this.origen);
logger.debug("Zona" + this.zona);
this.destinos = new HashMap<>();
this.destinos.put("Mar del Plata", "MDQ");
this.destinos.put("Punta Lara", "LTA");
}
</code></pre>
| 1 | 1,747 |
Using ezplot with specified ordinate range
|
<p>I have a symbolic function that I am plotting with ezplot:</p>
<pre><code> ezplot(f, [0,1]);
</code></pre>
<p>I could not find a way to specify the y-values (ordniate) to plot this function. However, I want f to be plotted for x in [0,1] and y in [0,1] also. Default ezplot plots my function for y in [0,20] or something like that. How can I specify the y-range?</p>
<p>Here is my function (in q):</p>
<pre><code> ((490*q^3 - 1300*q^2 + 1080*q - 240)^2/(9*(240*q - 300*q^2 + 90*q^3)^2) - (655*q^3 - 1570*q^2 + 1160*q - 240)/(3*(90*q^3 - 300*q^2 + 240*q)))/((10*q^2 - 7*q^3)/(480*q - 600*q^2 + 180*q^3) - (1080*q - 1300*q^2 + 490*q^3 - 240)^3/(27*(240*q - 300*q^2 + 90*q^3)^3) + (((10*q^2 - 7*q^3)/(480*q - 600*q^2 + 180*q^3) - (1080*q - 1300*q^2 + 490*q^3 - 240)^3/(27*(240*q - 300*q^2 + 90*q^3)^3) + ((1080*q - 1300*q^2 + 490*q^3 - 240)*(1160*q - 1570*q^2 + 655*q^3 - 240))/(6*(240*q - 300*q^2 + 90*q^3)^2))^2 - ((1080*q - 1300*q^2 + 490*q^3 - 240)^2/(9*(240*q - 300*q^2 + 90*q^3)^2) - (1160*q - 1570*q^2 + 655*q^3 - 240)/(720*q - 900*q^2 + 270*q^3))^3)^(1/2) + ((1080*q - 1300*q^2 + 490*q^3 - 240)*(1160*q - 1570*q^2 + 655*q^3 - 240))/(6*(240*q - 300*q^2 + 90*q^3)^2))^(1/3) - (490*q^3 - 1300*q^2 + 1080*q - 240)/(3*(90*q^3 - 300*q^2 + 240*q)) + ((10*q^2 - 7*q^3)/(2*(90*q^3 - 300*q^2 + 240*q)) - (490*q^3 - 1300*q^2 + 1080*q - 240)^3/(27*(240*q - 300*q^2 + 90*q^3)^3) + (((10*q^2 - 7*q^3)/(2*(90*q^3 - 300*q^2 + 240*q)) - (490*q^3 - 1300*q^2 + 1080*q - 240)^3/(27*(240*q - 300*q^2 + 90*q^3)^3) + ((490*q^3 - 1300*q^2 + 1080*q - 240)*(655*q^3 - 1570*q^2 + 1160*q - 240))/(6*(240*q - 300*q^2 + 90*q^3)^2))^2 - ((490*q^3 - 1300*q^2 + 1080*q - 240)^2/(9*(240*q - 300*q^2 + 90*q^3)^2) - (655*q^3 - 1570*q^2 + 1160*q - 240)/(3*(90*q^3 - 300*q^2 + 240*q)))^3)^(1/2) + ((490*q^3 - 1300*q^2 + 1080*q - 240)*(655*q^3 - 1570*q^2 + 1160*q - 240))/(6*(240*q - 300*q^2 + 90*q^3)^2))^(1/3)
</code></pre>
| 1 | 1,067 |
override core controller in custom module in Magento
|
<p>HI i have to extend the core controller in my own module for this i am referencing the below link
<a href="http://inchoo.net/tools-frameworks/how-to-extend-magento-core-controller/" rel="nofollow">http://inchoo.net/tools-frameworks/how-to-extend-magento-core-controller/</a></p>
<p>below is my module structure</p>
<p>/var/www/magento1.9/app/etc/modules</p>
<pre><code><?xml version="1.0"?>
<!--we need to enable this module as any other if-->
<!--you wish to do it as standalone module extension-->
<config>
<modules>
<Inchoo_Coreextended>
<active>true</active>
<codepool>local</codepool>
</Inchoo_Coreextended>
</modules>
</config>
</code></pre>
<p>/var/www/magento1.9/app/code/local/Inchoo/Coreextended/controllers/Frontend/Customer/AccountController.php</p>
<pre><code><?php
require_once Mage::getModuleDir('controllers', 'Mage_Customer').DS.'AccountController.php';
//we need to add this one since Magento wont recognize it automatically
class Inchoo_Coreextended_Frontend_Customer_AccountController extends Mage_Customer_AccountController
{//here, you extended the core controller with our
public function indexAction()
{
parent::indexAction();
//you can always use default functionality
}
public function myactionAction()
{
//my code
//you can write your own methods / actions
}
public function mymethod()
{
//my code
//you can write your own methods
}
public function loginAction()
{
echo "hello";
//finally you can write your code that will rewrite the whole core method
//and you can call for your own methods, as you have full control over core controller
}
}
</code></pre>
<p>/var/www/magento1.9/app/code/local/Inchoo/Coreextended/etc/config.xml</p>
<pre><code><?xml version="1.0"?>
<config>
<modules>
<Inchoo_Coreextended>
<version>0.1.0</version>
</Inchoo_Coreextended>
</modules>
<frontend>
<routers>
<customer>
<args>
<modules>
<Inchoo_Coreextended before="Mage_Customer_AccountController">Inchoo_Coreextended_Frontend_Customer</Inchoo_Coreextended>
</modules>
</args>
</customer>
</routers>
</frontend>
</config>
</code></pre>
<p>but when i am accessing the <code>http://localhost/magento1.9/index.php/customer/account/login/</code> it shows core login action and it is not switching from my module Can you please suggest where i am doing mistake .</p>
| 1 | 1,164 |
"Error converting data type nvarchar to numeric."
|
<p>I'm trying to create a function that returns a table with a bunch of fields.
The query used in the function inserts data to a temp table which then inserts into the returning table.
query runs fine when I run it outside of the function but when I select from the function I get "Error converting data type nvarchar to numeric." error. </p>
<p>The structure for the returning table is the same is the table which selects and inserts into the returning table. Below is how the function is defined</p>
<pre><code>ALTER FUNCTION [dbo].[Func_PrescriberData](@NetworkID Bigint, @StartDate datetime, @EndDate datetime)
RETURNS @rtnTable TABLE
(
Name nvarchar(1000) null,ClinicID int null ,NetworkPrescriberID int Null,GuideMedPatients int NULL, InactivePatients int NULL,AvgAge decimal NULL,AvgPHQScore decimal NULL,
[%RiskAssessmentHigh] varchar(10) NULL ,[%RiskAssessmentModerate] varchar(10) NULL,[%RiskAssessmentLow] varchar(10) NULL,
ToxicologyTests int NULL,[%ConsistentResults] varchar(10) NULL, [%Alcohol] varchar(10) NULL,[%NegativePrescribed] varchar(10) NULL
,[%Illicit] varchar(10) NULL,TotalPDMPs int NULL,[%AberrantResults] varchar(10) NULL, CSAReviewed int NULL,Type nvarchar(1000) null ,medlesstan15 int NULL,between15and59 int NULL,between60and100 int NULL,between101and500 int NULL,greaterthan500 int NULL, avgmed decimal NULL, [BH/AM] int NULL,OpiodsBelowThreshold int NULL,OpioidPreScreening int NULL,SedativesAntiAnxiety int NULL,Stimulants int NULL,Other int NULL)
AS
BEGIN
DECLARE @TempTable table
(
Name nvarchar(1000) null,ClinicID int null ,NetworkPrescriberID int Null,GuideMedPatients int NULL, InactivePatients int NULL,AvgAge decimal NULL,AvgPHQScore decimal NULL,
[%RiskAssessmentHigh] varchar(10) NULL ,[%RiskAssessmentModerate] varchar(10) NULL,[%RiskAssessmentLow] varchar(10) NULL,
ToxicologyTests int NULL,[%ConsistentResults] varchar(10) NULL, [%Alcohol] varchar(10) NULL,[%NegativePrescribed] varchar(10) NULL
,[%Illicit] varchar(10) NULL,TotalPDMPs int NULL,[%AberrantResults] varchar(10) NULL, CSAReviewed int NULL,Type nvarchar(1000) null ,medlesstan15 int NULL,between15and59 int NULL,between60and100 int NULL,between101and500 int NULL,greaterthan500 int NULL, avgmed decimal NULL, [BH/AM] int NULL,OpiodsBelowThreshold int NULL,OpioidPreScreening int NULL,SedativesAntiAnxiety int NULL,Stimulants int NULL,Other int NULL)
insert into @TempTable (
Name ,ClinicID,NetworkPrescriberID,GuideMedPatients, InactivePatients ,AvgAge ,AvgPHQScore ,[%RiskAssessmentHigh],[%RiskAssessmentModerate] ,[%RiskAssessmentLow]
,ToxicologyTests ,[%ConsistentResults], [%Alcohol] ,[%NegativePrescribed] ,[%Illicit],TotalPDMPs ,[%AberrantResults],
CSAReviewed ,Type,medlesstan15,between15and59,between60and100,between101and500,greaterthan500,avgmed,[BH/AM],OpiodsBelowThreshold,OpioidPreScreening,SedativesAntiAnxiety,Stimulants,Other
</code></pre>
<p>It's probably hard to tell what the issue is from the above script but I'm looking for a way to debug where the issue is.
Strange thing is the function runs fine if I change one of the parameters (change NetworkID) which is supposed to return data in the same format.</p>
<p>Can someone help me point to where to look?</p>
<p>Thanks,</p>
<p>I've found a link to post the entire sql script. It can be found <a href="http://www.tutorialspoint.com/execute_sql_online.php?PID=0Bw_CjBb95KQMclFFaTZ2azVlMEk" rel="nofollow noreferrer">here</a></p>
| 1 | 1,164 |
move my progressbar with an image android
|
<p>i have this code </p>
<p>is a progress bar that fill with a red color</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<gradient
android:startColor="#c3c3c3"
android:centerColor="#c3c3c3"
android:centerY="0.75"
android:endColor="#7f7f7f"
android:angle="270"/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"/>
<corners android:radius="10dp"/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<gradient
android:startColor="#234"
android:centerColor="#234"
android:centerY="0.75"
android:endColor="#a24"
android:angle="270"/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"/>
<corners android:radius="10dp"/>
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<gradient
android:startColor="#a42c48"
android:centerColor="#a42c48"
android:centerY="0.75"
android:endColor="#eb3e67"
android:angle="270"/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"/>
<corners android:radius="10dp"/>
</shape>
</clip>
</item>
</layer-list>
</code></pre>
<p>and look like this</p>
<p><img src="https://i.stack.imgur.com/DmAHy.png" alt="enter image description here"></p>
<p>now i want to add an image to move at the same time the progress bar fills up like the image below</p>
<p><img src="https://i.stack.imgur.com/C7GJx.png" alt="enter image description here"></p>
<p>please help me</p>
<p>thanks in advance</p>
| 1 | 1,267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.