input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
how split the array and save to database? <p>I parsed a file using <code>smarter_csv</code>: </p>
<pre><code>file = SmarterCSV.process(smarter_csv, file_encoding: windows-1251', col_sep: ';', verbose: true, convert_values_to_numeric: true, remove_zero_values: false)
</code></pre>
<p>And got this array:</p>
<pre><code>[{:code=>"1", :Name=>"Pen"},
{:code=>"2", :Name=>"Apple"}]
</code></pre>
<p>how you can break this array to save it in the database?</p>
<p>I guess you need to iterate through items using <code>each</code></p>
|
<p>Assuming you have Product model and attributes are code:string and name:string. And you store the parsed results in data variable.</p>
<p>You need to do the following:</p>
<pre><code>data = [{:code=>"1", :name=>"Pen"},
{:code=>"2", :name=>"Apple"}]
data.each{|row| Product.create(row) }
</code></pre>
<p>This will create two entries in your Product model.</p>
|
Dropbox API, Python3, Requests 400 Bad Request <p>I am able to authenticate and connect to the DropBox API and run <a href="https://www.dropbox.com/developers/documentation/http/teams#team-members-list" rel="nofollow"><code>team-members-list</code></a>.</p>
<p>But I get the following error when I attempt to run <a href="https://www.dropbox.com/developers/documentation/http/teams#team-members-remove" rel="nofollow"><code>team-members-remove</code></a> with additional header and data in the request.</p>
<blockquote>
<p>requests.exceptions.HTTPError: 400 Client Error: Bad Request for url:</p>
</blockquote>
<p>When adding <code>try</code>:</p>
<blockquote>
<p>raise JSONDecodeError("Expecting value", s, err.value) from None<br>
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </p>
</blockquote>
<p>Python code so far:</p>
<pre class="lang-py prettyprint-override"><code>headers = {'Authorization': 'Bearer ' + TOKEN}
url = 'https://api.dropboxapi.com/2/team/members/remove'
data = {
"user": {".tag": "team_member_id", "team_member_id": userid},
"wipe_data": "true",
"transfer_dest_id": {".tag": "team_member_id", "team_member_id": adminid},
"transfer_admin_id": {".tag": "team_member_id", "team_member_id": adminid},
"keep_account": "false",
}
response = requests.post(url, data=data, headers=headers)
</code></pre>
<p>I have attempted some variations on the above, including:</p>
<pre><code>headers = {'Authorization': 'Bearer ' + TOKEN, "Content-Type": "application/json" }
response = requests.post(url, json=data, headers=headers)
data = json.dump(data)
</code></pre>
<p>There are a few of these errors documented here, I've had a read of them and implemented the suggestions but still not been able to resolve this.</p>
<p>Any pointers greatly appreciated.</p>
<p>Background: </p>
<ul>
<li>Python 3.5.2</li>
<li>Requests</li>
<li>Dropbox for Business API</li>
</ul>
|
<p>Where I was going wrong was I was attempting to run the response.text through json.loads e.g.</p>
<pre><code>message = json.loads(response.text)
</code></pre>
<p>I changed this to </p>
<pre><code>print(response.text)
</code></pre>
<p>This way I was presented with the helpful error messages.</p>
<p>Code now looks like this and its working:</p>
<pre><code>headers = {"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"}
jsondata = json.dumps(data)
response = requests.post(url, data=jsondata, headers=headers)
</code></pre>
|
Elasticsearch how to query on ID field higher than x <p>I am trying to apply pagination to results by querying multiple times to get past the 10k barrier of Elasticsearch. Since the results of Elasticsearch can differ during multiple queries I want to use the generated ID to get the next results. </p>
<p>So for example, I run a query that returns 1000 results. Then I want to get the ID value of the 1000th result, and perform a query like : match : ID {{1000thID}}</p>
<p>This way I want to get the 1001 until 2000 result. after that 2001 until 3000, so on.</p>
<p>I currently use the Elasticsearch DSL for python to query on domain name like:</p>
<pre><code>search.query('match', domainname=domainname)
</code></pre>
<p>How do I rebuild this code to match above requirements. ('match',_ID > ID_Variable) </p>
|
<p>The best way to achieve what you want is to use the scroll/can API. However, if you still want to proceed that way, you can do it like this:</p>
<pre><code>last_id = ...
search.filter('range', id={'gt': last_id + 1, 'lt': last_id + 1000})
</code></pre>
|
UWP Write (and read) file in a (from) folder from a string <p>I'm developing an application for UWP only for desktop. A user can select in a <em>Settings page</em> where he wants to create some files and folders. Usually I used <code>StreamWriter</code> like:</p>
<pre><code>using (System.IO.StreamWriter file = new System.IO.StreamWriter(path)) {
file.WriteLine("Something");
}
</code></pre>
<p>I tried to use now <code>StorageFolder</code></p>
<pre><code>StorageFolder folder = ApplicationData.Current.LocalFolder;
</code></pre>
<p>but I can't find a way to specify a folder from a string like <code>C:\MyFolder</code>.</p>
<p>Thank you in advance.</p>
|
<p>You can let the user specify the folder he wants using the <a href="https://msdn.microsoft.com/library/windows/apps/br207881" rel="nofollow">FolderPicker</a> class.</p>
<pre><code>var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
// Application now has read/write access to all contents in the picked folder
// (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
//<<Here, you can write your files in the selected folder.>>
}
else
{
//Operation cancelled.
}
</code></pre>
<p>You can find more info on how to use it <a href="https://msdn.microsoft.com/el-gr/windows/uwp/files/quickstart-using-file-and-folder-pickers" rel="nofollow">here</a>.</p>
|
Spring-4 - Refactoring use of instanceof for calling appropriate method <p>I have below set of interfaces and classes.
Note the <code>doSomething</code> method. It has to check for the instance of the object before calling the interface method on it. I would like to avoid that, as it involves changing this method whenever a new Vehicle is added. What is the best way of doing this in Spring?</p>
<pre><code>class SomeService {
@Autowired
VehicleRepairService<Car> carRepariService;
@Autowired
VehicleRepairService<Truck> truckRepairService;
public void doSomething(String vehicleId) {
Vehicle vehicle = getVehicle(vehicleId);
if(vehicle instanceof Car) {
carRepairService.repair(vehicle);
} else {
truckRepairService.repair(vehicle);
}
}
}
interface VehicleRepairService<T extends Vehicle> {
void repair(T vehicle);
}
class CarRepairService implements VehicleRepairService<Car> {
@Autowired
SomeDependency some;
void repair(Car vehicle) {
.......
}
}
class TruckRepairService implements VehicleRepairService<Car> {
@Autowired
DifferentDependency different;
void repair(Truck vehicle) {
.......
}
}
</code></pre>
|
<p>Since none of the answers has a generic solution. Spring allows to inject all implementations of a type. The solution below is not tested I wrote it in a text editor. It can be improved by making VehicleRepairService an abstract class and use for example ResolvableType retrieve the generic type in this abstract class. Than it is not necessary anymore to implement the getType method in every instance. </p>
<pre><code>class SomeService {
@Autowired
private List<VehicleRepairService> vehicleRepairServices;
public void doSomething(String vehicleId) {
Vehicle vehicle = getVehicle(vehicleId);
for(VehicleRepairService vehicleRepairService:vehicleRepairServices){
if(vehicle.getClass().equals(vehicleRepairService.getType())){
vehicleRepairService.repair(vehicle);
}
}
}
public Vehicle getVehicle(String id){
return new Truck();
}
}
interface VehicleRepairService<T extends Vehicle> {
void repair(T vehicle);
Class<T> getType();
}
class CarRepairService implements VehicleRepairService<Car> {
public void repair(Car vehicle) {
}
@Override
public Class<Car> getType() {
return Car.class;
}
}
class TruckRepairService implements VehicleRepairService<Truck> {
public void repair(Truck vehicle) {
}
@Override
public Class<Truck> getType() {
return Truck.class;
}
}
</code></pre>
|
How to not get data to overwritten in firebase and store an attribute as a list of items? <p>Whenever I click on the SAVE Button to save the name and number, the skills field is being overwritten.</p>
<p><a href="https://i.stack.imgur.com/qh4La.png" rel="nofollow">Here the image of Activity while storing details</a></p>
<p>Also please help me to get the skills as a list instead of creating new skilladd every time. Also new skills must be appended to the list without overwriting.</p>
<p>/**** ACCOUNT.JAVA ****/</p>
<pre><code>package com.coginitoamicis.coginitoamicis;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Account extends AppCompatActivity implements View.OnClickListener {
private EditText accname;
private EditText accnumb;
private EditText accskill;
private Button accsave;
private Button accskilladd;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser()==null){
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
accname = (EditText) findViewById(R.id.accname);
accnumb = (EditText) findViewById(R.id.accnumb);
accsave = (Button) findViewById(R.id.accsave);
accskill = (EditText) findViewById(R.id.accskill);
accskilladd = (Button) findViewById(R.id.accskilladd);
accsave.setOnClickListener(this);
accskilladd.setOnClickListener(this);
}
private void userdatasave(){
String name = accname.getText().toString().trim();
String numb = accnumb.getText().toString().trim();
if(TextUtils.isEmpty(name)){
//name is empty
Toast.makeText(this,"Please Enter your Name",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(numb)){
//number is empty
Toast.makeText(this,"Please Enter your Mobile Number",Toast.LENGTH_SHORT).show();
return;
}
UserInformation userInformation = new UserInformation(name, numb);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Information Saved",Toast.LENGTH_SHORT).show();
}
private void skilldatasave(){
String skill = accskill.getText().toString().trim();
if(TextUtils.isEmpty(skill)){
//skills is empty
Toast.makeText(this,"Enter Skill to Proceed",Toast.LENGTH_SHORT).show();
return;
}
Skilladd skilladds = new Skilladd(skill);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).push().setValue(skilladds);
Toast.makeText(this,"Skills Added Successfully",Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View view) {
if (view == accsave){
userdatasave();
}
if (view == accskilladd){
skilldatasave();
}
}
}
</code></pre>
<p>/**** USERINFORMATION.JAVA ****/</p>
<pre><code>package com.coginitoamicis.coginitoamicis;
public class UserInformation {
public String name;
public String numb;
public UserInformation(String name, String numb){
this.name = name;
this.numb = numb;
}
}
</code></pre>
<p>/**** SKILLADD.JAVA ****/</p>
<pre><code>package com.coginitoamicis.coginitoamicis;
public class Skilladd {
public String skill;
public Skilladd(String skill){
this.skill = skill;
}
}
</code></pre>
|
<p>Use Push()</p>
<pre><code>Firebase newsPush = new Firebase(Config.FIREBASE_URL);
final News news = new News();
news.setNewsTitle(newsTitleString);
news.setNewsDetails(newsDetailsString);
newsPush.push().setValue(news);
</code></pre>
<p>Create Getters and Setters for Object</p>
<pre><code>public class News implements Serializable {
private String newsTitle;
private String newsDetails;
private String newsDate;
private String newsPicUrl;
/*news Model to get and set news data*/
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
</code></pre>
|
Why df[[2,3,4]][2:4] works and df[[2:4]][2:4] does not in Python <p>suppose we have a datarame</p>
<pre><code>import pandas as pd
df = pd.read_csv('...')
df
0 1 2 3 4
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
</code></pre>
<p>Why one approach is working and other returns syntax error?</p>
|
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p>
<pre><code>print (df.ix[2:4,2:4])
2 3
2 3 4
3 3 4
4 3 4
</code></pre>
|
Runining xercesImpl on java 6 <p>I am using xercesImpl.jar to create instance of DocumentImpl,
when I am runing the application on java6 I get the following error : </p>
<blockquote>
<p>The java class could not be loaded. java.lang.UnsupportedClassVersionError: (myClass) bad major version at offset=6</p>
</blockquote>
<p>at first I saw there Is a problem with my jdk , but after reading about it a little more I read there is conflict in xerces-2_11_0.jar and jdk6.</p>
<p>What jars and in what versions should I add to the project to avoid this problem ? </p>
<p>Thanks </p>
|
<p>Try using xercesImpl jar wothversion 2.11.0. you can find maven details as below :</p>
<pre><code><dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>
</code></pre>
<p>This should solve your conflicts.</p>
|
The Button btnGet is not working, what should I do <pre><code> ProfileActivity.java;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
//firebase auth object
private FirebaseAuth firebaseAuth;
//view objects
public TextView textViewUserEmail;
private Button buttonLogout,btnGet;
public EditText edtxtLati, edtxtLongi;
private LocationManager locationManager;
private LocationListener locationListener;
private Double lati, longi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
lati = location.getLatitude();
edtxtLati.append("" + lati);
longi = location.getLongitude();
edtxtLongi.append("" + longi);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
//VERSION AND PERMISSION CHECKING
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
} else {
configureButton();
}
//initializing firebase authentication object
firebaseAuth = FirebaseAuth.getInstance();
//if the user is not logged in
//that means current user will return null
if (firebaseAuth.getCurrentUser() == null) {
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
//getting current user
FirebaseUser user = firebaseAuth.getCurrentUser();
//initializing views
textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
edtxtLati = (EditText)findViewById(R.id.edtxtLati);
edtxtLongi = (EditText)findViewById(R.id.edtxtLongi);
btnGet = (Button)findViewById(R.id.btnGet);
//displaying logged in user name
textViewUserEmail.setText("Welcome "+user.getEmail());
//adding listener to button
buttonLogout.setOnClickListener(this);
}
public void onRequestPermissionsResult(int requestCode, String[] permission, int[] grantResults) {
switch(requestCode)
{
case 10:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED )
configureButton();
}
}
private void configureButton() {
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});
}
@Override
public void onClick(View view) {
//if logout is pressed
if (view == buttonLogout) {
//logging out the user
firebaseAuth.signOut();
//closing activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
}
}
</code></pre>
<blockquote>
<p>/AndroidRuntime: FATAL EXCEPTION: main
Process: com.praful.lochub, PID: 3742
java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=10,
result=-1, data=Intent {
act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to
activity {com.praful.lochub/com.praful.lochub.ProfileActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.praful.lochub.ProfileActivity.configureButton(ProfileActivity.java:121)
at com.praful.lochub.ProfileActivity.onRequestPermissionsResult(ProfileActivity.java:115)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7069)
at android.app.Activity.dispatchActivityResult(Activity.java:6921)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)Â
at android.app.ActivityThread.-wrap20(ActivityThread.java)Â
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)Â
at android.os.Handler.dispatchMessage(Handler.java:102)Â
at android.os.Looper.loop(Looper.java:154)Â
at android.app.ActivityThread.main(ActivityThread.java:6077)Â
at java.lang.reflect.Method.invoke(Native Method)Â
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)Â
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)Â
Application terminated.</p>
</blockquote>
<pre><code> activity_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.praful.lochub.ProfileActivity"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textViewUserEmail"
android:layout_gravity="center_horizontal"
android:fontFamily="casual"
android:textColor="@color/colorAccent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:id="@+id/buttonLogout"
android:layout_gravity="center_horizontal"
android:fontFamily="casual"
android:textColor="@color/common_google_signin_btn_text_dark_default"
android:textStyle="normal|bold"
android:textAllCaps="false"
android:textSize="18sp"
android:background="@color/colorAccent"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignBottom="@+id/textViewUserEmail" />
<Button
android:text="Get Location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnGet"
style="@style/Widget.AppCompat.Button.Colored"
android:fontFamily="casual"
android:textStyle="normal|bold"
android:textAllCaps="false"
android:textSize="16sp"
android:layout_below="@+id/edtxtLongi"
android:layout_centerHorizontal="true" />
<ImageButton
android:background="@drawable/showonmap"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_below="@+id/edtxtLongi"
android:layout_alignParentEnd="true"
android:layout_marginEnd="12dp"
android:id="@+id/imgbtnMap" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/edtxtLati"
android:hint="Latitude"
android:textAlignment="center"
android:fontFamily="casual"
android:layout_marginTop="15dp"
android:layout_below="@+id/textViewUserEmail"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/edtxtLongi"
android:fontFamily="casual"
android:hint="Longitude"
android:textAlignment="center"
android:layout_below="@+id/edtxtLati"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/loc"
android:id="@+id/imgbtnLocate"
android:background="@null"
android:layout_marginBottom="22dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</code></pre>
|
<p>Place your initialization:</p>
<pre><code>//initializing views
textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
edtxtLati = (EditText)findViewById(R.id.edtxtLati);
edtxtLongi = (EditText)findViewById(R.id.edtxtLongi);
btnGet = (Button)findViewById(R.id.btnGet);
</code></pre>
<p>at the top of your onCreate method right after</p>
<pre><code>setContentView(R.layout.activity_profile);
</code></pre>
<p>Your configureButton() method is the issue since it uses btnGet before it's initialized. You can see this from this line of your log:</p>
<pre><code>reference at com.praful.lochub.ProfileActivity.configureButton(ProfileActivity.java:121)
</code></pre>
|
Cannot find module './_apply' <p>If I run </p>
<pre><code>node index
</code></pre>
<p>I get: </p>
<pre><code>ERROR: Cannot find module './_apply'
</code></pre>
<p>I used npm install, and tried to manually install it</p>
<p>which node returns:</p>
<pre><code>/usr/bin/node
</code></pre>
<p>which npm returns:</p>
<pre><code>/usr/bin/npm
</code></pre>
<p>and echo $NODE_PATH</p>
<pre><code>/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
</code></pre>
<p>Apply is in node_modules, so I have no idea what's going on.</p>
|
<p>Did you "npm install apply" and did you try doing require("apply")?</p>
|
how to set slide proportions with ReporteRs package <p>I started to play with the <code>ReporteRs</code> package and hanging at a simple problem. I am trying to get a specific format for ma slides, for example to present on a 1280x1024 projector without any bars... But the slides created by <code>ReporteRs</code> have strange dimensions. Is there a way to set the size of the slides somehow?</p>
<p>Here is the example code:</p>
<pre><code>require(ReporteRs)
require(ggplot2)
myplot <- qplot(Sepal.Length, Petal.Length,
data=iris, color=Species,
size=Petal.Width, alpha=I(0.7))
# Create a new document
mydoc <- pptx(title="EVG demo")
mydoc <- addSlide(mydoc, "Content with Caption")
mydoc <- addTitle(mydoc, "Vector graphics format versus raster format")
mydoc <- addPlot(mydoc, function() print(myplot), vector.graphic=TRUE)
mydoc <- addPlot(mydoc, function() print(myplot), vector.graphic=FALSE)
writeDoc(mydoc, file="EVG_example.pptx")
</code></pre>
|
<p>I guess I just figured it out on my own. I saved an empty PowerPoint document with the expected ratios as <code>template.pptx</code> and used this when using function <code>pptx()</code>...</p>
<pre><code>myplot <- qplot(Sepal.Length, Petal.Length,
data=iris, color=Species,
size=Petal.Width, alpha=I(0.7) )
# Create a new document
mydoc <- pptx(title="EVG demo", template='template.pptx')
mydoc <- addSlide(mydoc, "Content with Caption")
mydoc <- addTitle(mydoc, "Vector graphics format versus raster format")
mydoc <- addPlot(mydoc, function() print(myplot), vector.graphic=TRUE)
mydoc <- addParagraph(mydoc, 'test test 1 2 3')
writeDoc(mydoc, file="EVG_example.pptx")
</code></pre>
|
Strange crash when using for loop <p>I have an app that is creating and filling entities inside a </p>
<pre><code>[[self managedObjectContext] performBlockAndWait
</code></pre>
<p>Inside this block I use a for loop to cycle through some data and create entities using this data. </p>
<p><strong>The strange part is :</strong>
If I use
<code>for ( Entity in Array )</code> it will crash after about 10 iterations. If I use the old <code>for ( int i = 0 i < array.count; i++)</code> and then access the array using <code>i</code> there is no crash. The crash is a <strong>signal SIGABRT</strong> </p>
<p>Can anyone think of a reason why this crash would occur?</p>
|
<p>try</p>
<pre><code>for ( Entity in array.length )
</code></pre>
|
Splitting text gathered using .text() <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(document).ready(function(){
var dates = "July 5, 2016July 12, 2016";
var splitted = dates.split(/\B(?=[A-Z])/);
var k = [];
for (i of splitted ) {
k.push(i.match(/\d+(?=,)/)[0]);
// alert(typeof k);
}
if (k) {
$.each(k, function(key, value) {
var date = value;
$(".fc-list-heading-main").append(date);
});
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc-list-heading-main"></div>
<div class="fc-list-heading-main"></div></code></pre>
</div>
</div>
</p>
<p>I'm working on this calendar of events for a website.The calendar gets messed up whenever there is more 1 event for a month. I'm working for a fix and got stuck on this one:</p>
<p>My code:</p>
<pre><code><script>
$(document).ready(function(){
$(".fc-prev-button").click(function(){
$('.fc-list-heading-main').each(function (index, value){
var dates = $(".fc-list-heading-main").text();
console.log(dates);
});
});
});
</script>
</code></pre>
<p>The result:</p>
<p><a href="https://i.stack.imgur.com/3w1Je.png" rel="nofollow"><img src="https://i.stack.imgur.com/3w1Je.png" alt="enter image description here"></a></p>
<p>How can I separate July 12, 2016 from July 5, 2016? I need to pass them as a separate date. Hope someone could help me on this one. Thanks in advance!</p>
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(document).ready(function(){
var dates = "July 5, 2016July 12, 2016";
var splitted = dates.split(/\B(?=[A-Z])/);
var k = [];
for (i of splitted ) {
k.push(i.match(/\d+(?=,)/)[0]);
}
if (k) {
$.each(k, function(key, value) {
$(".fc-list-heading-main").eq(key).append(value);
});
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fc-list-heading-main"></div>
<div class="fc-list-heading-main"></div></code></pre>
</div>
</div>
</p>
|
AngularGrid library produces empty space in some special cases <p>I am using Angular grid to achieve a Pintrest-like fluid layout of items on my page. It works fine in general but in soem special cases it produces an empty space on my page. It seems the position of item7 is not calculated correctly
<a href="https://i.stack.imgur.com/ZS62L.gif" rel="nofollow"><img src="https://i.stack.imgur.com/ZS62L.gif" alt="mockup of what is happening ins ome cases"></a>
I am using AngularGrid from <a href="https://github.com/s-yadav/angulargrid" rel="nofollow">here</a>
My code is quite similar to what they recommend in their <a href="http://ignitersworld.com/lab/angulargrid/#documentation" rel="nofollow">documentation</a> except that I am not using an image but a custom component inside the ng-repeat.
so it looks like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('app').controller('demo', demo);
function demo($rootScope, $scope, apiService, angularGridInstance) {
var self=this;
this.noOfProjects=8;
this.firstNo=0;
this.loadedProjects;
this.totalProjects;
apiService.searchProjects($rootScope.userId, self.noOfProjects, self.firstNo).then(function(response) {
console.log(response.data);
self.loadedProjects = response.data.matches;
self.totalProjects = response.data.header.totalCount;
console.log(self.loadedProjects);
$scope.pics=self.loadedProjects;
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dynamic-grid{
position: relative;
}
.angular-grid > *{
opacity: 1;
}
.dynamic-grid.angular-grid{
display: block;
}
.grid {
position: absolute;
list-style: none;
background: #ffffff;
box-sizing: border-box;
-moz-box-sizing : border-box;
overflow: hidden;
}
.grid-img {
width: 100%;
vertical-align: middle;
background-color: #fff;
}
.grid-img.img-loaded{
visibility: visible;
opacity: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="" data-ng-controller="demo">
<ul class="dynamic-grid" angular-grid="pics" grid-width="300" gutter-size="10" angular-grid-id="gallery" refresh-on-img-load="false" >
<li data-ng-repeat="project in pics" class="grid" data-ng-clock>
<project-info-min-grid project="project" class="grid-img" ></project-info-min-grid>
</li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>Can anyone help with this problem?</p>
|
<p>Ok. a bit of research showed that this was actually cased by this css on some parts of the content of each item:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;</code></pre>
</div>
</div>
</p>
<p>Instead I am now shortening the string in javascript like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var maxLength=100;
if(self.project.description){
if(self.project.description.length > maxLength) {
self.project.description = self.project.description.substring(0,maxLength-1)+"...";
}
}</code></pre>
</div>
</div>
</p>
<p>and everything works fine. Just in case someone else runs into this problem...</p>
|
Is there any simulator/tool to generate messages for streaming? <p>For testing purpose, I need to simulate client for generating 100,000 messages per second and send them to kafka topic. Is there any tool or way that can help me generate these random messages?</p>
|
<p>There's a built-in tool for generating dummy load, located in <code>bin/kafka-producer-perf-test.sh</code> (<a href="https://github.com/apache/kafka/blob/trunk/bin/kafka-producer-perf-test.sh" rel="nofollow">https://github.com/apache/kafka/blob/trunk/bin/kafka-producer-perf-test.sh</a>). You may refer to <a href="https://github.com/apache/kafka/blob/trunk/tools/src/main/java/org/apache/kafka/tools/ProducerPerformance.java#L106" rel="nofollow">https://github.com/apache/kafka/blob/trunk/tools/src/main/java/org/apache/kafka/tools/ProducerPerformance.java#L106</a> to figure out how to use it. </p>
<p>One usage example would be like that:</p>
<pre><code>bin/kafka-producer-perf-test.sh --broker-list localhost:9092 --messages 10000000 --topic test --threads 10 --message-size 100 --batch-size 10000 --throughput 100000
</code></pre>
<p>The key here is the <code>--throughput 100000</code> flag which indicated "throttle maximum message amount to approx. 100000 messages per second"</p>
|
MySQL UNION returns ids that don't exist <p>I have a table <strong>t</strong> with 900 ids, 1-900. For the purpose of my task, I need to do something like (I think there is no meaning in try to reason behind this type of query, as it's something I'm experimenting on):
The id is NOT unique (as it is somewhat of foreign key let's say)!</p>
<pre><code>SELECT DISTINCT(t5.id) FROM (
SELECT DISTINCT(t1.id) FROM t t1 WHERE {...}
UNION SELECT DISTINCT(t2.id) FROM (
SELECT DISTINCT(t0.id) FROM t t0 WHERE {...}) as t2
INNER JOIN t t3 ON t2.id=t3.id WHERE{...}
UNION SELECT DISTINCT(t3.id) FROM t t4 WHERE {...})
t5 ORDER BY t5.id
</code></pre>
<p>The <em>problem</em> is that the query, returns ids that are far from the 900 existing ones. The go all they way up to more than 10.000-20.000. Please help me provide you all the necessary information needed.</p>
|
<p>I'm not sure, but perhaps you need to add <code>as id</code> in the second select field, like this: </p>
<pre><code>SELECT DISTINCT(id) FROM ( SELECT DISTINCT(t1.id) **as id** FROM t t1 WHERE {...} UNION SELECT DISTINCT(t2.id) FROM t t2 WHERE {...} INNER JOIN t t3 ON t2.id=t3.id WHERE{...} UNION SELECT DISTINCT(t3.id) FROM t t4 WHERE {...}) t5 ORDER BY t5.id
</code></pre>
|
SQL Query to Remove Double Quotes in PHP Script is Not Working <p>In my PHP script, I need to update fields to remove the double quotes in a particular column. When I execute my query, the fields are not stripped of the double quotes. I suspect that it has something to do with escaping the characters in the query. The query below is what phpMyAdmin generated for me when I clicked "Create PHP" after successfully running the query in phpMyAdmin.</p>
<pre><code>$sql = "UPDATE `TNDB_CSV2` \n"
. " SET `Event` = TRIM(BOTH \'\"\' FROM `Event`)";
</code></pre>
<p>How can I change this to run in my PHP script instead of running it manually in phpMyAdmin?</p>
|
<p>You are going to have to escape the slashes themselves so that they stick around when the SQL query is executed so I am suggesting you do it like so:</p>
<pre><code> $sql = "UPDATE `TNDB_CSV2` \n"
. " SET `Event` = TRIM(BOTH '\\\"' FROM `Event`)";
</code></pre>
<p>I also got rid of the backslashes around the quotes</p>
|
Running the sample code in pytesseract <p>I am running python 2.6.6 and want to install the <a href="https://pypi.python.org/pypi/pytesseract" rel="nofollow">pytesseract</a> package. After extraction and installation, I can call the pytesseract from the command line. However I want to run the tesseract within python. I have the following code (ocr.py):</p>
<pre><code>try:
import Image
except ImportError:
from PIL import Image
import pytesseract
print(pytesseract.image_to_string(Image.open('test.png')))
print(pytesseract.image_to_string(Image.open('test-european.jpg'),lang='fra'))
</code></pre>
<p>When I run the code by python ocr.py, I get the following output:</p>
<pre><code>Traceback (most recent call last):
File "ocr.py", line 6, in <module>
print(pytesseract.image_to_string(Image.open('test.png')))
File "/pytesseract-0.1.6/build/lib/pytesseract/pytesseract.py", line 164, in image_to_string
raise TesseractError(status, errors)
pytesseract.TesseractError: (2, 'Usage: python tesseract.py [-l language] input_file')
</code></pre>
<p>test.png and test-european.jpg are in the working directory. Can Someone help me running this code?
I have tried the following:</p>
<ol>
<li>Adjusted the tesseract_cmd to 'pytesseract'</li>
<li>Installed tesseract-ocr</li>
</ol>
<p>Any help is appreciated as I am trying to solve this problem for hours now.</p>
|
<p><code>tesseract_cmd</code> should point to the command line program <a href="https://github.com/tesseract-ocr/tesseract" rel="nofollow"><code>tesseract</code></a>, not <code>pytesseract</code>.</p>
<p>For instance on Ubuntu you can install the program using:</p>
<pre><code>sudo apt install tesseract-ocr
</code></pre>
<p>And then set the variable to just <code>tesseract</code> or <code>/usr/bin/tesseract</code>.</p>
|
UIWebview show previous loaded content for brief <p>I am loading html string with <strong>loadHTMLString</strong> method in <code>UIWebView</code> in <code>UICollectionViewCell</code> and reuse that cell.but <code>UIWebview</code> showing previous loaded content for brief and after that load new content.</p>
<p>anyone have any idea about this??</p>
|
<p>Load the Webview in following method of <code>UITableViewDelegate</code>:</p>
<pre><code>- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
</code></pre>
|
Any suggestion on how to investigate css issue in bootstrap-designed page? <p>Any suggestion on how to check why I get this black box instead of standard bootstrap dropdown? I know, may sound like stupid question, but bear this me...</p>
<p>I checked, there are no referenced css files that could break this functionality. The problem is that I can't right-click on that black box and select "Inspect" to see generated code, the black box disappears once I click on it (right or left). Similarly I cant use Chrome Dev Tools to inspect that element, it disappears.</p>
<p>Generated HTML code:</p>
<pre><code><form method="post" ng-submit="vm.executeAction('ReAssignWorkOrder')" class="ng-pristine ng-valid">
<div class="form-group">
<label>Service Provider</label>
<input type="text" class="form-control ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="vm.data.ServiceProvider" disabled="">
</div>
<div class="form-group">
<label>Re-Assign To</label>
<select class="form-control">
<option value="Someone1">Someone1</option>
<option value="Someone2">Someone2</option>
<option value="Someone3">Someone3</option>
</select>
</div>
<div class="form-group">
<label>Progress Note</label>
<textarea class="form-control ng-pristine ng-untouched ng-valid ng-empty" rows="4" ng-model="vm.woReAssign.ProgressNote"></textarea>
</div>
<button type="submit" class="btn btn-primary pull-left">Re-Assign</button>
<button type="submit" class="btn btn-primary pull-right">Re-Assign and Dispatch</button>
</form>
</code></pre>
<p><a href="https://i.stack.imgur.com/4uKwh.png" rel="nofollow"><img src="https://i.stack.imgur.com/4uKwh.png" alt="enter image description here"></a></p>
<p>Same thing happens with html input date field:</p>
|
<p><strong>UPDATE:</strong> Whoever voted to close the question - I dont understand the reason, dont you want other people to know it was <strong>Chrome bug</strong> ??</p>
<p><a href="https://i.stack.imgur.com/La57F.png" rel="nofollow"><img src="https://i.stack.imgur.com/La57F.png" alt="enter image description here"></a></p>
|
Column being passed in as dataframe after naming arguments in user defined function <p>[Newbie here]Stuck at a very weird problem. I have a function to calculate lag, it works fine when the arguments are not named in function, but doesn't when I give them a name. </p>
<p>The following code doesnt work, and prints "data.frame" as class of argument a (when i am passing a column)</p>
<pre><code>lagger = function(ind = a,dep = c,lag = b){
print(class(a))
print(paste("linear correlation" ,cor(a,c), sep=" "))
print(paste("log linear correlation:" ,cor(log(a),c), sep=" "))
print(paste("log log correlation:" ,cor(log(a),log(c)), sep=" "))
for (i in 1:b){
del = a
del <- c(rep(NA,i),a[1:(NROW(a)-i)])
corr = (cor(del,c,use="complete"))
corr_log = cor(del,c,use="complete")
corr_log_log = cor(log(del),log(c),use="complete")
print(paste(" lag of" ,i , "unit/s :" , round(corr,3) ,"log",round(corr_log,3),"log log",round(corr_log_log,3), sep = " ") )
}
}
</code></pre>
<p>While this code works:</p>
<pre><code>lagger = function( a,c,b){
print(class(a))
print(paste("linear correlation" ,cor(a,c), sep=" "))
print(paste("log linear correlation:" ,cor(log(a),c), sep=" "))
print(paste("log log correlation:" ,cor(log(a),log(c)), sep=" "))
for (i in 1:b){
del = a
del <- c(rep(NA,i),a[1:(NROW(a)-i)])
corr = (cor(del,c,use="complete"))
corr_log = cor(del,c,use="complete")
corr_log_log = cor(log(del),log(c),use="complete")
print(paste(" lag of" ,i , "unit/s :" , round(corr,3) ,"log",round(corr_log,3),"log log",round(corr_log_log,3), sep = " ") )
}
}
</code></pre>
<p>Why?
Thanks in advance.</p>
|
<p>in your function argument:</p>
<pre><code>ind = a
</code></pre>
<p>means that the value per default of the argument <code>ind</code> will be a.
<code>ind</code> is the name of your argument so you must use it in the function instead of <code>a</code>.</p>
<p>try this:</p>
<pre><code>lagger <- function(ind,dep,lag){
print(class(ind))
print(paste("linear correlation" ,cor(ind,dep), sep=" "))
print(paste("log linear correlation:" ,cor(log(ind),dep), sep=" "))
print(paste("log log correlation:" ,cor(log(ind),log(dep)), sep=" "))
for (i in 1:lag){
del = ind
del <- c(rep(NA,i),ind[1:(NROW(ind)-i)])
corr = (cor(del,dep,use="complete"))
corr_log = cor(del,dep,use="complete")
corr_log_log = cor(log(del),log(dep),use="complete")
print(paste(" lag of" ,i , "unit/s :" , round(corr,3) ,"log",round(corr_log,3),"log log",round(corr_log_log,3), sep = " ") )
}
}
</code></pre>
<p>then when you use your function you can use </p>
<pre><code>lagger(ind = a, dep =c, lag = b)
</code></pre>
<p>If a, b and c have been defined.</p>
|
Forms firing ngSubmit twice on Angular 2.0.1 <p>For any form in Angular 2.0.1, whenever I press return or click on the submit button, the <code>ngSubmit</code> output is fired twice. I'm already including the <code>FormsModule</code> in the application module:</p>
<pre><code>@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
routing
],
declarations: [
// ...
],
providers: [
// ...
],
bootstrap: [AppComponent]
})
export class AppModule {}
</code></pre>
<p>I've tried to follow some answers (such as <a href="https://github.com/angular/angular/issues/9954#issuecomment-231743596" rel="nofollow">this</a> one), but <code>disableDeprecatedForms</code> and <code>provideForms</code> have been removed since RC6. I've also tried to import the <code>DeprecatedFormsModule</code>, but it seems to have been removed as well.</p>
<p>What should I do to prevent the <code>ngSubmit</code> to be fired twice?</p>
<h1>UPDATE:</h1>
<p>I didn't think the template would matter in this case since it's a known issue and it happens for any form in the application, but here follow one of the forms as an example (stripped out of unnecessary classes and tags):</p>
<pre><code><form (ngSubmit)="login(user)">
<input [(ngModel)]="user.username" name="username" type="email" id="username" required>
<label for="username">Email</label>
<input [(ngModel)]="user.password" name="password" type="password" id="password" required>
<label for="password">Password</label>
<button>
Submit
</button>
</form>
</code></pre>
|
<p>After some some comments I tried to reproduce the error in a Plunker only to realize that the problem was something else entirely. What was being fired twice was not the <code>ngSubmit</code>, but the HTTP request.</p>
<p>I was subscribing twice to the same <code>http.post(args)</code>, what happens is that I need to call <code>.share()</code> so it won't be executed for every subscribe (<a href="http://stackoverflow.com/a/37241863/2908285">http://stackoverflow.com/a/37241863/2908285</a>).</p>
|
How to add class Angular 2 <p>I'm trying to override only a part of my default class (glyphicon-eye-...). </p>
<p>With this code :</p>
<pre><code><i [class.glyphicon-eye-open] = "isOpen" class="glyphicon glyphicon-eye-close"></i>
</code></pre>
<p>I get <code>class = "glyphicon glyphicon-eye-close glyphicon-eye-open"</code></p>
<p>How can i get this instead <code>class="glyphicon glyphicon-eye-open"</code> ?</p>
|
<p>Use the <a href="https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html" rel="nofollow">ng-class</a> instead</p>
<pre><code><i [ngClass]="{'glyphicon-eye-close': !isOpen, 'glyphicon-eye-open': isOpen}" class="glyphicon"></i>
</code></pre>
|
How to move positions of divs using css <p>How can I make an element visually switch position with another element using CSS? For example, if I have this HTML markup:</p>
<pre><code><html>
<body>
<div class="div1">Div1</div>
<div class="div2">Div2</div>
<div class="div3">Div3</div>
</body>
</html>
</code></pre>
<p>I want <code>.div3</code> and <code>.div1</code> to switch places. How can I do this using <strong>CSS</strong>?</p>
|
<p>You can do it using flexbox's <code>order</code> property:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex {
display: flex;
}
.flex > div {
width: 100px;
text-align: center;
border: 1px solid #ccc;
}
.div1 {order: 3;}
.div2 {order: 2;}
.div3 {order: 1;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex">
<div class="div1">Div1</div>
<div class="div2">Div2</div>
<div class="div3">Div3</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Preview:</strong></p>
<p><a href="https://i.stack.imgur.com/HzWxS.png"><img src="https://i.stack.imgur.com/HzWxS.png" alt="preview"></a></p>
|
Getting Error from Adding and Printing Linked Lists <p>Briefly, I want my code to add the given elements to the list and print it to the screen. The Problem is, it prints the last element of the list for 3 times and doesn't print the others. I spent so much time but I couldn't find the problem. </p>
<pre><code>public class Book {
private String name;
private double price;
private String writer;
public Book(String name, double price, String writer) {
super();
this.name = name;
this.price = price;
this.writer = writer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
}
</code></pre>
<p>Here is the Node class: </p>
<pre><code>public class Node {
public static void main(String[] args) {
Node nd = new Node(bk);
Book bk1;
bk1 = new Book("Of Mice and Men", 22, "John Steinbeck");
nd.add(bk1);
bk1 = new Book("The Grapes of Wrath", 28, "John Steinbeck");
nd.add(bk1);
bk1 = new Book("Tortilla Flat", 33, "John Steinbeck");
nd.add(bk1);
nd.printData();
}
private static Book bk;
private Node link;
public Node root;
public Book getBk() {
return bk;
}
public void setBk(Book bk) {
this.bk = bk;
}
public Node getLink() {
return link;
}
public void setMyNode(Node link) {
this.link = link;
}
public Node(Book bk) {
super();
this.bk = bk;
this.link=null;
this.root=null;
}
public void add(Book bk) {
Node currentNode = root;
Node newNode = new Node(bk);
if(root==null){
root = newNode;
}
else{
while(currentNode.link!=null){
currentNode = currentNode.link;
}
currentNode.link = newNode;
}
}
public void printData() {
Node currentNode = root;
while(currentNode!=null){
Book bk = currentNode.getBk();
System.out.println("Name: " + bk.getName() + " Price: " + bk.getPrice() + " Writer: " + bk.getWriter());
currentNode =currentNode.link;
}
}
}
</code></pre>
|
<p>Your Node Class also needs a Book instance variable:</p>
<pre><code>private static Book bk;
private Book book;
private Node link;
public Node root;
</code></pre>
<p>Then these methods need updated to use the instance variable over the class variable:</p>
<pre><code>public Book getBk() {
return book;
}
public void setBk(Book bk) {
this.book = bk;
}
public Node(Book bk) {
super();
this.book = bk;
this.link=null;
this.root=null;
}
</code></pre>
<p>I have tested this and it works.</p>
<p>Hope this helps,</p>
<p>Liam</p>
|
Force some child elements to right side <p>There are four child divs. These are visible in desktop like this way:</p>
<pre><code>First Text | Second Text | Third Text | Fourth Text
</code></pre>
<p>In mobile, they will be like this way:</p>
<pre><code>First Text | Third Text
Second Text | Fourth Text
</code></pre>
<p>HTML structure of this block:</p>
<pre><code><div class="col one">First Text</div>
<div class="col two">Second Text</div>
<div class="col three">Third Text</div>
<div class="col fourth">Fourth Text</div>
</code></pre>
<p>I am able to achieve this scenario in multiple ways. But, the problem is, it's an existing project at where <strong>I am not allowed to modify any HTML structure</strong>. Is this scenario possible with CSS only (something like css flex or other way)?</p>
<p>N:B: height of divs are dynamic, so using <code>position: absolute;</code> won't be suitable. I even tried calculating div height with jQuery and use those value for positioning other divs. But, as the data, elements etc are coming from dynamic way (something like ng-repeat way of angularjs), I could not get those value after page load. For those kind of complexity, <strong>I am finding proper CSS solution</strong> (if there are any).</p>
<p><strong><a href="https://jsfiddle.net/f95mqs8L/3/" rel="nofollow">FIDDLE DEMO</a></strong></p>
<p><strong>Update:</strong></p>
<p>I forgot to mention one thing. Sorry for that. There will be no extra vertical space between two divs.</p>
<p><img src="http://i.imgur.com/uUyMggS.png" /></p>
<p><br>
It should be like this:</p>
<p><img src="http://i.imgur.com/hGG5a5y.png" /></p>
<p><strong><a href="https://jsfiddle.net/f95mqs8L/6/" rel="nofollow">Updated Fiddle</a></strong> (by @Johannes)</p>
|
<p>Yes, since you can use FlexBox, you can use the <code>order</code> to make it work:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {display: flex;}
.col {width: 25%;}
@media screen and (max-width: 480px) {
.col {width: 50%;}
.one {order: 1;}
.two {order: 3;}
.three {order: 2;}
.fourth {order: 4;}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col one">First Text</div>
<div class="col two">Second Text</div>
<div class="col three">Third Text</div>
<div class="col fourth">Fourth Text</div></code></pre>
</div>
</div>
</p>
|
Negative subscripts in Bash arrays <p>After creating a simple bash stack script I encountered an error related to bash arrays.</p>
<p><em>From the Bash manual:</em></p>
<blockquote>
<p>An indexed array is created automatically if any variable is assigned
to using the syntax:</p>
<p><code>name[subscript]=value</code></p>
<p>name[subscript]=value The subscript is treated as an arithmetic
expression that must evaluate to a number. If subscript evaluates to a
number less than zero, it is used as an offset from one greater than
the arrayâs maximum index (so a subcript of -1 refers to the last
element of the array).</p>
</blockquote>
<p>Everything worked perfectly fine on my local machine unfortunately my server environment is slightly different.</p>
<p>The negative subscript worked on Ubuntu 14.04 / GNU bash version 4.3.11(1). However when I tried to run the same script on my server with GNU bash version 4.2.46(1) I encountered the following error:</p>
<pre><code>line 46: [-1]: bad array subscript
</code></pre>
<p>I tried to create an array and call the last element directly from the terminal (not inside the script) and it worked:</p>
<pre><code>user@local:~$ arr=( 1 2 3 4 5 )
user@local:~$ echo ${arr[-1]}
5
</code></pre>
<p>I am kinda confused here. Is there any solution or workaround for this?</p>
|
<p>Guess what's in the <a href="http://tiswww.case.edu/php/chet/bash/CHANGES" rel="nofollow">Bash changelog</a>:</p>
<p>For: <em>changes between this version, bash-4.3-beta, and the
previous version, bash-4.3-alpha</em></p>
<blockquote>
<p>x. The shell now allows assigning, referencing, and unsetting elements of
indexed arrays using negative subscripts (a[-1]=2, echo ${a[-1]}) which
count back from the last element of the array.</p>
</blockquote>
<p>For: <em>changes between this version, bash-4.2-alpha,
and the previous version, bash-4.1-release</em></p>
<blockquote>
<p>p. Negative subscripts to indexed arrays, previously errors, now are treated
as offsets from the maximum assigned index + 1.</p>
</blockquote>
<p>So your test is only reading with negative offsets (okay in ~4.2 and above), but your error stems from an attempt to assign or unset with negative offsets (okay in ~4.3 and above).</p>
<p>Perhaps you can refer to the length of the array and do some math on that with:<br>
(reading) <code>${arr[${#arr[@]}-1]}</code> and<br>
(assigning) <code>arr[${#arr[@]}-1]=last</code> and<br>
(clearing) <code>unset arr[${#arr[@]}-1]</code></p>
|
expressjs route methods before and after <p>How to add middleware functions to each of expressjs route functions ? Most of route functions which turn out to be CRUD on database have standard before and after statements - is there a way to have before and after for route functions.</p>
<pre><code> app.route('/api/resources').all(projectsPolicy.isAllowed)
.get(resources.list)
.post(resources.create);
</code></pre>
|
<p>I think it's possible to make this:</p>
<pre><code>app.route('/api/resources').all(projectsPolicy.isAllowed)
.get(before,resources.list,after)
.post(before,resources.create,after);
</code></pre>
<p>where before and after are functions</p>
|
how to use Idioms in xamarin.forms using C# code and XAML <p>How to use idiom to set Grid (height, width) padding, margin and to set label font size in xamarin forms using C# and XAML code.</p>
<p>I have an example of use Rectangle with StackLayout. But i am not aware of using it with other controls.</p>
<pre><code><StackLayout Spacing="10" AbsoluteLayout.LayoutFlags="All" BackgroundColor="#0E517B" Padding="0,30,0,0">
<StackLayout.AbsoluteLayout.LayoutBounds>
<OnIdiom x:TypeArguments="Rectangle" Phone="0.5,1,1,0.80" Tablet="1,0,0.5,1" />
</StackLayout.AbsoluteLayout.LayoutBounds></StackLayout>
</code></pre>
|
<p>You can use it with virtually any property of any type of object you use in XAML.</p>
<p>Just use the right property and get the correct type of the argument it needs.</p>
<p>For instance, if you want to set the <code>Spacing</code> in a <code>Grid</code>, just do this:</p>
<pre><code><Grid VerticalOptions="FillAndExpand">
<Grid.ColumnSpacing>
<OnIdiom x:TypeArguments="x:Double"
Phone="20"
Tablet="40"/>
</Grid.ColumnSpacing>
<Grid.RowSpacing>
<OnIdiom x:TypeArguments="x:Double"
Phone="10"
Tablet="20"/>
</Grid.RowSpacing>
<Grid.Padding>
<OnIdiom x:TypeArguments="Thickness"
Phone="10, 10, 10, 0"
Tablet="20, 20, 20, 0"/>
</Grid.Padding>
<!-- Grid Content -->
</Grid>
</code></pre>
<p>The things to note here is that we set the <code>ColumnSpacing</code> by adding a child node to the <code>Grid</code> and as a child of that we use the <code>OnIdiom</code>. If you would want to do something different for a platform there is also the <a href="https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/essential_xaml_syntax/" rel="nofollow">OnPlatform</a>.</p>
<p>The only thing you need to figure out is what the <code>x:TypeArguments</code> has to be. This is the type of object that you are trying to assign as a value. In the case above, you would have to check what the type of <code>Grid.ColumnSpacing</code> is, which is a <code>Double</code>.</p>
<p>For more on this check <a href="https://blog.xamarin.com/bringing-xamarin-forms-apps-to-tablets/" rel="nofollow">this blog post</a> by James Montemagno.</p>
|
if (isset) to hide an element until it is set <p>I am attempting to hide an image box until a file has been set within my file upload code. Right now it shows the <code>$preview</code> image box regardless if a file has been set.</p>
<p>What am I doing wrong?</p>
<pre><code><form action="" method="POST" enctype="multipart/form-data">
Change your profile picture <br><input type="file" name="file" class="inputbarfile" onchange="readURL(this);">
<?php
$preview_file = '<input type="file" name="file" class="inputbarfile" onchange="readURL(this);">';
$preview = '<img width="300px" height="200px" id="file" src="#" alt="your image">';
if (empty($preview_file)) {
'';
} else {
echo $preview;
} ?>
<input type="submit" name="create" value="Upload">
</form>
</code></pre>
|
<p>If you want to do it with PHP only, your code should look like below ( except the security for $_POST htmlstrips, escapes):</p>
<pre><code><?php if (isset($_POST['file'])):?>
<?php $file = $_POST['file']; //#SECURE You should escape here ?>
File: <?php echo $file; ?>
Image: <img width="300px" height="200px" id="file" src="path/to/image/<?php echo $file ?>" alt="your image" />
<?php endif; ?>
<form action="#" method="POST" enctype="multipart/form-data">
Change your profile picture <br>
<input type="file" name="file" class="inputbarfile" onchange="readURL(this);" />
<input type="submit" name="create" value="Upload" />
</form>
</code></pre>
|
EF - Cannot apply operator '==' to operands of type 'TId' and 'TId' <p>I have this generic class, which uses Entity Framework 6.x.</p>
<pre><code>public class GenericRepository<TEntity, TId> where TEntity, class, IIdentifyable<TId>
{
public virtual TEntity GetById(TId id)
{
using (var context = new DbContext())
{
var dbSet = context.Set<TEntity>();
var currentItem = dbSet.FirstOrDefault(x => x.Id == id);
return currentItem;
}
}
public virtual bool Exists(TId id)
{
using (var context = new DbContext())
{
var dbSet = context.Set<TEntity>();
var exists = dbSet.Any(x => x.Id == id);
return exists ;
}
}
}
</code></pre>
<p>And these interfaces:</p>
<pre><code>public interface IIdentifyable : IIdentifyable<int>
{
}
public interface IIdentifyable<out TId>
{
TId Id { get; }
}
</code></pre>
<p>And entities that looks like this:</p>
<pre><code>public class CustomerEntity : IIdentifyable<int>
{
public string Name { get; set; }
public int Id { get;set; }
}
public class ProductEntity : IIdentifyable<Guid>
{
public string Name { get; set; }
public Guid Id { get;set; }
}
</code></pre>
<p><strong>My issue is that it doesn't compile. I get this error:</strong></p>
<blockquote>
<p>Cannot apply operator '<code>==</code>' to operands of type '<code>TId</code>' and '<code>TId</code>'</p>
</blockquote>
<p>I tried to change it to <code>x => Equals(x.Id, id)</code>, but then EF cannot translate it. Any way around it?</p>
<p>I know that I can use <code>Find()</code> instead of <code>FirstOrDefault</code>. But I need this for more than the methods mentioned above. <strong>Is there any way I can let EF compare <code>TId</code> with <code>TId</code>?</strong> <code>TId</code> is currently only <code>guid</code> and <code>int</code>. I've already seen the questions below, but they don't handle the issue regarding translation to SQL.</p>
<p><a href="http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c">Can't operator == be applied to generic types in C#?</a></p>
<p><a href="http://stackoverflow.com/questions/8982645/how-to-solve-operator-cannot-be-applied-to-operands-of-type-t-and-t">How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T'</a></p>
|
<p>This is a known issue with generics which normally is handled by using <code>EqualityComparer<T>.Default</code> instead of the <code>==</code> operator. However this approach doesn't work with LINQ to Entities.</p>
<p>One way to solve it is to build the predicate dynamically using the <a href="https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression(v=vs.110).aspx" rel="nofollow"><code>Expression</code></a> class from the <code>System.Linq.Expressions</code> namespace like this:</p>
<pre><code>public class GenericRepository<TEntity, TId> where TEntity: class, IIdentifyable<TId>
{
protected static Expression<Func<TEntity, bool>> EqualsPredicate(TId id)
{
Expression<Func<TEntity, TId>> selector = x => x.Id;
Expression<Func<TId>> closure = () => id;
return Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(selector.Body, closure.Body),
selector.Parameters);
}
}
</code></pre>
<p>and use it like this:</p>
<pre><code>dbSet.FirstOrDefault(EqualsPredicate(id));
</code></pre>
<p>or </p>
<pre><code>dbSet.Any(EqualsPredicate(id));
</code></pre>
<p>etc.</p>
<p><strong>Update:</strong> Here is another way that works with EF.</p>
<p>Add the following constraint to the <code>GenericRepository</code> class</p>
<pre><code>where TId : IEquatable<TId>
</code></pre>
<p>and then use <code>Equals</code> method</p>
<pre><code>x => x.Id.Equals(id);
</code></pre>
|
npm install and deprecated warnings <p>I've started to use npm recently and sometimes during installations some warnings pop up.</p>
<p>For example, running</p>
<pre><code> npm install gulp-chimp --save-dev
</code></pre>
<p>yields the following warnings</p>
<blockquote>
<p>npm WARN deprecated to-iso-string@0.0.2: to-iso-string has been deprecated, use @segment/to-iso-string instead.</p>
<p>npm WARN deprecated jade@0.26.3: Jade has been renamed to pug, please install the latest version of pug instead of jade</p>
<p>npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue</p>
<p>npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing Set-Cookie <a href="https://nodesecurity.io/advisories/130" rel="nofollow">https://nodesecurity.io/advisories/130</a></p>
</blockquote>
<p>My question is not specific to gulp-chimp but to npm in general. Should I try to update these packages or not? I understand it's the developer's call to use the updated package or not and I feel like I may break something by trying to update the packages myself but I'm also anxious about letting vulnerabilities be.</p>
|
<p>To ensure that updating the dependencies doesn't break anything, version control is a must. Often you can update the deprecated dependencies without much trouble, but there are definitely times where doing so will cause breakage in the package using it. </p>
<p>What I don't recommend doing is ignoring the deprecation errors. While it's true that the package maintainer needs to update it on their end, the problem is still very much yours. Many of these outdated packages have known security vulnerabilities that are now going to be impacting your application.</p>
<p>To get a solid picture of which dependencies are outdated, run something like:</p>
<p><code>npm outdated -depth=3</code></p>
<p>It defaults to a depth of <code>0</code> which will only check top-level dependencies, so increasing the depth level to some extent (3 is just an example) will reveal many more dependencies that are out of date. </p>
<p>The more important thing, as you already noted, is finding out which of these dependencies may have known vulnerabilities. You can test for these vulnerabilities using a tool like <a href="https://snyk.io/" rel="nofollow">Snyk</a>, which checks your dependencies against an <a href="https://snyk.io/vuln" rel="nofollow">open-source database of vulnerabilities</a>. Snyk will let you patch your vulnerabilities (using either a CLI or automated Github pull requests) without upgrading, in the case that those upgrades break your code.</p>
<p><em>Full disclosure: I work at Snyk. :) That being said this is exactly the problem it's meant to help with.</em></p>
|
the query is not using an index despite the columns joined are of the same type <p>The following query is taking too long and as the execution plan suggests it is scanning over a million rows on SPC and not using an index. I would like to understand if there is way to either use the index or modify the query to avoid searching through that amount of data. </p>
<pre><code>mysql> explain extended select *
-> from (((((((`raw`.`HUB_PA` `HP`
-> left
-> join `raw`.`SAT_TABLE1` `SPD` on(((`HP`.`P_HA` = `SPD`.`P_HA`) and (`SPD`.`ENDS_ON` = str_to_date('31/12/9999','%d/%m/%Y')))))
-> join `raw`.`LINK_TABLE1` `LPR` on((`LPR`.`P_HA` = `HP`.`P_HA`))) join `raw`.`PA_ROLE` `HR` on(((`LPR`.`PA_ROLE_HA` = `HR`.`P_ROLE_HASH`) and (`HR`.`PARTY_ROLE` = 'CUSTOMER'))))
-> join `raw`.`LINK_TABLE2` `LPC` on((`LPC`.`P_HA` = `HP`.`P_HA`))) join `raw`.`H_LOC` `HL` on((`HL`.`LOC_HA` = `LPC`.`LOC_HA`)))
-> join `raw`.`SAT_TABLE2` `SPC` on(((`SPC`.`PCH` = `LPC`.`PCH`) and (`SPC`.`ENDS_ON` = str_to_date('31/12/9999','%d/%m/%Y')))))
-> join `raw`.`SAT_TABLE3` `SPA` on((`SPA`.`LOC_HA` = `LPC`.`LOC_HA`)));
+----+-------------+-------+------------+--------+-------------------------------------+-------------------+---------+-----------------+---------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+--------+-------------------------------------+-------------------+---------+-----------------+---------+----------+----------------------------------------------------+
| 1 | SIMPLE | HR | NULL | ALL | PRIMARY | NULL | NULL | NULL | 7 | 14.29 | Using where |
| 1 | SIMPLE | SPC | NULL | ALL | PRIMARY,SAT_CONTACT_INDEX | NULL | NULL | NULL | 1318796 | 10.00 | Using where; Using join buffer (Block Nested Loop) |
| 1 | SIMPLE | LPC | NULL | eq_ref | PRIMARY,LINK_CP_INDEX,LINK_PC_INDEX | PRIMARY | 32 | raw.SPC.PCH | 1 | 100.00 | Using where |
| 1 | SIMPLE | HL | NULL | eq_ref | PRIMARY | PRIMARY | 32 | raw.LPC.LOC_HA | 1 | 100.00 | NULL |
| 1 | SIMPLE | SPA | NULL | ref | PRIMARY,SAT_ADDRESS_INDEX | SAT_ADDRESS_INDEX | 32 | raw.LPC.LOC_HA | 1 | 100.00 | NULL |
| 1 | SIMPLE | HP | NULL | eq_ref | PRIMARY | PRIMARY | 32 | raw.LPC.P_HA | 1 | 100.00 | NULL |
| 1 | SIMPLE | SPD | NULL | ref | PRIMARY,SAT_DETAILS_INDEX | PRIMARY | 32 | raw.LPC.P_HA | 1 | 100.00 | Using where |
| 1 | SIMPLE | LPR | NULL | ref | LINK_ROLE_INDEX | LINK_ROLE_INDEX | 33 | raw.LPC.P_HA | 1 | 10.00 | Using where |
+----+-------------+-------+------------+--------+-------------------------------------+-------------------+---------+-----------------+---------+----------+----------------------------------------------------+
8 rows in set, 2 warnings (0.02 sec)
| SAT_TABLE2 | CREATE TABLE `SAT_TABLE2` (
`CANCEL_FROM_MAILING` int(11) DEFAULT NULL,
`CDC_HPC` char(32) DEFAULT NULL,
`STARTS_FROM` datetime DEFAULT NULL,
`ENDS_ON` datetime DEFAULT NULL,
`LOAD_DATETIME` datetime NOT NULL,
`PCH` char(32) NOT NULL,
`SOURCE_SYSTEM` int(11) DEFAULT NULL,
PRIMARY KEY (`PCH`,`LOAD_DATETIME`),
KEY `SAT_CONTACT_INDEX` (`PCH`),
KEY `SAT_CONTACT_CDC_INDEX` (`CDC_HASH_PARTY_CONTACT`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
| PA_ROLE| CREATE TABLE `HUB_PARTY_ROLE` (
`LOAD_DATETIME` datetime DEFAULT NULL,
`PA_ROLE_HA` char(32) NOT NULL,
`PARTY_ROLE` varchar(50) DEFAULT NULL,
`SOURCE_SYSTEM` int(11) DEFAULT NULL,
PRIMARY KEY (`PARTY_ROLE_HASH`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
</code></pre>
|
<p>You dont have index for <code>SPC</code>.<code>ENDS_ON</code> </p>
<p>You should create a composite index for <code>SAT_TABLE2( PCH, ENDS_ON)</code></p>
|
Mark as unseen on Gmail (imaplib) <p>I'm trying to mark email as unseen on Gmail server.</p>
<p>I'm using this command:</p>
<pre><code>res, data = mailbox.uid('STORE', uid, '-FLAGS', '(\Seen)')
</code></pre>
<p>Everything goes OK but when I check it using web browser it's still marked as seen.
When I check flags here's what I got:</p>
<pre><code> b'46 (FLAGS (-FLAGS \\Seen))'
</code></pre>
<p>I've seen multiple questions on this issue but none of the proposed solutions work. </p>
<p>Just to mention that I'm appending this email using:</p>
<pre><code>mailbox.append(db_email.folder, "-FLAGS \Seen", time.mktime(db_email.date.timetuple()), mail.as_bytes())
</code></pre>
<p>But the flag parameter <code>-FLAGS \Seen</code> does not have any effect since it's the same when I don't pass flag argument.</p>
<p>Also, I've double-checked <code>uid</code> for given mail folder and it matches to appropriate email.</p>
|
<p>It appears you've misunderstood flags on APPEND a bit.</p>
<p>By doing <code>APPEND folder (-FLAGS \Seen) ...</code> you've actually created a message with two flags: The standard <code>\Seen</code> flag, and a nonstandard <code>-FLAGS</code> flag.</p>
<p>To create a message without the \Seen flag, just use <code>()</code> as your flag list for <code>APPEND</code>.</p>
<p><code>-FLAGS</code> is a subcommand to STORE, saying to remove these flags from the current list. Conversely, <code>+FLAGS</code> is add these flags to the current list. The plain <code>FLAGS</code> overwrites the current list.</p>
<p>Also, if you do remove the <code>\Seen</code> flag over an IMAP connection, it can take sometime to show up in the GMail WebUI. You may need to refresh or switch folders to get the changes to render.</p>
<p>NB: You are not protecting your backslashes. <code>\S</code> is not a legal escape sequence, so will be passed through, but you should either use a double backslash (<code>'\\Seen'</code>) or a raw string (<code>r'\Seen'</code>)</p>
|
When we use "left" property in an animate function in jquery, does it mean offset().left or position().left? <p>Here is it manipulating the <code>$("#mydiv").position().left</code> or <code>$("#mydiv").offset().left</code>?</p>
<pre><code>$("#mydiv").animate({"left":"-100"},1000,"swing");
</code></pre>
|
<p><strong>Neither.</strong></p>
<p>You are simply animating the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/left" rel="nofollow"><code>left</code></a> property of the element. The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/position" rel="nofollow"><code>position</code></a> of the element and it's parents sets how that property's value is used, if it is used at all.</p>
|
Angular directive without timeout service does not work <p>In angularJS, I have written a directive to display data. This data is fetched by a http service from remote database.</p>
<p>If I apply below <em>timeout</em> service in code, then result is displayed on the html page as http service returns in one second.</p>
<pre><code>$timeout(function () {
$scope.treeRoot = $scope.$eval('serviceResult') || {};
}, 1000);
</code></pre>
<p>If i do not use timeout service, then page does not show any data because $scope.treeRoot is empty e.g.</p>
<pre><code>$scope.treeRoot = $scope.$eval('serviceResult') || {};
</code></pre>
<p>In production, the http service can take time more than one second to return, is there any generic solution.</p>
|
<p>You should use Angular's <a href="https://docs.angularjs.org/api/ng/service/$q" rel="nofollow">promises</a> or <a href="https://docs.angularjs.org/api/ng/service/$http" rel="nofollow">$http</a> service which allows to return a promise.</p>
<p>After the promise, e.g. $http request, is resolved, you can populate <code>$scope.treeRoot</code> with the results.</p>
<p>Let me know if that helps.</p>
|
TSQL trigger instead of insert <p>I need to replace, after an insert in a certain table, one of the column value if it match with a banned value.</p>
<p>example:</p>
<pre><code>INSERT INTO [dbo].[TEST_A]
([COL_A]
,[COL_B])
VALUES
('TEST'
,'TEST1')
</code></pre>
<p>TEST1 is a banned value and I want to replace it in 'BANNED'.</p>
<p>This is the trigger I wrote but it seems to working properly well:</p>
<pre><code>CREATE TRIGGER [dbo].[TEST_NAME_INS] ON [dbo].[TEST_A]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO TEST_A
(COL_A
,COL_B)
SELECT
COL_A
,REPLACE(COL_B, 'TEST1', 'BANNED')
FROM inserted
WHERE INSERTED.COL_B IN ('TEST1')
</code></pre>
<p>The error is that if I insert a different value in COL_B no rows are inserted.</p>
<p>Can you give me a solution?</p>
<p>thanks in advance</p>
|
<p>If you have more values than you want to put in a case statement, you can try using a table to store the banned words and the replacement for them. Then join to that in the insert, something like:</p>
<pre><code>CREATE TRIGGER [dbo].[TEST_NAME_INS] ON [dbo].[TEST_A]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO TEST_A
(COL_A
,COL_B)
SELECT
COL_A
,CASE WHEN b.banned is null then i.col_b
ELSE b.replacement
END
FROM inserted i
LEFT JOIN Banned b on i.col_B = b.banned
</code></pre>
|
Autorefactor with intellij <p>Itellij keeps refactoring my code which is like this:</p>
<p>MY CODE</p>
<pre><code> public void setOwner(Owner owner) {
this.owner = owner;
}
</code></pre>
<p>into something like this: </p>
<p>AFTER DEFAULT REFACTOR:</p>
<pre><code>public void setOwner(Owner owner) {this.owner = owner;}
</code></pre>
<p>and I do not want that, where is the function responsible for that?</p>
|
<p>By default IntelliJ is set to "fold" or "collapse" certain types of code for example, one-line methods.</p>
<p>If you want to change it, open Preference & go to Editor -> General -> Code Folding and un-select some or all the options.</p>
|
Sendgrid Unsub For Only Specified Group <p>I am using sendgrid unsub api's for who does not want the campaign e-mails.</p>
<p>But when I send request for unsub the email, the adress goes to global unsub list. </p>
<p>Here is my php code</p>
<pre><code>$parameters = array(
"api_user" => self::EMAIL_USER_NAME,
"api_key" => self::EMAIL_PASSWORD,
"email" => $email,
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
$json_response = curl_exec($curl);
</code></pre>
<p>How to specify an unsub group id for api call?</p>
|
<p>It looks like you're using the V2 API right now. Unsub groups are only available via the V3 API, using the <a href="https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html#-POST" rel="nofollow">suppressions endpoint</a>.</p>
<p>In V3, you POST addresses to the resource URL of the unsub group, for example, <code>https://api.sendgrid.com/v3/asm/groups/:group_id/suppressions</code></p>
<p>Keep in mind that to use V3 you'll need to use the <a href="https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html" rel="nofollow">updated authentication schema</a> that uses an <code>Authorization</code> header and a real API key.</p>
|
Python cprofiler a function <p>How to profile one function with cprofiler?</p>
<pre><code>label = process_one(signature)
</code></pre>
<p>become</p>
<pre><code>import cProfile
label = cProfile.run(process_one(signature))
</code></pre>
<p>but it didn't work :/</p>
|
<p>according to documentation (<a href="https://docs.python.org/2/library/profile.html" rel="nofollow">https://docs.python.org/2/library/profile.html</a>) it should be <code>cProfile.run('process_one(signature)')</code></p>
<p>also, look at the answer <a href="http://stackoverflow.com/a/17259420/1966790">http://stackoverflow.com/a/17259420/1966790</a></p>
|
Error saving a file on server <p>I am generating a Key and i need to record on server. When i tried locally, it Works ! The problem is when i try on the server...
The archive is generated but when ON THE SERVER the download finish,but i cannot open and cannot save. I don´t get an error...but i just cannot save...</p>
<p>The code:</p>
<pre><code> string fileNamePrivate = @"pasta1/archive.txt";
Directory.CreateDirectory(Path.GetDirectoryName(fileNamePrivate));
StreamWriter textWriterPriv = new StreamWriter(fileNamePrivate, true);
var pemWriter = new PemWriter(textWriterPriv);
pemWriter.WriteObject(keyPair.Private);
pemWriter.Writer.Flush();
textWriterPriv.Close();
</code></pre>
|
<p>Try to use </p>
<pre><code>string fileNamePrivate = "~/PASTA1/archive.txt";
Directory.CreateDirectory(Path.GetDirectoryName(HostingEnvironment.MapPath(fileNamePrivate)));
StreamWriter textWriterPriv = new StreamWriter(fileNamePrivate, false);
</code></pre>
<p>How is a Server you have to use HostingEnvironment.MapPath and set "false" instead "true" on StreamWriter if you need to overwrite.</p>
|
MsgViewer (Java) won't open .msg files - Batch file solution? <p>I've just downloaded MsgViewer from here:
<a href="https://sourceforge.net/projects/msgviewer/" rel="nofollow">https://sourceforge.net/projects/msgviewer/</a></p>
<p>I need it to be the default program for opening .msg files.
It required Java JRE so I've installed the 64bit JRE on my 64bit Win2012R2 server. </p>
<p>Running MSGViewer.jar from the install folder and dragging/dropping a .msg file into it works just fine, so I created a file association between .msg and MSGViewer.jar. BUT now when I double-click a .msg file I get the dreaded blue bar error 'This app can't run on your PC' - despite it working fine when run manually. </p>
<p>I've been advised to create a batch file to handle this but after a lot of head scratching I can't work out how to do this successfully. Can anyone show me how to create a batch file that opens when a .msg file is clicked and opens that file in C:\Program Files (x86)\MSGViewer-1.9\MSGViewer.jar ?</p>
<p>I've created a batch file containing:
Java -jar MSGViewer.jar</p>
<p>And associated .msg files to it. Now clicking a .msg file opens MSGViewer but it opens blank and doesn't display the message. Any ideas of which command line options I could use to display the clicked msg file within MSGViewer when it opens? </p>
|
<p>Worked it out!</p>
<p>*.msg associated to batch file containing: </p>
<p>Java -jar MSGViewer.jar %1</p>
<p>"%1" being the magical answer. </p>
|
Bootstrap dataTable not sorting and searching in php table <p>I'm a site that has one controller page to run the mysql query. It outputs the results to a viewer page named <code>m_analitica.php</code>, with <code>include("header.php")</code> at top and <code>include("footer")</code> at the bottom. </p>
<p>code for <code>m_analitica.php</code> : </p>
<pre><code><div>
<table class="table table-striped table-bordered table-hover" id="myTable">
<div><h2>Mapa AnalÃtica</h2></div>
<thead>
<tr>
<th>Name</th>
<th>Tipo Documento</th>
<th>Número</th>
<th>Cliente</th>
<th>Obra</th>
<th>Designação</th>
<th>Agregado</th>
<th>Quantidade (ton)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Tipo Documento</th>
<th>Número</th>
<th>Cliente</th>
<th>Obra</th>
<th>Designação</th>
<th>Agregado</th>
<th>Quantidade (ton)</th>
</tr>
</tfoot>
<?php foreach ($positions as $position): ?>
<tbody>
<tr>
<td><?= $position["data"] ?></td>
<td><?= $position["tipo"] ?></td>
<td><?= $position["num"] ?></td>
<td><?= $position["cliente"] ?></td>
<td><?= $position["obra"] ?></td>
<td><?= $position["nome_obra"] ?></td>
<td><?= $position["agr"] ?></td>
<td><?= $position["ton"] ?></td>
</tr>
</tbody>
<?php endforeach ?>
</table>
</code></pre>
<p></p>
<p>In the <em>head</em> of <code>header.php</code> I included the following js scripts and CSS:</p>
<pre><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="../public/js/DataTables-1.10.12/media/css/dataTables.bootstrap.min.css" />
<link href="../public/css/bootstrap.min.css" rel="stylesheet"/>
<script src="../public/js/bootstrap.min.js"></script>
<script src="../public/js/DataTables-1.10.12/media/js/jquery.dataTables.min.js"></script>
<script src="../public/js/DataTables-1.10.12/media/js/dataTables.bootstrap.min.js"></script>
</code></pre>
<p>Then before body element closure in <code>footer.php</code> I inserted the script:</p>
<pre><code><script type="text/javascript">
$('#myTable').dataTable();
</script>
</code></pre>
<p>I get the formatting right, except it does not divide the table into pages, and the search and sorting are not working, it does nothing by clicking them.</p>
<p>Does the bootstrap dataTable not work with php? Or with foreach loops? Or his there something wrong with the code.</p>
|
<p>Remove the <code><tbody></code> tags from inside your loop. You only want to repeat the <code><tr></code> tags. Put the <code><tbody></code> tags outside of the loop.</p>
|
How to use nested loops <p>I'm learning php and I'm stuck with one task.. </p>
<p>I'm currently looping through an array holding sub arrays which looks like this:</p>
<pre><code>$data[1]["First"] = "Iva";
$data[1]["Last"] = "IviÄ";
$data[1]["Date"] = "2016-09-29";
$data[1]["Paid"] = "Yes";
$data[2]["First"] = "Petar";
$data[2]["Last"] = "PeriÄ";
$data[2]["Date"] = "2016-02-08";
$data[2]["Paid"] = "No";
$data[3]["First"] = "Tomo";
$data[3]["Last"] = "TomiÄ";
$data[3]["Date"] = "2015-08-22";
$data[3]["Paid"] = "Yes";
</code></pre>
<p>I need to echo HTML table from this Array. On the value ['Paid'], html table should output select field and showing current value as selected.
Also, first column of the table should assign #ID number. </p>
<p>So far, I've managed to create the table, but I cannot get the select field working on the Paid using Yes/No.</p>
<pre><code><table border="1" align="center" width="80%">
<tr bgcolor="yellow">
<th>ID #</th>
<th>First</th>
<th>Last</th>
<th>Date</th>
<th>Paid</th>
</tr>
<?php
foreach ( $data as $info )
{
// date transform
$date = explode('-', $info['Date']);
//var_dump($date);
echo '<tr align="center" bgcolor="#f6f6f6">';
echo ' <td>' '</td>';// How to count #IDs starting from 1?
echo '<td>'. $info['First'] .'</td>';
echo '<td>'. $info['Last'] .'</td>';
echo '<td>'. $date[2].'.'.$date[1].'.'.$date[0].'.</td>';
//echo '<td>'. $info['Paid'] .'</td>';
echo '<td>';
echo '<select name="Paid">';
echo '<option value="0" selected>'. $info['Paid'] .'</option>';
echo '<option value="1">'. $info['Paid'] .'</option>';//This is where I'm stuck
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
?>
</code></pre>
<p>Can anyone help me solve this issue?</p>
|
<p>There are plenty of loops you can use to achieve this, the easiest case here is the <code>foreach()</code> loop.</p>
<pre><code><!-- conditional loops -->
<?php foreach($data as $single): ?>
<!-- shorthand PHP statement to echo the result -->
<td> <?= $single['First']; ?> </td>
<?php endforeach; ?>
</code></pre>
<p><strong>Note</strong> - Array index's start at 0, not 1. So the first value would be <code>$data[0]['First']</code></p>
<p>If you're creating tables for each array inside it, you can use <em>nested loops</em> like this:</p>
<pre><code><?php for($i = 0; $i <= count($data); $i++):
foreach($data[$i] as $key => $val): ?>
<td>
<!-- ternary expression -->
<tr> <?= ($key == "First") ? $val : ""; ?> </tr>
</td>
<?php endforeach;
endfor;
</code></pre>
<p>If you prefer a different approach, you can use <code>while()</code> loops to achieve the same idea:</p>
<pre><code><?php $i = 0;
while($i != count($data)): ?>
<tr> <?= $data[$i++]['First']; ?> </tr>
<?php endwhile;
</code></pre>
<p><strong>Note for future</strong> - It's a lot easier working with bool datatypes rather than 'yes', 'no' strings. For example:</p>
<pre><code>$paid = true;
echo ($paid) ? 'selected' : '';
</code></pre>
<p>rather than something like:</p>
<pre><code>echo ($paid == 'No') ? '' : 'selected';
</code></pre>
|
Filtering Elasticsearch Results - Nest <p>I currently want to write a query that matches 'name', from a class called entity, then filters out the results where a guid field (stored as a string in ES) is compared to a list of string guids. If the guid stored in the Elasticsearch record matches any in the list of guids then return those results.</p>
<p>The code I have written to do this is:</p>
<pre><code> ISearchResponse<Entity> oResponse = null;
oResponse = _client.Search<Entity>(s => s
.Size(oReq.returnValue)
.Query(qr => qr
.Bool(b => b
.Filter(flt => flt.Terms(tms => tms.Field(fd => fd.extentUid).Terms<string>(oReq.extentUids.ToList())))
.Should(sh => sh
.Match(mt => mt.Field(fl => fl.name.ToLower()).Query(oReq.name.ToLower())))))
.Sort(srt => srt.Descending(SortSpecialField.Score)));
</code></pre>
<p>The following code returns 0 results when I know for certain that a lot of the Elasticsearch records have a guid that matches one in the list. Can someone help?</p>
<p>Note: In the code I filter the records first but I have tried putting that after the .Should() and I've tried using the .PostFilter().</p>
<p>Thanks in advance,</p>
<p>Gary </p>
|
<p>I would check your mapping and make sure your guid field is not analyzed. As shown in elastic search's <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/_finding_exact_values.html#_term_query_with_text" rel="nofollow">Finding Exact Values</a>, if the field is analyzed, each group separated by a <code>-</code> will be considered a different token. A <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html" rel="nofollow">terms query</a> says that it </p>
<blockquote>
<p>Filters documents that have fields that match any of the provided terms (not analyzed).</p>
</blockquote>
<p>This means that it will not analyze the strings you provide it and query those non-analyzed strings on the specified field. If your field is analyzed, you will not get any matches.</p>
<p>As a side note, unless it is specified in your mapping, your <code>name</code> field <em>is</em> probably analyzed by default. You shouldn't have to use <code>.ToLower()</code> in your match query, since <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html" rel="nofollow">match queries</a> will use the default search analyzer on your queried string. </p>
|
Error: [ng:areq] Argument 'employerCtrl' is not a function, got undefined <p>I have one arguments undefined but i don't understand why.
If I put my controller in app.js folder but everything works as I intend to create a good structure nothing works.</p>
<p>structure:</p>
<pre><code>index
app
app.js
components
home
views
job_offers.html
controller
employer_controller.js
</code></pre>
<p>My controller:</p>
<pre><code>var app = angular.module('myApp.employerCtrl', []);
app.controller("employerCtrl", ["$scope", function($scope) {
$scope.title = "Fronteend Software Engineer";
$scope.company = "Bee Engineering";
$scope.city = "Lisbon";
$scope.schedule = "Full-time";
$scope.date = "17-10-2016";
console.log($scope.city,$scope.title);
}]);
</code></pre>
<p>App.js</p>
<pre><code>var app = angular.module('myApp', ["ngRoute"]);
app.config(function($routeProvider){
$routeProvider
.when("/",{
templateUrl: "app/components/home/views/job_offers.html",
controller: "employerCtrl"
})
.when("/job" , {
templateUrl: "app/components/job/views/job.html",
controller: "job"
})
.when("/formation" , {
templateUrl: "app/components/formation/views/formation.html",
controller: "formation"
})
.when("/news" , {
templateUrl: "app/components/news/views/news.html",
controller: "news"
})
.otherwise({
redirectTo: '/login'
})
});
</code></pre>
<p>html</p>
<pre><code><html lang="en" data-ng-app="myApp" >
<!-- About Section -->
<section id="slide" class="about-section" >
<div class="container">
<div class="row content" ng-view>
</div>
</div>
</section>
</code></pre>
|
<p>You dont have to declare the module for the controller again,</p>
<pre><code>//remove this line
var app = angular.module('myApp.employerCtrl', []);
app.controller("employerCtrl", ["$scope", function($scope) {
$scope.title = "Fronteend Software Engineer";
$scope.company = "Bee Engineering";
$scope.city = "Lisbon";
$scope.schedule = "Full-time";
$scope.date = "17-10-2016";
console.log($scope.city,$scope.title);
}]);
</code></pre>
|
How to union two ordered queries in the same table <p>I have events table with columns
'title',
'description',
'start_date',
'end_date'.</p>
<p>I want to get ordered list live and future events, depends on 'start_date' and 'end_date'. </p>
<p>I try </p>
<pre><code>(
select *
from `events`
where `start_date` < NOW() and `end_date` > NOW()
order by `start_date` desc
)
union all
(
select *
from `events`
where `start_date` > NOW()
order by `start_date` desc)
</code></pre>
<p>but result have not that ordering which I want. I want at first ordered list by start_date live events after that ordered list by start_date future events.</p>
|
<p>I think you do not need union in this one.
Just put a <code>OR</code> condition in your basic query.</p>
<p>Then, to split the result into <code>"this one is live"</code> and <code>"this one is future"</code> you can use a flag</p>
<pre><code>SELECT *, start_date < NOW() AS flag
FROM `events`
WHERE (`start_date` < NOW() and `end_date` > NOW())
OR `start_date` > NOW()
ORDER BY flag DESC, start_date
</code></pre>
<p>Nota : the <code>DESC</code> is here to show you you want live before future event. Otherwise just put <code>ASC</code>.</p>
|
How to differentiate color scheme <p>I would like to change color scheme <code>Eiffel</code> so that the keyword <code>class</code> in java files will be different color than keyword <code>int</code>? If I change <code>Storage</code> in Eiffel, both keywords change the color.</p>
|
<p>You need to find out the exact scopes of <code>class</code> and <code>int</code>. The <a href="https://packagecontrol.io/packages/PackageResourceViewer" rel="nofollow">PackageResourceViewer</a> is a great way to open files inside <code>.sublime-package</code> files.</p>
<p>Once installed, launch *âPackageResourceViewer: Open Resource<code>, open the Java package and look for the syntax files (e.g.</code>Java.sublime-syntax`).</p>
<p>I'm not familiar enough with Java, but it looks to me like <code>class</code> uses the scope <code>meta.class</code> and <code>int</code> uses <code>storage.type.primitive.array</code>. That means, that in your theme you would at least have to change <code>meta</code> or <code>storage</code>. Needless to say that you can be more specific than that.</p>
|
How do I find out how many times each character of a string 's' repeats itself <p>I have searched and found some similar questions, but just can't seem to figure out how to apply them to my problem. Please bear with me, as this is my first post on the site.</p>
<p>I have to find out how many times a character of a string repeats itself. For example, if given <code>"launch at noon"</code>, the method should print:</p>
<pre><code>"l" appears once in "launch at noon".
"a" appears twice in "launch at noon".
"u" appears once in " launch at noon ".
"n" appears 3 times in "launch at noon".
"c" appears once in "launch at noon".
"h" appears once in "launch at noon".
" " appears twice in "launch at noon".
"t" appears once in "launch at noon".
"o" appears twice in "launch at noon".
</code></pre>
|
<pre><code>public void test() {
// The string to test.
String s = "launch at noon";
// Count them.
Map<Character, Integer> characterCounts = countCharacters(s);
// Print the results.
for (Map.Entry<Character, Integer> e : characterCounts.entrySet()) {
int count = e.getValue();
// Work out the name for the number.
String number = count < specials.length
// The special short ones.
? specials[count]
// Is it a general one?
: count < numbersAsWords.length
// Yes
? numbersAsWords[count] + " times"
// Way too many.
: "too many times";
// Print it.
System.out.println("\"" + e.getKey() + "\" appears " + number + " in \"" + s + "\".");
}
}
private Map<Character, Integer> countCharacters(String s) {
// Map from character in string to count of occurrences.
Map<Character, Integer> counts = new HashMap<>();
// Walk the string.
for (int i = 0; i < s.length(); i++) {
// Get character at that point.
char ch = s.charAt(i);
// What's in the map for that character.
Integer count = counts.get(ch);
if (count == null) {
// Not seen this character before - start at zero.
count = 0;
}
// Increment seen count.
count += 1;
// Put it back in the map.
counts.put(ch, count);
}
return counts;
}
// The short ones.
private static final String[] specials = {"not at all", "once", "twice"};
// The rest.
private static final String[] numbersAsWords = {"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
"twenty-one",
"twenty-two",
"twenty-three",
"twenty-four",
"twenty-five",
"twenty-six",
"twenty-seven",
"twenty-eight",
"twenty-nine",
"thirty",
"thirty-one",
"thirty-two",
"thirty-three",
"thirty-four",
"thirty-five",
"thirty-six",
"thirty-seven",
"thirty-eight",
"thirty-nine",
"forty",
"forty-one",
"forty-two",
"forty-three",
"forty-four",
"forty-five",
"forty-six",
"forty-seven",
"forty-eight",
"forty-nine",
"fifty",
"fifty-one",
"fifty-two",
"fifty-three",
"fifty-four",
"fifty-five",
"fifty-six",
"fifty-seven",
"fifty-eight",
"fifty-nine",
"sixty",
"sixty-one",
"sixty-two",
"sixty-three",
"sixty-four",
"sixty-five",
"sixty-six",
"sixty-seven",
"sixty-eight",
"sixty-nine",
"seventy",
"seventy-one",
"seventy-two",
"seventy-three",
"seventy-four",
"seventy-five",
"seventy-six",
"seventy-seven",
"seventy-eight",
"seventy-nine",
"eighty",
"eighty-one",
"eighty-two",
"eighty-three",
"eighty-four",
"eighty-five",
"eighty-six",
"eighty-seven",
"eighty-eight",
"eighty-nine",
"ninety",
"ninety-one",
"ninety-two",
"ninety-three",
"ninety-four",
"ninety-five",
"ninety-six",
"ninety-seven",
"ninety-eight",
"ninety-nine",
"one hundred",
};
</code></pre>
|
Storing multiple outputs from each iteration of a for loops in R <p>I can't find a solution to this problem:</p>
<p>Given a fix path and a very limited directories from year. I'm trying to obtain each combination of path between this initial combination (<em>fixPath - year</em>) and the different, <strong>non-fixed and non-equally quantity</strong>, subdirectories contained in each combination of <em>fixPath - year</em></p>
<pre><code>fixPath <- "C:/Users/calcazar/Desktop/example"
year <- 2008:2010
pathVector <- paste(fixPath, year, sep = "/")
pathVector
[1] "C:/Users/calcazar/Desktop/example/2008" "C:/Users/calcazar/Desktop/example/2009"
[3] "C:/Users/calcazar/Desktop/example/2010"
</code></pre>
<p>My approach to solve this problem is use a for-loop:</p>
<ol>
<li>Set the working directory with <code>setwd(pathVector[1])</code></li>
<li>Scan the files (the subdirectories) with <code>list.files</code>in that working directory and obtain each combination with: <code>paste(pathVector[1], list.files(pathVector[1]), sep = "/")</code></li>
<li>Store this combinations in a vector and proceed with the next iteration</li>
</ol>
<p>...but <strong>from each iteration of the loop I have a bunch of combinations and I can't figure out how to store more than one for each iteration</strong>. Here is my code:</p>
<pre><code>for (i in seq_along(pathVector)) {
setwd(pathVector[i])
# here I only obtain the combination of the last iteration
# and if I use pathFinal[i] I only obtain the first combination of each iteration
pathFinal <- paste(pathVector[i], list.files(pathVector[i]), sep = "/")
# print give me all the combinations
print(pathFinal[i])
}
</code></pre>
<p>So, <strong>how can store multiple values (combinations) from each iteration in a for loop?</strong></p>
<p>I want a vector that contain all the combinations, for example:</p>
<pre><code> "C:/Users/calcazar/Desktop/example/2008/a"
"C:/Users/calcazar/Desktop/example/2008/z"
"C:/Users/calcazar/Desktop/example/2009/b"
"C:/Users/calcazar/Desktop/example/2009/z"
"C:/Users/calcazar/Desktop/example/2009/y"
"C:/Users/calcazar/Desktop/example/2010/u"
</code></pre>
<p>Thx!</p>
|
<p>You might try to set up a vector beforehand and then use this part in your for loop:</p>
<pre><code>append(VectorName, pathFinal[i])
</code></pre>
<p>you might try to include it in your existing code like this</p>
<pre><code>pathFinal <- append(pathFinal, paste(pathVector[i], list.files(pathVector[i]), sep = "/"))
</code></pre>
<p>I haven't checked it, but it should add each new value to your desired vector. Also, I don't think you need to use <code>setwd()</code>.</p>
|
HSQL Trigger generates SQL Error: -458, SQLState: S1000 / java.lang.ArrayIndexOutOfBoundsException <p>I have an HSQL version of an Oracle database schema to perform unit tests.</p>
<p>I need to update a column on update with current timestamp.</p>
<p>The trigger I have implemented is loaded without complaint by the hsql engine, but it crashes at runtime when I try to update rows.</p>
<p>Here is a sample test case that you can run in a project configured with spring and junit:</p>
<pre><code>public class UtSqlTriggerTest {
@Test public void testTrigger() throws SQLException {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new InMemoryResource(
"CREATE TABLE TEST (ID NUMERIC NOT NULL PRIMARY KEY,DATA VARCHAR(200), LAST_UPDATE TIMESTAMP);\n" +
"CREATE TRIGGER updTimestamp AFTER UPDATE OF DATA ON TEST\n" +
"REFERENCING NEW AS newrow OLD AS oldrow\n" +
"FOR EACH ROW\n" +
"SET newrow.LAST_UPDATE = current_timestamp;"));
Connection connection = DriverManager.getConnection("jdbc:hsqldb:file:/opt/db/testdb;shutdown=true", "SA", "");
resourceDatabasePopulator.populate(connection);
JdbcTemplate tjdbc = new JdbcTemplate(new SingleConnectionDataSource(connection, true));
tjdbc.update("INSERT INTO TEST(ID, DATA) VALUES (0, 'HELLO')");
tjdbc.update("UPDATE TEST SET DATA = 'HELLO WORLD' WHERE ID = 0");
tjdbc.queryForObject("SELECT LAST_UPDATE FROM TEST WHERE ID = 0", Date.class);
}
}
</code></pre>
<p>What's wrong with this trigger ? Why it generated ArrayIndexOutOfBoundException ?</p>
<pre><code>CREATE TRIGGER updateDateAjoutFichier AFTER UPDATE OF DATA ON TEST
REFERENCING NEW AS newrow OLD AS oldrow
FOR EACH ROW
SET newrow.LAST_UPDATE = current_timestamp;
</code></pre>
|
<p>When you run the CREATE TRIGGER in a SQL client you will see the following error message:</p>
<blockquote>
<p>attempt to assign to non-updatable column: LAST_UPDATE [SQL State=0U000, DB Errorcode=-2500]</p>
</blockquote>
<p>This is because you are trying to modify a column in an <code>AFTER</code> trigger. Changing column values is only possible in a <code>BEFORE</code> trigger. So you should use:</p>
<pre><code>CREATE TRIGGER updTimestamp <b><i>BEFORE</i></b> UPDATE OF DATA ON TEST
REFERENCING NEW AS newrow OLD AS oldrow
FOR EACH ROW
SET newrow.LAST_UPDATE = current_timestamp;</code></pre>
|
Android - ActionBar Up button not visible when using TextView as ToolBar title <p>I have added a <code>Toolbar</code> on top of all of my activities. But I wanted the title to be in the centre, so as per some suggestions on SO, I created a <code>TextView</code> inside the <code>Toolbar</code>and I was able to put it in the centre.<br>
Now, when I am trying to add an <strong>Up Action</strong> following this guide <a href="https://developer.android.com/training/appbar/up-action.html" rel="nofollow">Adding an Up Action | Android Developers</a>, I do not get any UpButton.<br>
Is this because of using a <code>TextView</code> inside of the <code>Toolbar</code> ? Because I read on SO that the Toolbar is basically a <code>View</code> and can be configured just like any other <code>View</code>, so I don't get why this should be a problem.</p>
<ol>
<li><code>If that is the reason, and I'd have to use the default</code>android:title="My Title"<code>attribute in for the</code>Toolbar` , is there any other way to put it in the centre ?</li>
<li>What is the workaround for this problem so that I can get an Up Action as well as the toolbar title in the centre ? </li>
</ol>
<p>Thanks for any help you'd be able to provide.</p>
<p><em>XML Layout</em> </p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_width="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/lifeline_toolbar"
android:elevation="4dp"
android:background="@android:color/background_dark"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
<TextView
android:layout_gravity="center_horizontal"
android:text="Lifeline"
android:textStyle="bold"
android:textSize="18sp"
android:id="@+id/lifeline_toolbar_title"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.Toolbar>
<LinearLayout>
</LinearLayout>
<LinearLayout>
</LinearLayout>
</LinearLayout>
</code></pre>
<p><em>Java Code</em></p>
<pre><code>public class ll_home extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ll_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.lifeline_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
</code></pre>
|
<p>You need to set the getSupportActionBar().setHomeButtonEnabled(true); enable the Up Action button</p>
<pre><code>Toolbar toolbar = (Toolbar) findViewById(R.id.lifeline_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
</code></pre>
|
cURL returns response but unable to get the same response when tried to access using selenium firefox webdriver <p>I am trying to extract some data from a website from Linux server using Selenium.</p>
<p>When the URL is pinged through cURL, we are able to see the response from the server but when the same URL requested through Selenium Firefox webdriver, we aren't recieving any response for hours.</p>
<p>For eg:- One of the link we are trying to reach is as follows : </p>
<p><a href="http://www.vudu.com/movies/#!content/776990" rel="nofollow">http://www.vudu.com/movies/#!content/776990</a></p>
<p>Can you point out to a possible issue?</p>
<p>Is it common for websites to react this way?</p>
<p>What might be the way to overcome this issue ?</p>
<p>Thanks in advance for help .</p>
<p><strong>NOTE:-</strong> The websites we are trying to ping , are already whitelisted in the server.</p>
|
<p>The server might be responding differently based upon you User Agent string. Many extensions allow you to set this, including "User-Agent Switcher for Chrome."</p>
<p>You might also experiment with the Selenium <code>chromedriver</code> and look to see exactly what the request is inside the browser. You can find this by using the "network" tab of the developer tools:</p>
<p><a href="https://i.stack.imgur.com/CfP5D.png" rel="nofollow"><img src="https://i.stack.imgur.com/CfP5D.png" alt="enter image description here"></a></p>
|
could someone tell me what is wrong with this? <p>Question: wow, you are given two things:</p>
<p>The calling order in which all the processes are called.
The ideal order in which all the processes should have been executed.
Now, let us demonstrate this by an example. Let's say that there are 3 processes, the calling order of the processes is: 3 - 2 - 1. The ideal order is: 1 - 3 - 2, i.e., process number 3 will only be executed after process number 1 has been completed; process number 2 will only be executed after process number 3 has been executed.</p>
<ol>
<li><p>Iteration #1:
Since the ideal order has process #1 to be executed firstly, the calling ordered is changed, i.e., the first element has to be pushed to the last place. Changing the position of the element takes 1 unit of time. The new calling order is: 2 - 1 - 3. Time taken in step #1: 1.</p></li>
<li><p>Iteration #2: Since the ideal order has process #1 to be executed firstly, the calling ordered has to be changed again, i.e., the first element has to be pushed to the last place. The new calling order is: 1 - 3 - 2. Time taken in step #2: 1.</p></li>
<li><p>Iteration #3: Since the first element of the calling order is same as the ideal order, that process will be executed. And it will be thus popped out. Time taken in step #3: 1.</p></li>
<li><p>Iteration #4: Since the new first element of the calling order is same as the ideal order, that process will be executed. Time taken in step #4: 1.</p></li>
<li><p>Iteration #5: Since the last element of the calling order is same as the ideal order, that process will be executed. Time taken in step #5: 1.</p></li>
</ol>
<p>Total time taken: 5 units.
S: Executing a process takes 1 unit of time. Changing the position takes 1 unit of time.</p>
<p><strong>Input format:</strong>
The first line a number N, denoting the number of processes. The second line contains the calling order of the processes. The third line contains the ideal order of the processes.</p>
<p><strong>Output format:</strong>
Print the total time taken for the entire queue of processes to be executed.</p>
<p>Constraints: 1<=N<=100</p>
<p>SAMPLE INPUT </p>
<pre><code>3
3 2 1
1 3 2
</code></pre>
<p>SAMPLE OUTPUT </p>
<pre><code>5
</code></pre>
<p>The first method that came to me was to declare a variable and increase it by one after every swap plus 2, but then if we take an array of size 3, there are only two possibilities. Hence I printed those out, and yes guys this is a problem from an online judge, there was no syntax error, but in the site it tells that there was some problem in declaration, I have no clue what to do I am new to programming and can someone suggest a new method which is applicable for arrays of bigger sizes. </p>
<pre><code>#include <stdio.h>
swap(a,b);
long long int a,b;
int main(void) {
long long int n,i;
long long int a[3],b[3];
scanf("%d",&n);
for(i=0;i<=2;i++)
{
scanf("%d",a[i]);
}
for(i=0;i<=2;i++)
{
scanf("%d",&b[i]);
}
if(a[i]=b[i])
{
printf("2");
}
while(a[i]!=b[i])
{
swap(b[0],b[2]);
swap(b[0],b[1]);
{
if(a[i]=b[i])
printf("5");
}
}
return 0;
}
swap(a,b){
long long int temp;
a=temp;
b=a;
temp=b;
return swap(a,b);
}
</code></pre>
|
<p>Your <code>swap()</code> function has multiple issues:</p>
<p>1: It calls itself with <code>return swap(a,b);</code> in the last line of the function. This will result in infinite recursion and a stack overflow.</p>
<p>2: You need to declare the return type of the function. If it takes two <code>long long</code> parameters and returns nothing, then it should be declared as follows:</p>
<pre><code>void swap(long long a, long long b);
</code></pre>
<p>3: As written, the function will have no effect anyway. You need to pass <em>pointers</em> to these variables if you want to change their values:</p>
<pre><code>long long swap(long long *a, long long *b);
</code></pre>
<p>4: To pass pointers to this function, prefix the parameters with <code>&</code> as follows:</p>
<pre><code>swap(&b[0],&b[2]); /* NOT: swap(b[0],b[2]); */
</code></pre>
<p>5: The order of operations in the <code>swap()</code> function is also wrong. You start by irretrievably losing the value of <code>a</code> instead of storing it so that it can be assigned to <code>b</code>. Try this instead:</p>
<pre><code>void swap(long long *a, long long *b) {
long long temp;
temp = *a;
*a = *b;
*b = temp;
}
</code></pre>
<hr>
<p><strong>NOTE:</strong> Please learn how to format your code properly. Also, always compile your development code with warnings enabled (e.g., add <code>-Wall -pedantic</code> to the command line). Doing so would have drawn your attention to most if not all of these problems without having to ask here.</p>
|
c# how do you swap horizontal and diagonal <p>for example, given matrix like this:</p>
<pre><code>1 2 3
4 5 6
7 8 9
</code></pre>
<p>and it will be </p>
<pre><code>1 5 9
4 2 6
7 8 3
</code></pre>
<p>and i found matrix that horizontal and diagonal but i can't swap those
can you guys help me get a code in C# for this?</p>
|
<p>While the first answer does work, this solution will account for cases where the dimension lengths are not 100% known. It will use the smallest dimension length as the for loop end point.</p>
<pre><code>int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 }, {13, 14, 15} };
int numDims = arr.Rank;
int min = 0;
for (int i = 0; i < numDims; i++)
{
int current = arr.GetUpperBound(i) + 1;
if (current < min || min == 0)
{
min = current;
}
}
for (int i = 1; i < min; i++)
{
var tmp = arr[0, i];
arr[0, i] = arr[i, i];
arr[i, i] = tmp;
}
</code></pre>
<p>Additionally, if you, the OP, had left your attempt posted, I could've explained why this is better.</p>
|
Javascript object value from string path <p>I have an object:</p>
<pre><code>var obj= {
hello:{
it:"ciao",
en:"hello"
}
}
</code></pre>
<p>Now the problem is that i can't access a value through <code>obj.hello[lang]</code>, neither <code>obj.hello.en</code>.</p>
<p>i have a <strong>string</strong> like 'hello.it' or 'hello.en' and I want to get something like obj[myString] that became obj.hello.en</p>
<p>I tried to split the string with <code>.split('.')</code>, but i have to loop hard coded through the length result </p>
<p>How can i achieve this?</p>
|
<p>I don't understand... obj.hello.it should work</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj= {
hello:{
it:"ciao",
en:"hello"
}
}
console.log(obj.hello.it);</code></pre>
</div>
</div>
</p>
<p>If you need to get this value from a string 'hello.it' I would do something like that :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj= {
hello:{
it:"ciao",
en:"hello"
}
}
var helloIt = 'hello.it';
var helloEn = 'hello.en';
function translate(s){
var values = s.split('.');
var resource = values[0];
var lang = values[1];
return obj[resource][lang];
}
console.log(translate(helloIt));
console.log(translate(helloEn));</code></pre>
</div>
</div>
</p>
<p>After that you have to manage some cases (if the string has not the right format, if the translation does not exist...). You could manage that everything in a translation module or something... Hope it helps ;)</p>
<p>EDIT :</p>
<p>If you want to have a way to 'explore' objects using a string you can do something like that :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj= {
hello:{
it:"ciao",
en:"hello"
}
};
function explore(o, s){
return s.split('.').reduce(function(r, ss){
return r && r[ss] ? r[ss] : null;
}, o);
}
console.log(explore(obj, 'hello.it'))</code></pre>
</div>
</div>
</p>
|
Reading files with hdfs3 fails <p>I am trying to read a file on HDFS with Python using the hdfs3 module. </p>
<pre><code>import hdfs3
hdfs = hdfs3.HDFileSystem(host='xxx.xxx.com', port=12345)
hdfs.ls('/projects/samplecsv/part-r-00000')
</code></pre>
<p>This produces</p>
<pre><code>[{'block_size': 134345348,
'group': 'supergroup',
'kind': 'file',
'last_access': 1473453452,
'last_mod': 1473454723,
'name': '/projects/samplecsv/part-r-00000/',
'owner': 'dr',
'permissions': 420,
'replication': 3,
'size': 98765631}]
</code></pre>
<p>So it seems to be able to access the HDFS and read the directory structure. However, reading the file fails.</p>
<pre><code>with hdfs.open('/projects/samplecsv/part-r-00000', 'rb') as f:
print(f.read(100))
</code></pre>
<p>gives</p>
<pre><code>---------------------------------------------------------------------------
OSError Traceback (most recent call last)
.
.<snipped>
.
OSError: [Errno Read file /projects/samplecsv/part-r-00000 Failed:] 1
</code></pre>
<p>What could be the issue? I am using Python3.5.</p>
|
<p>if You want any operation on files then you have to pass full File path .</p>
<pre><code>import hdfs3
hdfs = hdfs3.HDFileSystem(host='xxx.xxx.com', port=12345)
hdfs.ls('/projects/samplecsv/part-r-00000')
#you have to add file to location
hdfs.put('local-file.txt', '/projects/samplecsv/part-r-00000')
with hdfs.open('projects/samplecsv/part-r-00000/local-file.txt', 'rb') as f:
print(f.read(100))
</code></pre>
|
Adding foreign key fails unless data is first removed and reinserted after <p>I have an odd issue with foreign keys. I am trying to perform the following query:</p>
<pre><code>ALTER TABLE [GroupMember] FOREIGN KEY ([Group]) REFERENCES [Group]([GUID])
</code></pre>
<p>Which gives me the following error:</p>
<blockquote>
<blockquote>
<p>The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__GroupMember__Group__0D25C822". The conflict occurred in database "x", table "dbo.Group", column 'GUID'.</p>
</blockquote>
</blockquote>
<p>I then verified the existing things, which I have confirmed are all ok:</p>
<ul>
<li>Referenced table (dbo.Group) has a defined PRIMARY KEY on [GUID] column</li>
<li>Referencing table (dbo.GroupMember) has no [Group]-values which do not exist in [GUID]-column of dbo.Group-table</li>
<li>No similarly referencing foreign keys exist already</li>
</ul>
<p>From here on, I experimented. Taking some rows in and out, wiping the table, truncating the table. What I can conclude so far:</p>
<ul>
<li>If I wipe the referencing table using <code>DELETE FROM [GroupMember];</code> then try to apply the FK constraint, I receive the same error message</li>
<li>If I truncate the referencing table using <code>TRUNCATE TABLE [GroupMember];</code>, I can apply the FK constraint without errors. Additionally, I am able to reinsert the exact same data after applying the FK constraint, without problems. </li>
</ul>
<p>From this I can conclude that the data itself is not the problem. Can anyone make sense of this? Why am I able to apply the constraint after truncating the table, but not after deleting all records?</p>
|
<p>If you are using Microsoft SSMS check whether unchecking "Prevent saving changes that require table re-creation" solves the problem. You'll find this in Options > Designers > Table and Database Designers.</p>
<p>I have had similar issues that have been resolved by this. Let me know if it works or not.</p>
<p>Good luck.</p>
|
How to get title attribute of element and insert it after element using jquery? <p>I have a list with list elements like this...</p>
<pre><code><li class="first leaf">
<a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
</li>
</code></pre>
<p>And I wand to take the title attribute and append it as a div after the like this...</p>
<pre><code><li class="first leaf">
<a href="/admin/store/orders/view" title="View and process the orders.">View orders</a>
<div>View and process the orders.</div>
</li>
</code></pre>
<p>So far, I am here...</p>
<pre><code>(function ($) {
$('#block-menu-menu-admin-welcome li a').each(function () {
$(this).append('<div>' + $(this).attr('title') + '</div>');
});
})(jQuery);
</code></pre>
<p>But it isnt working. Can anyone help?</p>
|
<p>Your first this in your loop is a reference to the anchor. You have to comb out of that to its parent element and append to that.</p>
<pre><code>$(this).parent().append('<div>' + $(this).attr('title') + '</div>');
</code></pre>
|
AJAX POST returns complete PHP instead echoed string <p>i created a js function which gets called by certain action,</p>
<pre><code>var getX3DListFromServer = function()
{
var dataList;
//var post = $.post('X3DHandling.php', {postState:"getList"},
//function(data){
// dataList = data;
//});
//console.log(dataList);
//
$.ajax({
type: 'POST',
url: 'X3DHandling.php',
data: {postState:"getList"},
success: function(data){$('#result').html(data);},
error: function(){alert('getting list error')},
});
return dataList;
}
</code></pre>
<p>the php contains the following code,</p>
<pre><code><?php
echo "Working";
?>
</code></pre>
<p>I thought that the string gets pushed into the div but instead the variable <strong>data</strong> contains the complete php. It seems like the php file got not intepreted in an appropiate way.</p>
<pre><code><div id="result" class="footer"><!--?php
echo "Working";
?--></div>
</code></pre>
<p>I did everything what other people described in videos or different entries - but I don't know what I did wrong.</p>
<p>I hoped to get a result like this:</p>
<pre><code><div id="result" class="footer">
echo "Working";
</div>
</code></pre>
<p>I hope you can help me - thank you for your time.</p>
|
<p>Do Something like:</p>
<pre><code>$.ajax({
type: "POST",
url: "functions.php",
data: {
products: "products",
},
success: function (data) {
console.log("received data: " + data);
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL
</code></pre>
<p>And in the PHP:</p>
<pre><code>if (isset($_POST['products'])) {
$MyProducts = $_POST['products'];
//PHP FUNCTION CALL HERE FOR EXAMPLE
}
</code></pre>
|
Executing Sas Code in schedular <p>I use sas - exceed. I do batch submission with commands on Unix. It will be really helpful if any one can guide me on how will I schedule my task at particular day and time(Say Sunday). The steps that I used to run my query on batch mode are given below:
BATCH PROCESS:</p>
<p>Step-1: Open the unix window.</p>
<p>Step-2: Give Bash command</p>
<p>Step-3: Go to your lib: cd /sas01/saswork/apollo/shaque </p>
<p>Step-4: vi cd1_41_1.sas (Here VI is the command followed by the file name)</p>
<p>Step-5: cw (paste the entire code).</p>
<p>Copy the code from the notepad and then right click the mouse on the unix window.</p>
<p>Step-6: esc button.</p>
<p>Step-7: :wq (To write & Quit). /<em>Your file name is displayed</em>/</p>
<p>Step-8: nohup sas94 cd1_41_1 &</p>
<p>I have been looking over internet for this, but I m still not very clear. Please help me out here.</p>
<p>Thanks</p>
|
<p>Unless you have a separate utility for scheduling, the default scheduler in Unix is <code>cron</code>. I would be cautious about using it, however, if your level of understanding of unix is not very high; it is somewhat difficult to use correctly.</p>
<p>You can read one of many papers on scheduling SAS jobs on Unix, like <a href="http://support.sas.com/resources/papers/proceedings11/057-2011.pdf" rel="nofollow">Some Tricks to get the best out of SAS and Unix</a>, to get all of the details; the short list of details is that you need to have a shell script (.sh) that contains the instructions to do what you want it to do (in this case, what you would have typed into the command line - at minimum, the <code>sas</code> call in step 8, and usually instructions to change directory to the appropriate directory for saving logs), and then you need to edit <code>crontab</code> to instruct the scheduler (<code>cron</code>) to execute that shell script at a particular time/day.</p>
|
find repeated element in list of list python <p>I have been struggling with this problem for two days and I need help with it. I need to find repeated element in a list of lists
<code>list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)]</code> where "a" and "b" elements are integers and "c" elements are floats.</p>
<p>So if for example <code>a1 == a2</code> or <code>a1 == bn</code>, I need to create a new list with the entire list elements and I need to iterate this for all the lists (a, b, c) in the list of lists. To put it another way, I need all lists that have elements that are present in more than one list. I need to compare only "a" and "b" elements but obtain the associated value "c" in the final list.</p>
<p>For example:</p>
<pre><code>list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]
desired_result=[(1, 2, 4.99), (1, 4, 3.00), (5, 1, 1.12)]
</code></pre>
<p>I try many ideas...but nothing nice came up:</p>
<pre><code>MI_network = [] #repeated elements list
genesis = list(complete_net) #clon to work on
genesis_next = list(genesis) #clon to remove elements in iterations
genesis_next.remove(genesis_next[0])
while genesis_next != []:
for x in genesis:
if x[0] in genesis_next and x[1] not in genesis_next:
MI_network.append(x)
if x[0] not in genesis_next and x[1] in genesis_next:
MI_network.append(x)
genesis_next.remove(genesis_next[0])
</code></pre>
|
<p>You can count occurrences of specific list elements and take lists with counts > 1. Something like this, using <code>collections.defaultdict()</code>:</p>
<pre><code>>>> from collections import defaultdict
>>> count = defaultdict(int)
>>> for lst in list_of_list:
... count[lst[0]] += 1
... count[lst[1]] += 1
...
>>> [lst for lst in list_of_list if count[lst[0]] > 1 or count[lst[1]] > 1]
[(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)]
</code></pre>
|
Ionic Serve: Displays code only for a split second <p>My code is only shown for a split second after returning ionic serve and goes blank. I've everything needed to run this like nodejs, cordova, ionic, jdk, etc.
I'm new to ionic and would appreciate if someone can help me solve this.
This was run on internet explorer.</p>
<p><a href="https://i.stack.imgur.com/82fqw.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/82fqw.jpg" alt="enter image description here"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>-->
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<h1>asdf</h1>
<!--
The nav bar that will be updated as we navigate between views.
-->
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<!--
The views will be rendered in the <ion-nav-view> directive below
Templates are in the /templates folder (but you could also
have templates inline in this html file if you'd like).
-->
<ion-nav-view></ion-nav-view>
</body>
</html></code></pre>
</div>
</div>
</p>
|
<p>really you are very lost.
if you try to show </p>
<pre><code><h1>asdf</h1>
</code></pre>
<p>well that disappear because is replaced by the angular app in your code</p>
<pre><code> <!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</code></pre>
<p>you do write your in angularjs for that you can check the docs of <a href="https://docs.angularjs.org/guide" rel="nofollow">angular</a> and <a href="http://ionicframework.com/docs/" rel="nofollow">ionic</a>.</p>
<p>you can retire the class of body and write direct in index but that is the really bad way </p>
|
angularjs http get from json url <p>I have problem with this code I have json data from my asp.net web api. I could not get this data by angularjs. as you can see the the code;</p>
<pre><code><!DOCTYPE html>
<html ng-app="myapp">
<head>
<title ng-bind="helloAngular"></title>
<script src="~/Scripts/angular.min.js"></script>
<script>
var myapp = angular.module('myapp', []);
myapp.controller('myController', function ($scope, $htpp){
$htpp.get({
method:'GET',
url:'http://localhost:50972/api/product'})
.success(function (response) {
$scope.result = response.statusText
});
});
</script>
</head>
<body ng-controller="myController">
<table border="1">
<tr ng-repeat="product in response">
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.type}}</td>
</tr>
</table>
</body>
</html>
</code></pre>
|
<p>You have some typo errors: instead of <code>$htpp</code> use <code>$http</code></p>
<pre><code>myapp.controller('myController', function ($scope, $http){
$http.get({
method:'GET',
url:'http://localhost:50972/api/product'})
.success(function (response) {
$scope.result = response.data;
});
});
</code></pre>
|
Why is my app not showing data, being fetched in JSON from an API, using retrofit, in recyclerview in android? <p>Before anything, let me tell you that I'm a beginner in android development. I've been developing a music streaming app, which fetches data in JSON from an API. I'm using
retrofit2 as HTTP client and GSON library for JSON parsing. </p>
<p>So I was working on an API method to get TopArtist info. And followings are the classes and layout:</p>
<p>MainActicity.java: This is the main activity</p>
<pre><code>package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import com.example.myapplication.APIServices.API_Service;
import com.example.myapplication.Models.Artist;
import com.example.myapplication.Models.LastAPIRecyclerViewAdapter;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
public static final String API_Url = "http://ws.audioscrobbler.com/2.0/";
public static final String API_Key = "//my API-key";
@Bind(R.id.recyclerView)
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
StaggeredGridLayoutManager mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mStaggeredGridLayoutManager);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_Url)
.addConverterFactory(GsonConverterFactory.create())
.build();
API_Service api_service = retrofit.create(API_Service.class);
Call<List<Artist>> call = api_service.getTopArtist();
call.enqueue(new Callback<List<Artist>>() {
@Override
public void onResponse(Response<List<Artist>> response, Retrofit retrofit)
{
List<Artist> artist = response.body();
Log.d("Artist", "onResponse: " + response.code());
LastAPIRecyclerViewAdapter lastAPIRecyclerViewAdapter = new LastAPIRecyclerViewAdapter(artist);
recyclerView.setAdapter(lastAPIRecyclerViewAdapter);
}
@Override
public void onFailure(Throwable t)
{
Log.d("Artist", "onFailure: " + t.getMessage());
}
});
}
}
</code></pre>
<p>APIService.java:</p>
<pre><code>import com.example.myapplication.MainActivity;
import com.example.myapplication.Models.Artist;
import java.util.List;
import retrofit.Call;
import retrofit.http.GET;
public interface API_Service {
@GET("?method=tag.gettoptracks&tag=pop&api_key=" + MainActivity.API_Key + "&format=json")
Call<List<Artist>> getTopArtist();
}
</code></pre>
<p>Artist.java: This is the Model/POJO Class which is going to store all the data fetched from API's GET request.</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@Generated("org.jsonschema2pojo")
public class Artist {
@SerializedName("name")
@Expose
private String name;
@SerializedName("mbid")
@Expose
private String mbid;
@SerializedName("url")
@Expose
private String url;
@SerializedName("streamable")
@Expose
private String streamable;
@SerializedName("image")
@Expose
private List<Image> image = new ArrayList<Image>();
@SerializedName("@attr")
@Expose
private Attr attr;
/**
*
* @return
* The name
*/
public String getName() {
return name;
}
/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return
* The mbid
*/
public String getMbid() {
return mbid;
}
/**
*
* @param mbid
* The mbid
*/
public void setMbid(String mbid) {
this.mbid = mbid;
}
/**
*
* @return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* @param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* @return
* The streamable
*/
public String getStreamable() {
return streamable;
}
/**
*
* @param streamable
* The streamable
*/
public void setStreamable(String streamable) {
this.streamable = streamable;
}
/**
*
* @return
* The image
*/
public List<Image> getImage() {
return image;
}
/**
*
* @param image
* The image
*/
public void setImage(List<Image> image) {
this.image = image;
}
/**
*
* @return
* The attr
*/
public Attr getAttr() {
return attr;
}
/**
*
* @param attr
* The @attr
*/
public void setAttr(Attr attr) {
this.attr = attr;
}
}
</code></pre>
<p>LastAPIRecyclerViewAdapter.java: </p>
<pre><code>import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myapplication.R;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class LastAPIRecyclerViewAdapter extends RecyclerView.Adapter<LastAPIRecyclerViewAdapter.LastAPIRecyclerViewHolder>{
private List<Artist> artists;
public LastAPIRecyclerViewAdapter(List<Artist> _artist) {
this.artists = _artist;
}
@Override
public LastAPIRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View viewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_cardview, parent, false);
return new LastAPIRecyclerViewHolder(viewItem);
}
@Override
public void onBindViewHolder(LastAPIRecyclerViewHolder holder, int position) {
holder.title.setText(artists.get(position).getName());
}
@Override
public int getItemCount() {
return 0;
}
class LastAPIRecyclerViewHolder extends RecyclerView.ViewHolder{
@Bind(R.id.cardView)
CardView cardView;
@Bind(R.id.textView)
TextView title;
@Bind(R.id.imageView)
ImageView image;
LastAPIRecyclerViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
</code></pre>
<p>custom_cardview.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cardView"
app:cardElevation="2dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:contentDescription="ImageView of the Recycler View" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />
</android.support.v7.widget.CardView>
</LinearLayout>
</code></pre>
<p>activity_main:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/recyclerView">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</code></pre>
<p>So whenever I run this application, it doesn't show me any view. Just a blank activity. Where did I go wrong?</p>
|
<p>Need to update this to return the length of the list </p>
<pre><code>@Override
public int getItemCount() {
return 0;
}
</code></pre>
<p>As far as I can tell, everything else looks okay </p>
|
Return elastic search result as raw JSON <p>Sorry for duplicated question, but this does not seem to work with current Elastic Search 2.x version. Basically, I use NEST to send query to ES and would like to get response as plain JSON, just like using POST command on Sense. Similar problem exists here: <a href="http://stackoverflow.com/questions/20751970/returning-raw-json-in-elasticsearch-nest-query">Returning Raw Json in ElasticSearch NEST query</a></p>
<p>Results retrieved using:</p>
<pre><code>var searchResult = _elasticClient.LowLevel.Search<SearchResponse<SearchResult>>(querytEST);
</code></pre>
<p>Result wanted:</p>
<pre><code>{
"took": 406,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 14,
"max_score": 0,
"hits": []
},
"aggregations": {
"query": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 1,
"buckets": [
{
"key": "laura",
"doc_count": 14,
"top": {
"hits": {
"total": 14,
"max_score": 4.1078563,
"hits": [
{...
</code></pre>
|
<p>The type <code>T</code> passed to <code>.Search<T></code> on the low level client specifies the return type of the result. In order to get json returned, you simply need to change this to <code>string</code></p>
<pre><code>var searchResult = _elasticClient.LowLevel.Search<string>(querytEST);
</code></pre>
|
How to model REST api for authentication service that services two "apps"? <p>I'm building a solution that serves the sell and consuming side of the market which will require two apps. I will be building it on aws lambda with a microservice architecture.</p>
<p>There is alot of shared logic / model between the two. So, I'm trying to figure out the api designs to do that.</p>
<p>I'm stuck in trying to decide if it would make more sense to pass in the client type as a param or put it as a resource.</p>
<p><a href="http://api.example.com/v1/users?client=seller" rel="nofollow">http://api.example.com/v1/users?client=seller</a></p>
<p>or</p>
<p><a href="http://api.example.com/v1/client/seller/users" rel="nofollow">http://api.example.com/v1/client/seller/users</a></p>
|
<p>There are no hard and fast rules, it depends on the set of use-cases and how open a particular design is for future enhancements.</p>
<ol>
<li>Using a URL param follows the REST semantics literally, as <code>seller</code> is not necessarily a sub-resource of <code>users</code>, but more of a filter on the type. But validation and extensibility is a pain, since the value of <code>client</code> is now free-form and the application has to enforce the constraints. These constraints have to be modified and documented whenever you are making future changes.</li>
<li>Using a sub-resource path makes the API more intuitive. Though theoretically not a sub-resource, nested paths are easier to read and maintain. Any new <code>client</code> additions in the future would make the documentation fairly evident, since the path gives away the type.</li>
</ol>
<p>I would prefer option #2 with the sub-resource pattern primarily because it is more user-friendly.</p>
<blockquote>
<blockquote>
<p>There is alot of shared logic / model between the two</p>
</blockquote>
</blockquote>
<p>You could have this in both the options with the same shared model. This is an implementation concern and it shouldn't govern your design IMHO.</p>
|
Excel.exe has triggered a breakpoint <p>my vs 2015 recently showed some strange behaviour and I was wondering whether on of you around here encountered similiar problems. I am creating a xll addin with c++ and the xll Lib of Keith Lewis (xll12).</p>
<p>The code ran well, but at some point the c++ debugger pops up with a strange error message that excel.exe has triggered a breakpoint. I tried to narrow it down in my code, but nothing helped. So I commented everything out, but the debugger still sends this message. Going further the debugger asks me if he should show me the disassembly (?):
The he shows me the following line</p>
<p>DebugBreak:
000007FEFD1231F0 xchg ax,ax<br>
000007FEFD1231F2 int 3 </p>
<p>Does anyone of you have an idea?</p>
<p>Thanks in advance</p>
|
<p><code>int 3</code> is the i686 assembly instruction for a breakpoint.</p>
<p>In itself it's not particular useful but is signalling to you that something has gone awry.</p>
<p>If your xll is <em>really</em> that minimal, are you sure you're registering it correctly with Excel?</p>
|
UIButton inside UISegmentedControl action <p>I am continuing my calculation program to improve my skills in Swift code. Right now I have a problem: I want that an UISegmentedControl select the operator of my operations (+, - ecc..) and when one is selected a UIButton func calculate the values based on the decision of the UISegmentedControl.</p>
<p>Here is the code but is not working.</p>
<p>Thanks,
Matteo</p>
<pre><code>import UIKit
class ViewController: UIViewController {
@IBOutlet weak var firstNumber: UITextField!
@IBOutlet weak var secondNumber: UITextField!
@IBOutlet weak var resultButton: UIButton!
@IBOutlet weak var resultNumber: UILabel!
@IBOutlet weak var operatorSelector: UISegmentedControl!
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 operatorSelectorChanged(_ sender: UISegmentedControl) {
switch operatorSelector.selectedSegmentIndex {
case 0:
@IBAction func resultFunction(_ sender: AnyObject) {
if let firstNumberConv :Int = Int(firstNumber.text!), let secondNumberConv :Int = Int(secondNumber.text!) {
let result = firstNumberConv + secondNumberConv
resultNumber.text = "\(result)"
} else { resultNumber.text = "Inserire solo valori numerici"}
}
case 1:
@IBAction func resultFunction(_ sender: AnyObject) {
if let firstNumberConv :Int = Int(firstNumber.text!), let secondNumberConv :Int = Int(secondNumber.text!) {
let result = firstNumberConv - secondNumberConv
resultNumber.text = "\(result)"
} else { resultNumber.text = "Inserire solo valori numerici"}
}
default:
break;
}
}
}
</code></pre>
|
<p>Try removing the lines with <code>@IBAction func ...</code> inside your switch cases.</p>
<p>I think your <code>@IBAction func operatorSelectorChanged</code> should look something like this:</p>
<pre><code>@IBAction func operatorSelectorChanged(_ sender: UISegmentedControl) {
switch operatorSelector.selectedSegmentIndex {
case 0:
if let firstNumberConv = Int(firstNumber.text!), let secondNumberConv = Int(secondNumber.text!) {
let result = firstNumberConv + secondNumberConv
resultNumber.text = "\(result)"
} else { resultNumber.text = "Inserire solo valori numerici"}
case 1:
if let firstNumberConv = Int(firstNumber.text!), let secondNumberConv = Int(secondNumber.text!) {
let result = firstNumberConv - secondNumberConv
resultNumber.text = "\(result)"
} else { resultNumber.text = "Inserire solo valori numerici"}
default:
break;
}
}
</code></pre>
|
How replication works <p>Lets say that I have replication on master Solr server configured like this:</p>
<pre><code><lst name="master">
<str name="enable">true</str>
<str name="replicateAfter">optimize</str>
<str name="confFiles">solrconfig.xml,schema.xml,stopwords.txt,synonyms.xml</str>
<str name="commitReserveDuration">00:00:10</str>
</lst>
</code></pre>
<p>and slave configured like this:</p>
<pre><code><lst name="slave">
<str name="enable">true</str>
<str name="masterUrl">masterSolr</str>
<str name="pollInterval">24:00:00</str>
</lst>
</code></pre>
<ol>
<li>How slave knows that optimization was performed on master (master know nothing about slaves)?</li>
<li>Does slave checks it every 24 hours (not more often)?</li>
<li>Will replication be performed if there was no optimization but some several commits (on master)?</li>
<li>How to reach a state where slave will do the replication ONLY after optimization (nothing else) and will do it shortly after this optimization (we don't want to wait several hours)? </li>
</ol>
|
<p>the replication is a pull mechanism - so to be able to support your scenario you need to do a bit of configuration.</p>
<p>For you questions:<br>
1. it does not - it pulls in intervals (or forced) from master which tells what version is ready to be replicated<br>
2. yes - 24 hours<br>
3. only if an optimize have been done since the last index fetch<br>
4. some configuration and knowledge from master to slave is needed.<br>
You can use the postOptimize update event on the updatehandler to force a repication on slaves</p>
<pre><code><listener event="postOptimize" class="solr.RunExecutableListener">
<str name="exe">wget</str>
<str name="dir">solr/bin</str>
<bool name="wait">true</bool>
<arr name="args"> <str> http://slave_host:port/solr/core?/replication?command=fetchindex</str> </arr>
</listener>
</code></pre>
<p>you can then remove the poll interval from the slave config. you need to add multiple args (in str tags) for each slave </p>
|
Get Azure Sql serve port in ARM <p>I am using an ARM template to get an azure sql server name but I looking for a way to also get the port (1433) instead of providing a hardcoded value.</p>
<p>My ARM code:
<code>
[concat(reference(resourceId('Microsoft.SQL/servers/', parameters('database_server_name'))).fullyQualifiedDomainName,':1433')]
</code></p>
|
<p>Do it the same as your database_server_name parameter:</p>
<pre><code>[concat(reference(resourceId('Microsoft.SQL/servers/', parameters('database_server_name'))).fullyQualifiedDomainName,':', parameters('port_number'))]
</code></pre>
|
C# Google Cloud Storage Get ListObjects in Folders <p>I'm storing all my application information in Google Cloud Storage. I've created a bucket and inside this bucket I've folders. With that code, I can get list of all my folders.</p>
<pre><code>public static IList<uFolder> ListFolders(string bucketName)
{
if (storageService == null)
{
CreateAuthorizedClient();
}
Objects objects = storageService.Objects.List(bucketName).Execute();
if (objects.Items != null)
{
return objects.Items.
Where(x => x.ContentType == "application/x-www-form-urlencoded;charset=UTF-8").
Select(x => new uFolder(x.Name)).ToList();
}
return null;
}
</code></pre>
<p>But actually this code, get all my files and folders in my bucket. So I need to be extract them. My first question, Is there a shortcut to this method?</p>
<p>My other and most important question is, How can I get all files just in specific folder? For example;
My bucket name is MyBucket and I want to get all files from "MyBucket/2/". How can I do this? Is this the only way check the medialink or selflink of the files?</p>
<p>Thanks for all answer. Have a good day, good works...</p>
|
<p>I think what you want is to set the <a href="https://developers.google.com/resources/api-libraries/documentation/storage/v1/csharp/latest/classGoogle_1_1Apis_1_1Storage_1_1v1_1_1ObjectsResource_1_1ListRequest.html#ab1665c7589c52755d83720ec48665d85" rel="nofollow">Delimiter</a> property of the list request to <code>/</code>. This will return a delimited result at the top level of your hierarchy.</p>
|
Bootstrap Validator to validate length of field correct syntax <p>I'm trying to validate the string's length with Bootstrap Validator. Unfortunately, the JavaScript does not work. I'm thinking maybe a syntax error.</p>
<p>HTML :</p>
<pre><code> <form id="ordertracking" role="form">
<div style="margin-bottom: 12px" class="input-group">
<span class="input-group-addon"><strong>@</strong></span>
<input id="login-username" type="text" class="form-control" name="email" placeholder="Email">
<span class="input-group-addon"><i class="glyphicon glyphicon-barcode"></i></span>
<input id="login-password" type="text" class="form-control" name="customerNum" placeholder="Customer #">
</form>
</code></pre>
<p>JS:</p>
<pre><code> $('#ordertracking').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
stringLength: {
min: 5,
max: 50,
message: 'The full email must be less than 50 characters'
}
}
},
customerNum: {
validators: {
stringLength: {
min: 4,
max: 6,
message: 'The customer number has to be 5 or 6 digits'
}
}
}
}
});
</code></pre>
<p>Link to Codepen: <a href="http://codepen.io/Delano83/pen/bwQZbB" rel="nofollow">http://codepen.io/Delano83/pen/bwQZbB</a> </p>
<p>I've been knocking my head on this for two hours so any suggestions is very appreciated. </p>
|
<p>You haven't included the Library:</p>
<p>Add this to your head section below all the other scripts and it should work. </p>
<p><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"></script></code></p>
<p>if you check the console you will see this error: </p>
<pre><code>Uncaught TypeError: $(...).bootstrapValidator is not a function
</code></pre>
<p>That made me realise the library was not being loaded correctly.</p>
|
JS Canvas, images in animation stack instead of change after every turn <p>I have been stuck on this for a few days, and can't find a solution. What I am trying to make is that after every cycle the images change, and after all images get displayed in order it starts again with the first image again. Now the problem I have is that the images on the right get stacked up. Here is the code: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas, ctx, x, y, w, e;
var brojac = 0;
var i = 0;
var images = [];
images[0] = new Image();
images[0].src = "https://www.a1smallbusinessmarketing.com/images/prosbo_hires.jpg";
images[1] = new Image();
images[1].src = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png";
images[2] = new Image();
images[2].src ="http://www.jasonjsmith.com/img/small-business-seo.jpg";
images[3] = new Image();
images[3].src ="https://g.twimg.com/business/page/image/11TwitterForSmallBusiness-300_1.png";
function start_canvas() {
function draw() {
for (i = 0; i <= brojac; i++) {
if (brojac == 4) {
brojac = 0;
i = 0;
} else {
ctx.drawImage(images[i], x, y);
}
}
};
function draw1(w, e) {
ctx.drawImage(images[i - 1], w, e);
};
function update(time) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (w >= x) {
e += 8;
y += 8;
} else {
x -= 4;
w += 4;
};
draw(x, y);
draw1(w, e);
if (e > canvas.height) {
brojac++;
x = canvas.width - 190;
y = 15;
w = 1;
e = 15;
}
requestAnimationFrame(update)
}
canvas = document.getElementById('canvas1');
x = canvas.width - 190;
y = 15;
w = 1;
e = 15;
ctx = canvas.getContext('2d');
requestAnimationFrame(update)
}
window.addEventListener("load", start_canvas);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code><style> canvas {
border: #666 2px solid;
}
</style></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas1" width="1650" height="825" style="width: 650px; height: 330px;"></canvas>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>*Due to the images I randomly found on the net, the stacking can only be seen with the last two images. How can I make them not stack?<br>
<strong>Side question</strong> If I wanted to make,lets say, images [0,1] from array only go to the middle and not drop, could I use switch statement or should I use if?<br>
Thank you in advance.</p>
|
<h2>Use (%) modulo to cycle</h2>
<p>If you want to cycle through an array of items you can use % to get the array index. % returns the remainder of a divide. ie <code>0 % 4 == 0</code>, <code>3 % 4 == 3</code>, <code>4 % 4 == 0</code>, <code>7 % 4 == 3</code></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_()" rel="nofollow">Modulo (aka remainder) operator MDN</a></p>
<p>So if you have an array of items you just create a index and use the array length to get the remainder.</p>
<pre><code> var currentIndex = 0;
// then to loop through the array
currentIndex = (currentIndex + 1) % array.length;
</code></pre>
<p>Which is very handy and saves us from having to add conditional statements for cycling through arrays and similar.</p>
<p>I rewrote your code. I draw the images in the update loop, i check if the image has loaded though the animation will still play if the image has not loaded. If you move the <code>if(images[currentImage].complete){</code> to the beginning of the update function and the closing brace to the line above <code>requestAnimationFrame...</code> the animation will not start until the image has loaded.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// image names
var imageURLS = [
"https://www.a1smallbusinessmarketing.com/images/prosbo_hires.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png",
"http://www.jasonjsmith.com/img/small-business-seo.jpg",
"https://g.twimg.com/business/page/image/11TwitterForSmallBusiness-300_1.png"
]
// load the images
var images = imageURLS.map(url=>{var img = new Image(); img.src = url; return img});
function start_canvas() {
var canvas = document.createElement('canvas');
canvas.width=1650;
canvas.height=825;
canvas.style.width = "650px"; // Note the canvas is scaled down
canvas.style.height = "330px";
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var currentImage = 0; // points to the current image being rendered
const imageStartY = 15; // constants for image start and speeds
const imageStartRight = canvas.width - 190;
const imageStartLeft = 1;
const horizontalSpeed = 4;
const verticalSpeed = 8;
var leftImg = {x : imageStartLeft,y : imageStartY}; // left and right image locations
var rightImg = {x : imageStartRight,y : imageStartY};
// main loop
function update(time) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (leftImg.x >= rightImg.x) { // check if moving down
leftImg.y += verticalSpeed;
rightImg.y += verticalSpeed;
} else { // else moving towards center
leftImg.x += horizontalSpeed;
rightImg.x -= horizontalSpeed;
};
if(images[currentImage].complete){ // make sure the current image has loaded
ctx.drawImage(images[currentImage],leftImg.x, leftImg.y); // draw both images
ctx.drawImage(images[currentImage],rightImg.x, rightImg.y);
}
if (leftImg.y > canvas.height) { // if at bottom cycle to next image and start again
currentImage = (currentImage + 1) % images.length; // loop image index % is modulo and returns the remainder
leftImg.x = imageStartLeft;
leftImg.y = imageStartY;
rightImg.x = imageStartRight;
rightImg.y = imageStartY;
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
}
window.addEventListener("load", start_canvas);</code></pre>
</div>
</div>
</p>
|
Group values conditionally in data frame in R <p>Colleagues</p>
<p>I have the following problem. My data-set looks like this:</p>
<pre><code>Article = c("A","A","A","A","B","B","B","C","C","C","C")
Value = c(1,5,2,1,20,18,5,6,3,31,99)
df = data.frame(Article, Value)
</code></pre>
<p>My goal is to match the highest Value per Article with the lowest Value per Article exhaustively (ignoring middle values), e.g. 1 with 100, 2 with 99, 3 with 98 and etc. And to assign groups for these matches.</p>
<p>The final result for this data frame has to match first row with Article "A" with second row of Article "A", because the first row Value is 1 (and it is the lowest) and second row Value is 5 (and it is the highest). For this pair the algorithm has to assign a similar group, e.g. "A_1". Then the algorithm looks what rows for Article "A" are left and repeats the assignment process - we have only two rows left so it matches them into "A_2".</p>
<p>After that the algorithm jumps into rows with Article = "B" and so on.</p>
<p>The final result has to look like this:</p>
<pre><code>Group = c("A_1","A_1", "A_2","A_2", "B_1", "B_NA", "B_1", "C_2", "C_1", "C_2", "C_1")
df = data.frame(Article, Value, Group)
</code></pre>
<p>My idea (I do not know how to code it yet) is a bit strange:</p>
<p>For N in Article I want to sort the data frame segment ascending (e.g. filter the data frame for only Article N and sort this segment ascending) and assign to first row's Group value = "N_1". Then assign the last row of the segment value = "N_1". Next filter this segment for rows that do not have an assigned value in Group variable yet and repeat the assignment for first and last value. And so on until the algorithm gives groups for all rows in a segment, then it jumps to another value in N.</p>
<p>Can somebody advices me on this problem? Thanks a lot in advance</p>
|
<p>ok so you could then do something like this:</p>
<pre><code>library(dplyr)
high_and_low <- df %>%
group_by(Article) %>%
summarise(high = max(Value),
low = min(Value))
</code></pre>
<p>which just pulls out the high and low values for each block. if you needed other info associated with the rows in which the high/low values are found then you could get that too.</p>
<p>is this getting you anywhere closer?</p>
|
How to add TextBlock text value from database object value <p>I'm working on WPF application which has one Window.xaml where I'm using dataGrid which is filled from Database (MSSQL 2008R2), In that dataGrid I'm loading orders from my Database.</p>
<p>I'm also grouping my orders by numberOfOrder, and its possible to expand them or to collapse them, in case there will be many orders at same time.</p>
<p>Anyway, inside of my expander Is DockPanel, which has textBlock there, I used that textBlock to display number of each order from database, but I am wondering how could I display something else from database into that textBlock (for example I want to display DateTime when I inserted my order into database - I've that property allready), let's keep everything grouped by Number of Order by lets display something else instead of numberOfOrder like I did until now.</p>
<p>Here is photo of how that looks right now:</p>
<p><a href="https://i.stack.imgur.com/fGhga.png" rel="nofollow"><img src="https://i.stack.imgur.com/fGhga.png" alt="enter image description here"></a></p>
<p>Order Number: #1 <- I'm displaying this in TextBlock and 1 is numberOfOrder from my database.</p>
<pre><code><TextBlock FontWeight="Normal" FontFamily="Verdana" FontSize="20" Height="25" Foreground="#83D744" Text="{Binding Path=Name,StringFormat= Number of Order:# {0}}" />
</code></pre>
<p>And what I would like to do here is to display something else instead of Order Number, as I said I would like to display DateTime maybe or whatever, so I would make it look like this:</p>
<p><a href="https://i.stack.imgur.com/XqWat.png" rel="nofollow"><img src="https://i.stack.imgur.com/XqWat.png" alt="enter image description here"></a></p>
<p>Here is full code:</p>
<p><strong>XAML: (TextBlock is important here)</strong></p>
<pre><code><DataGrid.GroupStyle>
<!-- Style for groups at top level. -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" Background="Black" Opacity="0.7">
<Expander.Header >
<DockPanel Height="50" Margin="0,0,0,0" Name="dockPanel" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=ActualWidth}">
<Button>...</Button>
<Button>...</Button>
<TextBlock FontWeight="Normal" FontFamily="Verdana" FontSize="20" Height="25" Foreground="#83D744" Text="{Binding Path=Name,StringFormat= Number of Order:# {0}}" />
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</code></pre>
<p><strong>MY CLASS WHICH IS USED TO FILL DATAGRID:</strong></p>
<pre><code>public class OrderLocal
{
public string Title { get; set; }
public int Quantity { get; set; }
public int NumberOfOrder { get; set; }
public DateTime DateOfInput { get; set; }
}
</code></pre>
<p><strong>CODE BEHIND WHERE I AM FILLING DATAGRID WILL ALL ORDERS:</strong></p>
<pre><code>public MainWindow()
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.WindowState = WindowState.Maximized;
var ordersList = OrdersController.localOrders();
collectionViewSource.Source = ordersList;
collectionViewSource.GroupDescriptions.Add(new PropertyGroupDescription("NumberOfOrder"));
DataContext = collectionViewSource;
}
</code></pre>
|
<p>Maybe you can put just another TextBlock in your DockPanel?</p>
<pre><code><DockPanel>
<Button DockPanel.Dock="Right"/>
<Button DockPanel.Dock="Right"/>
<TextBlock Text=""/>
<TextBlock Text"whatever you wan"/>
<TextBlock Text="{Binding Items, Converter={StaticResource ItemsConverter},StringFormat=\{0:d\}}"/>
</DockPanel>
</code></pre>
<p>and converter:</p>
<pre><code>public class ItemsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ReadOnlyObservableCollection<object> items = value as ReadOnlyObservableCollection<object>;
if (items == null) throw new ArgumentNullException(nameof(items));
DateTime latestOrderDate = items.Max(x => x.OrderDate);
return latestOrderDate;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>That's it. With different converted you can get different values from your items.</p>
<p>Regards</p>
<p>Steffen</p>
|
Swift 3 : Extra argument 'error' in call <p>I have tried all solutions like try catch. But not able to solve this error. Please help me out, I am new to ios.</p>
<pre><code>func apicalling () {
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "7adebcbe-18b4-d2a7-2159-2fbcaea27edd"
]
let parameters = [
"customerID": "1",
"listType": "2"
]
let postData = JSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)
var request = NSMutableURLRequest(url: NSURL(string: "http://exp.php")! as URL,
cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
</code></pre>
<p>The error in this below line :</p>
<pre><code>let postData = JSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)
</code></pre>
<p>Please help me out.</p>
<p>Thanks.</p>
|
<p>In swift 3, it will be:</p>
<pre><code>do {
let data = try JSONSerialization.data(withJSONObject: parameters, options:[])
// do your works
} catch {
print("Got error: \(error)")
}
</code></pre>
<p>The API document is here: <a href="https://developer.apple.com/reference/foundation/jsonserialization/1413636-data" rel="nofollow">https://developer.apple.com/reference/foundation/jsonserialization/1413636-data</a></p>
|
what is equivalent of "npm install --save" in yarn? <p>I am using yarn to install the dependencies,what will be the equivalent of "npm install --save " in yarn to update the entry in package json. I can use "npm install --save " here, but i want to use yarn as much as possible to improve performance & avoid confusions between npm and yarn.</p>
<p><a href="https://www.npmjs.com/package/yarn" rel="nofollow">https://www.npmjs.com/package/yarn</a> </p>
|
<p>The yarn equivalent to<code>npm install <name> --save</code> is:</p>
<pre><code>yarn add <name>
</code></pre>
<p><a href="https://yarnpkg.com/en/docs/migrating-from-npm#toc-cli-commands-comparison" rel="nofollow">Here's the link to the docs</a> for the full list of commands in comparison to <code>npm</code>.</p>
|
Why Adt plugin for eclipse doesnot work? <p>I am running windows and eclipse mars. I downloaded and installed the <a href="https://developer.android.com/studio/tools/sdk/eclipse-adt.html" rel="nofollow">ADT plugin</a> version 23.0.7. but nothing happens after I install it. I can't find the option to create a new android project. Also there is no option to convert a java project(this is actualy adt project before i uninstal and update adt) into an android project.</p>
|
<p>Open the Error Log view after installing ADT and see if there are any relevant errors reported there.</p>
<p>Also, since ADT is no longer supported, it may just be incompatible with Eclipse's Mars (and newer) releases. Try installing it into <a href="https://eclipse.org/downloads/packages/release/luna/sr2" rel="nofollow">Eclipse Luna</a>.</p>
|
Generate mapping.txt with Proguard <p>Ho to generate the mapping file with Proguard enabled ?</p>
<p>Here is my config file proguard.cfg :</p>
<pre><code>-keep class mono.MonoRuntimeProvider { *; <init>(...); }
-keep class mono.MonoPackageManager { *; <init>(...); }
-keep class mono.MonoPackageManager_Resources { *; <init>(...); }
-keep class mono.android.** { *; <init>(...); }
-keep class mono.java.** { *; <init>(...); }
-keep class mono.javax.** { *; <init>(...); }
-keep class opentk.platform.android.AndroidGameView { *; <init>(...); }
-keep class opentk.GameViewBase { *; <init>(...); }
-keep class opentk_1_0.platform.android.AndroidGameView { *; <init>(...); }
-keep class opentk_1_0.GameViewBase { *; <init>(...); }
-keep class android.runtime.** { <init>(***); }
-keep class assembly_mono_android.android.runtime.** { <init>(***); }
# hash for android.runtime and assembly_mono_android.android.runtime.
-keep class md52ce486a14f4bcd95899665e9d932190b.** { *; <init>(...); }
-keepclassmembers class md52ce486a14f4bcd95899665e9d932190b.** { *; <init>(...); }
/* some code ... */
-printmapping mapping.txt
</code></pre>
<p>I get these warnings :</p>
<pre><code>PROGUARD : warning : can't write resource [META-INF/MANIFEST.MF] (Duplicate zip entry [formsviewgroup.jar:META-INF/MANIFEST.MF])
PROGUARD : warning : can't write resource [.readme] (Duplicate zip entry [classes.jar:.readme])
PROGUARD : warning : can't write resource [.readme] (Duplicate zip entry [classes.jar:.readme])
PROGUARD : warning : can't write resource [META-INF/MANIFEST.MF] (Duplicate zip entry [classes.jar:META-INF/MANIFEST.MF])
PROGUARD : warning : can't write resource [META-INF/MANIFEST.MF] (Duplicate zip entry [classes.jar:META-INF/MANIFEST.MF])
PROGUARD : warning : can't write resource [META-INF/MANIFEST.MF] (Duplicate zip entry [classes.jar:META-INF/MANIFEST.MF])
</code></pre>
<p>More details here :
<a href="https://forums.xamarin.com/discussion/79813/generate-mapping-txt-with-proguard" rel="nofollow">https://forums.xamarin.com/discussion/79813/generate-mapping-txt-with-proguard</a></p>
|
<p><code>Xamarin.Android</code> includes a <code>-dontobfuscate</code> in it's <code>proguard_xamarin.cfg</code> and thus mapping for obfuscated Java stack traces would be turned off even if you include <code>-printmapping</code></p>
<h3><code>proguard_xamarin.cfg</code> (Xamarin.Android Version: 7.0.1.3)</h3>
<pre><code># This is Xamarin-specific (and enhanced) configuration.
-dontobfuscate
-keep class mono.MonoRuntimeProvider { *; <init>(...); }
-keep class mono.MonoPackageManager { *; <init>(...); }
-keep class mono.MonoPackageManager_Resources { *; <init>(...); }
-keep class mono.android.** { *; <init>(...); }
-keep class mono.java.** { *; <init>(...); }
-keep class mono.javax.** { *; <init>(...); }
-keep class opentk.platform.android.AndroidGameView { *; <init>(...); }
-keep class opentk.GameViewBase { *; <init>(...); }
-keep class opentk_1_0.platform.android.AndroidGameView { *; <init>(...); }
-keep class opentk_1_0.GameViewBase { *; <init>(...); }
-keep class android.runtime.** { <init>(***); }
-keep class assembly_mono_android.android.runtime.** { <init>(***); }
# hash for android.runtime and assembly_mono_android.android.runtime.
-keep class md52ce486a14f4bcd95899665e9d932190b.** { *; <init>(...); }
-keepclassmembers class md52ce486a14f4bcd95899665e9d932190b.** { *; <init>(...); }
# Android's template misses fluent setters...
-keepclassmembers class * extends android.view.View {
*** set*(***);
}
# also misses those inflated custom layout stuff from xml...
-keepclassmembers class * extends android.view.View {
<init>(android.content.Context,android.util.AttributeSet);
<init>(android.content.Context,android.util.AttributeSet,int);
}
</code></pre>
<p>FYI: Thus warning, are just that, warning. Duplicate zip entries for resources are usually harmless. If you have a need to include one duplicated resource over another, you would need to remove (or rename) the unneeded ones.</p>
|
To find the overlapping of two date ranges and merge it into one date range in JAVA <p>We have blocks with specific no. of date ranges, and require to merge the date ranges of every block which are overlapping and add their overall quantity.</p>
<p>Consider the below given input and desired output:</p>
<h2>Input:</h2>
<pre><code>Block 1 -
14/11/2016 - 17/11/2016 ===> 100
18/11/2016 - 20/11/2016 ===> 200
Block 2 -
15/11/2016 - 16/11/2016 ===> 50
17/11/2016 - 20/11/2016 ===> 300
Block 3 -
15/11/2016 - 18/11/2016 ===> 100
19/11/2016 - 20/11/2016 ===> 400
</code></pre>
<h2>Desired Output:</h2>
<pre><code>14/11/2016 ===> 100
15/11/2016 - 16/11/2016 ===> 250
17/11/2016 ===> 500
18/11/2016 ===> 600
19/11/2016 - 20/11/2016 ===> 900
</code></pre>
<p>Please could you advise if any java utility to handle this complexity.</p>
|
<p>Utility unknown, but you could compute your answers with an array of integers where the data representation of the index of the array is the offset of each day from a start point, and then you iterate over every range and increment the value of the range into the corresponding indices of the array, then when you're done, each index represents the offset date of a start date and the value is the accumulated value from the ranges in the blocks. Then if you want to have the output represented by ranges again, you can step through the content and declare start and end points of ranges based on consecutive matching values.</p>
<p><code>
set start date = day of first entry of first block
for each block
for each range
for each day of range
offset = day-of-range - start-date
array[offset] += rangeValue</code></p>
<p>Picture it like stacking timelines together, then letting them all project down into a common discrete set of holders which aggregate the value landing in each holder.</p>
<p><code>
new range(start date, start date)
range-value = array[0]
for each index in array
if array[index] == array[index-1]
range-end = startdate+index
else
new range(startdate+index, startdate+index)
range-value = array[index]
</code></p>
<p>Not accounting for index bounds at the start or error traps. It may not be the most elegant solution, but it should solve your problem.</p>
|
php urlencode returns different results when run in a class <p>I'm running PHP 5.3.3 and when using <code>$str=urlencode("£")</code>, the value of <code>$str</code> is <code>%A3</code>, as I would expect. However if I call the <code>urlencode</code> function from within a class, the value of <code>$str</code> is <code>%C2%A3</code>. </p>
<p>I've also tried passing the £ through the function <code>http_build_query</code>, but this has the same variant in result when running outside / inside of a class. I can work around this using <code>str_replace</code> to rid <code>$str</code> of the unwanted encoding but would really like to know why this is happening. It's almost as though <code>urlencode</code> is using a different character set when being called from within a class.</p>
<p>Any thoughts will be greatly appreciated!</p>
|
<p>There are very few reasons that <code>urlencode()</code> might return different values. Inside or outside the class is not the issue. We can rule that out very easily.</p>
<p>Create a file <code>test.php</code> with the following:</p>
<pre><code><?php
var_dump(urlencode("£"));
class x {
public function y() {
var_dump(urlencode("£"));
}
}
$x = new X();
$x->y();
</code></pre>
<p>The above will print the exact same in both cases.</p>
<p>It's not an issue with PHP, or the function, or where you're using the function. </p>
<p>It looks like one value was stored UTF-8 and one was stored ISO 8859-1.</p>
<p>It's likely that the values are two different values of two different encodings. Check where the values come from, how they got there, and how they're being displayed. Are all the values using the same encodings e.g. UTF-8 or ISO 8859-1. What encoding are they stored in. When they were stored did they come from the encoded source e.g. html page (was the page encoded with the same encoded as all the above). </p>
|
In Qt how to add a file with a QFileDialog in a QLineEdit <p>I have one window which has a button named "..." which open an other window which has also a button named "..." which open a QFileDialog. Next to the button of the second window, there are 10 QLineEdit to get 10 files. With the QFileDialog, I can't take a mp3 file and put his name in the first QLineEdit. How can I do ? And if the first QLineEdit is already took, how can I put the name of a mp3 file in the second QLineEdit ?</p>
<p>The file "main.h" has just the include of Qt. Here is my code and I tried many solutions without success :</p>
<pre><code>#include "main.h"
int main(int argc, char **argv)
{
QApplication program(argc, argv);
/* ******************** First Window ******************** */
QWidget window;
QVBoxLayout layout;
window.setWindowTitle("Programme");
window.setWindowIcon(QIcon(":/Images/Images/Bouclier.png"));
window.setFixedSize(450, 400);
QHBoxLayout layouttop;
QLabel labeltop("Nom du programme :");
QLineEdit lineedittop;
layouttop.addWidget(&labeltop);
layouttop.addWidget(&lineedittop);
QHBoxLayout layoutmiddle;
QPushButton buttonnext;
QPushButton buttonprevious;
QPushButton buttonetc("...");
QLineEdit line0;
QLineEdit line1;
QLineEdit line2;
QLineEdit line3;
QLineEdit line4;
QLineEdit line5;
QLineEdit line6;
QLineEdit line7;
QLineEdit line8;
QLineEdit line9;
QVBoxLayout layoutleft;
layoutleft.addWidget(&buttonnext);
buttonnext.setIcon(QIcon(":/Images/Images/Haut.png"));
layoutleft.addWidget(&buttonprevious);
buttonprevious.setIcon(QIcon(":/Images/Images/Bas.png"));
QVBoxLayout layoutcenter;
layoutcenter.addWidget(&line0);
layoutcenter.addWidget(&line1);
layoutcenter.addWidget(&line2);
layoutcenter.addWidget(&line3);
layoutcenter.addWidget(&line4);
layoutcenter.addWidget(&line5);
layoutcenter.addWidget(&line6);
layoutcenter.addWidget(&line7);
layoutcenter.addWidget(&line8);
layoutcenter.addWidget(&line9);
line0.setReadOnly(true);
line1.setReadOnly(true);
line2.setReadOnly(true);
line3.setReadOnly(true);
line4.setReadOnly(true);
line5.setReadOnly(true);
line6.setReadOnly(true);
line7.setReadOnly(true);
line8.setReadOnly(true);
line9.setReadOnly(true);
QVBoxLayout layoutright;
layoutright.addWidget(&buttonetc);
layoutmiddle.addLayout(&layoutleft);
layoutmiddle.addLayout(&layoutcenter);
layoutmiddle.addLayout(&layoutright);
QHBoxLayout layoutbottom;
QPushButton buttonapply("Apply");
QPushButton buttoncancel("Cancel");
layoutbottom.addWidget(&buttonapply);
layoutbottom.addWidget(&buttoncancel);
layout.addLayout(&layouttop);
layout.addLayout(&layoutmiddle);
layout.addLayout(&layoutbottom);
window.setLayout(&layout);
window.show();
/* ******************** First Window ******************** */
/* ******************** Second Window ******************** */
QWidget windowed;
QVBoxLayout layouted;
windowed.setWindowTitle("Session");
windowed.setWindowIcon(QIcon(":/Images/Images/Bouclier.png"));
windowed.setFixedSize(450, 400);
QHBoxLayout layouttoped;
QLabel labeltoped("Nom de la session :");
QLineEdit lineedittoped;
layouttoped.addWidget(&labeltoped);
layouttoped.addWidget(&lineedittoped);
QHBoxLayout layoutmiddled;
QPushButton buttonnexted;
QPushButton buttonprevioused;
QPushButton buttonetced("...");
QString file;
QLineEdit lined0;
QLineEdit lined1;
QLineEdit lined2;
QLineEdit lined3;
QLineEdit lined4;
QLineEdit lined5;
QLineEdit lined6;
QLineEdit lined7;
QLineEdit lined8;
QLineEdit lined9;
QComboBox box;
QLabel label("Durée :");
QVBoxLayout layoutlefted;
layoutlefted.addWidget(&buttonnexted);
buttonnexted.setIcon(QIcon(":/Images/Images/Haut.png"));
layoutlefted.addWidget(&buttonprevioused);
buttonprevioused.setIcon(QIcon(":/Images/Images/Bas.png"));
QVBoxLayout layoutcentered;
layoutcentered.addWidget(&lined0);
layoutcentered.addWidget(&lined1);
layoutcentered.addWidget(&lined2);
layoutcentered.addWidget(&lined3);
layoutcentered.addWidget(&lined4);
layoutcentered.addWidget(&lined5);
layoutcentered.addWidget(&lined6);
layoutcentered.addWidget(&lined7);
layoutcentered.addWidget(&lined8);
layoutcentered.addWidget(&lined9);
lined0.setReadOnly(true);
lined1.setReadOnly(true);
lined2.setReadOnly(true);
lined3.setReadOnly(true);
lined4.setReadOnly(true);
lined5.setReadOnly(true);
lined6.setReadOnly(true);
lined7.setReadOnly(true);
lined8.setReadOnly(true);
lined9.setReadOnly(true);
QVBoxLayout layoutrighted;
layoutrighted.addWidget(&buttonetced);
QVBoxLayout layoutmore;
QHBoxLayout layoutmored;
layoutmored.addWidget(&label);
layoutmored.addWidget(&box);
box.addItem("30");
box.addItem("60");
layoutmore.addLayout(&layoutmored);
layoutmiddled.addLayout(&layoutlefted);
layoutmiddled.addLayout(&layoutcentered);
layoutmiddled.addLayout(&layoutrighted);
layoutmiddled.addLayout(&layoutmore);
QHBoxLayout layoutbottomed;
QPushButton buttonapplyed("Apply");
QPushButton buttoncanceled("Cancel");
layoutbottomed.addWidget(&buttonapplyed);
layoutbottomed.addWidget(&buttoncanceled);
layouted.addLayout(&layouttoped);
layouted.addLayout(&layoutmiddled);
layouted.addLayout(&layoutbottomed);
windowed.setLayout(&layouted);
/* ******************** Second Window ******************** */
/* ******************** Actions First Window ******************** */
QObject::connect(&buttonetc, &QPushButton::clicked, &windowed, &QWidget::show);
/* ******************** Actions First Window ******************** */
/* ******************** Actions Second Window ******************** */
QObject::connect(&buttonetced, &QPushButton::clicked, [&windowed, &file] {file = QFileDialog::getOpenFileName(&windowed, QObject::tr("Sélectionner un fichier son ..."), "C:/", QObject::tr("Audio (*.mp3)"));});
lined0.setText(Qstring(file));
/* ******************** Actions Second Window ******************** */
return program.exec();
}
</code></pre>
|
<p>Maybe you can try to emit the address of filename in one window and then receive this address in the second window by slot function</p>
|
Python/Flask: UnicodeDecodeError/ UnicodeEncodeError: 'ascii' codec can't decode/encode <p>Sorry for the millionth question about this, but I've read so much about the topic and still don't get this error fixed (newbie to all of this).
I'm trying to display the content of a postgres table on a website with flask (using Ubuntu 16.04/python 2.7.12). There are non-ascii characters in the table ('ü' in this case) and the result is a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128).</p>
<p>This is what my <strong>init</strong>.py looks like:</p>
<pre><code> #-*- coding: utf-8 -*-
from flask import Blueprint, render_template
import psycopg2
from .forms import Form
from datetime import datetime
from .table import Item, ItemTable
test = Blueprint('test', __name__)
def init_test(app):
app.register_blueprint(test)
def createTable(cur):
cmd = "select * from table1 order by start desc;"
cur.execute(cmd)
queryResult = cur.fetchall()
items = []
table = 'table could not be read'
if queryResult is not None:
for row in range(0, len(queryResult)):
items.append(Item(queryResult[row][0], queryResult[row][1].strftime("%d.%m.%Y"), queryResult[row][2].strftime("%d.%m.%Y"), \
queryResult[row][1].strftime("%H:%M"), queryResult[row][2].strftime("%H:%M"), \
queryResult[row][3], queryResult[row][4], queryResult[row][5], queryResult[row][6]))
table = ItemTable(items)
return table
@test.route('/test')
def index():
dbcon = psycopg2.connect("dbname=testdb user=postgres host=localhost")
cur = dbcon.cursor()
table = createTable(cur)
cur.close()
return render_template('test_index.html', table=table)
</code></pre>
<p>And part of the html-file:</p>
<pre><code>{% extends "layout.html" %}
{% block head %}Title{% endblock %}
{% block body %}
<script type="text/javascript" src="{{ url_for('static', filename='js/bootstrap.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}">
<div class="row" id="testid">
{{table}}
</div>
{% endblock %}{#
Local Variables:
coding: utf-8
End: #}
</code></pre>
<p>The problem is in queryResult[row][6] which is the only row in the table with strings, the rest is integers. The encoding of the postgres database is utf-8. The type of queryResult[row][6] returns type 'str'. What I read <a href="http://initd.org/psycopg/docs/usage.html#unicode-handling" rel="nofollow">here</a> is that the string should be encoded in utf-8, as that is the encoding of the database client. Well, that doesn't seem to work!?
Then I added the line</p>
<pre><code>psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
</code></pre>
<p>to force the result to be unicode (type of queryResult[row][6] returned type 'unicode'), because as was recommended <a href="http://stackoverflow.com/questions/5120302/avoiding-python-unicodedecodeerror-in-jinjas-nl2br-filter">here</a>, I tried to stick to unicode everywhere. Well that resulted in a UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal not in range(128).
Then I thought, maybe something went wrong with converting to string (bytes) before and I tried to do it myself then with writing</p>
<pre><code>queryResult[row][6].encode('utf-8', 'replace')
</code></pre>
<p>which led to an UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128). Didn't even work with 'ignore' instead of 'replace'.
What is going on here? I checked if the render_template() has a problem with unicode by creating and passing a variable v=u'ü', but that was no problem and was displayed correctly. Yeah, I read the usual recommended stuff like nedbatchelder.com/text/unipain.html and Unicode Demystified, but that didn't help me solve my problem here, I'm obviously missing something.</p>
<p>Here is a traceback of the first UnicodeDecodeError:</p>
<pre><code>File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/name/Desktop/testFlask/app/test/__init__.py", line 95, in index
return render_template('test_index.html', table=table) #, var=var
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template
context, ctx.app)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask/templating.py", line 116, in _render
rv = template.render(context)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/name/Desktop/testFlask/app/templates/test_index.html", line 1, in top-level template code
{% extends "layout.html" %}
File "/home/name/Desktop/testFlask/app/templates/layout.html", line 40, in top-level template code
{% block body %}{% endblock %}
File "/home/name/Desktop/testFlask/app/templates/test_index.html", line 7, in block "body"
{{table}}
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/table.py", line 86, in __html__
tbody = self.tbody()
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/table.py", line 103, in tbody
out = [self.tr(item) for item in self.items]
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/table.py", line 120, in tr
''.join(c.td(item, attr) for attr, c in self._cols.items()
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/table.py", line 121, in <genexpr>
if c.show))
File "/home/name/Desktop/testFlask/app/test/table.py", line 7, in td
self.td_contents(item, self.get_attr_list(attr)))
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/columns.py", line 99, in td_contents
return self.td_format(self.from_attr_list(item, attr_list))
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/flask_table/columns.py", line 114, in td_format
return Markup.escape(content)
File "/home/name/Desktop/testFlask/venv/lib/python2.7/site-packages/markupsafe/__init__.py", line 165, in escape
rv = escape(s)
</code></pre>
<p>Any help is greatly appreciated...</p>
|
<p>since in Python 2 bytecode is not enforced, one can get confused with them.
Encoding and Decoding works as far as i know from string to bytecode and reverse. So if your resultset is a string, there should be no need to encode it again.
If you get wrong representations for special characters like "§", i would try something like this:</p>
<p>repr(queryResult[row][6])).</p>
<p>Does that work?</p>
|
Java - copy items from one list to another using generics <p>I am trying to make a generic copy from one list to another for certain objects I know the are compatible each other, F can be an argument of T constructor</p>
<pre><code>public static <F,T> List<T> copyFrom(List<F> from){
List<T> to = new ArrayList<T>();
if (from!=null && !from.isEmpty()){
for (F f : from){
to.add(new T.newInstance(f));
}
}
return to;
}
</code></pre>
<p>but I don't know to to create an instance of T</p>
|
<p>One solution is to pass something to <code>copyFrom</code> that knows how to make a <code>T</code> from an <code>F</code>. For example:</p>
<pre><code>public static <F, T> List<T> copyFrom(List<F> from, Function<F, T> converter) {
List<T> to = new ArrayList<T>();
if (from != null && !from.isEmpty()) {
for (F f : from) {
to.add(converter.apply(f));
}
}
return to;
}
</code></pre>
<p>This uses Java 8's interface <code>java.util.function.Function</code>. If you're not using Java 8, you can write such an interface yourself, it looks like this:</p>
<pre><code>public interface Function<F, T> {
T apply(F arg);
}
</code></pre>
<p>Using Java 8 streams, you can make this much shorter:</p>
<pre><code>public static <F, T> List<T> copyFrom(List<F> from, Function<F, T> converter) {
if (from == null) {
return new ArrayList<>();
}
return from.stream().map(converter).collect(Collectors.toList());
}
</code></pre>
<p>If you have, for example, a class <code>One</code> and a class <code>Two</code> as concrete types and <code>Two</code> has a constructor that takes a <code>One</code>, you can use a method reference <code>Two::new</code> as the <code>converter</code> argument:</p>
<pre><code>class One { ... }
class Two {
public Two(One one) {
// ...
}
}
List<One> list = ...;
List<Two> = copyFrom(list, Two::new);
</code></pre>
|
Identify drive letter of USB composite device using Python <p>I have a USB composite device that has an SD card. Using Python, I need a way to find the drive letter of the SD card when the device is connected. Does anyone have experience with this? Initially it needs to work in Windows, but I'll eventually need to port it to Mac and Linux.</p>
|
<p>I don't have an SD card attached to a USB port. To get you started, you could <em>try</em> this on Windows. Install <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">Golden's WMI</a>. I found that the Windows .zip wouldn't install but the pip version works fine, or at least it does on Win7. Then you can list logical disks with code like this.</p>
<pre><code>>>> import wmi
>>> c=wmi.WMI()
...
>>> for disk in c.Win32_LogicalDisk():
... print(disk)
</code></pre>
<p>This code provided a listing that included mention of a NAS which is why I have hopes for your SD card. Various refinements are possible.</p>
|
Output InnerHTML Perl LibXML <p>Please see MWE below</p>
<pre><code>use XML::LibXML;
my $content = "<tr>
<td class='title'>Synonym(s)</td>
<td>Automobile<br/>Car<br/></td>
</tr>";
my $parser = XML::LibXML->new({suppress_errors=>1, suppress_warnings=>1, recover=>2});
my $document = $parser->parse_html_string($content);
my @node = $document->findnodes('//td[@class="title" and text()="Synonym(s)"]/following-sibling::td');
print $node[0]->toString();
</code></pre>
<p>The output is:
<code><td>Automobile<br/>Car<br/></td></code></p>
<p>But I need just the "inner" content:
<code>Automobile<br/>Car<br/></code></p>
<p>How do I need to change the xPath, or do I need a different LibXML method.</p>
<p>Thank you,
Tobias </p>
|
<p>There is no built-in way to do that in XML::LibXML. Changing the xpath won't help. That xpath gives you a list of <code>td</code> elements. If you'd get the stuff inside of all <code>td</code> elements that fit the current xpath, you'd end up with a long list of things and no way to discern where the content of the first <code>td</code> ends and the second <code>td</code> starts.</p>
<p>Instead, you need to construct it by converting <a href="https://metacpan.org/pod/distribution/XML-LibXML/lib/XML/LibXML/Node.pod#childNodes" rel="nofollow">all children</a> of the <code>td</code> element to string.</p>
<pre><code>print join '', map { $_->toString } $node[0]->childNodes;
</code></pre>
<p>Output:</p>
<pre><code>Automobile<br/>Car<br/>
</code></pre>
|
Convert .fbx to .obj with Python FBX SDK <p>I have a ten frame .fbx file of an animal walking. This file includes a rigged model with textures, but I am only interested in the mesh of the model at each frame. </p>
<p>How can I use Python FBX SDK or Python Blender SDK to export each frame of the fbx file into an obj file?</p>
<p>Am I approaching this the wrong way? Should I try to find a way to do this manually in Maya/Blender first?</p>
|
<p>its a example for fbx to obj
import fbx</p>
<pre><code># Create an SDK manager
manager = fbx.FbxManager.Create()
# Create a scene
scene = fbx.FbxScene.Create(manager, "")
# Create an importer object
importer = fbx.FbxImporter.Create(manager, "")
# Path to the .obj file
milfalcon = "samples/millenium-falcon/millenium-falcon.fbx"
# Specify the path and name of the file to be imported
importstat = importer.Initialize(milfalcon, -1)
importstat = importer.Import(scene)
# Create an exporter object
exporter = fbx.FbxExporter.Create(manager, "")
save_path = "samples/millenium-falcon/millenium-falcon.obj"
# Specify the path and name of the file to be imported
exportstat = exporter.Initialize(save_path, -1)
exportstat = exporter.Export(scene)
</code></pre>
|
cast numpy array into memmap <p>I generate some data in my memory and I want to cast it into numpy.memmap to save up RAM. What should I do? my data is in:</p>
<pre><code> X_list_total_standardized=np.array(X_list_total_standardized)
</code></pre>
<p>I know that I could initialize an empty numpy.memmap:</p>
<pre><code>X_list_total_standardized_memmap=np.memmap(self._prepared_data_location_npmemmap_X,dtype='float32',mode='w+')
</code></pre>
<p>What is the most convenient way to store X_list_total_standardized into the memmap? Thank you</p>
<p>PS: would the following command be ok?</p>
<pre><code> X_list_total_standardized_memmap[:]=X_list_total_standardized[:]
</code></pre>
|
<p>I found next example in numpy documentation :</p>
<pre><code>data = np.arange(12, dtype='float32')
data.resize((3,4))
fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
fp[:] = data[:]
</code></pre>
<p>So your last command is ok.</p>
|
Can HTTP-header LAST-UPDATED be trusted? <p>I have been using <a href="http://www.rexswain.com/httpview.html" rel="nofollow">Rex Swain's HTTP Viewer</a> to verify that none of the texts on a certain webpage has been changed recently.</p>
<p>The response was: "Code last updated 21 January 2012", so as I understand it, I can't really assume that anything was actually changed on that date but is it safe to assume that none of the texts on the webpage has been changed since that date?</p>
<p>I am not an HTTP expert, so please use layman terms where possible, thanks :-)</p>
<p>BR</p>
|
<p>A web server typically uses the corresponding file's <em>last updated</em> attribute as the value for the HTTP <code>Last-Modified</code> header, so in <strong>general</strong> it can be trusted, but it's always possible that the date is wrong, for whatever reason.</p>
<p>The <code>Last-Modified</code> header is usually used for caches, to populate the <code>If-Modified-Since</code> header in subsequent requests.</p>
|
Extract a single email address from Word doc and apply it to the TO: field of an Outlook email <p>The company I work for emails letters to hundreds of people a day. The letter templates vary, as does the location in the letter of the data that I want. I already have VBA code that handles most of the steps for the user, including attaching the letter as PDF to an Outlook email and populating the subject and body. Currently, the issue is that human error is causing typos and misdirection when the users type in the email address that the letter is going TO. So I'm trying to add a section in this code that searches the document for an email address (there will always only be one email address in the doc, but might be in different place), and then copies that email and puts it in the TO line of the Outlook email. Here is the code I'm using:</p>
<pre><code>Sub EmailDocumentAsPDFfinal()
Dim SourceDoc As Document
Dim OutlookApp As Object
Dim OutlookMessage As Object
Dim TempFileName As Variant
Dim TempFilePath As String
Dim DefaultName As String
Dim UserAnswer As Long
Dim x As Long
Set SourceDoc = ActiveDocument
TempFilePath = Environ$("temp") & "\"
If SourceDoc.Path <> "" Then
DefaultName = Left(SourceDoc.Name, InStrRev(SourceDoc.Name, ".") - 1)
Else
DefaultName = SourceDoc.Name
End If
TempFileName = "DocName"
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=TempFilePath & TempFileName & ".pdf", _
ExportFormat:=wdExportFormatPDF
On Error Resume Next
Set OutlookApp = GetObject(class:="Outlook.Application") 'Handles if Outlook is already open
Err.Clear
If OutlookApp Is Nothing Then Set OutlookApp = CreateObject(class:="Outlook.Application") 'If not, open Outlook
If Err.Number = 429 Then
MsgBox "Outlook could not be found, aborting.", 16, "Outlook Not Found"
Exit Sub
End If
On Error GoTo 0
Set OutlookMessage = OutlookApp.CreateItem(0)
On Error Resume Next
With OutlookMessage
.To = ""
.CC = ""
.BCC = ""
.Subject = "This is the letter you requested"
.Body = "Please let us know if you have any questions."
.Attachments.Add TempFilePath & TempFileName & ".pdf"
.Display
End With
On Error GoTo 0
Kill TempFilePath & TempFileName & ".pdf"
Set OutlookMessage = Nothing
Set OutlookApp = Nothing
End Sub
</code></pre>
|
<p>Try adding the following block to your code (preferrably in the beginning after you define <code>SourceDoc</code>) - it looks for the email using wildcards and returns a full string to the <code>EmAdr</code> variable, which you can use in the <code>.To</code> line of your outlook sender code</p>
<pre><code>Dim rng as Range
Dim EmAdr as String
Set rng = SourceDoc.Content
With Rng.Find
.Text = "*@*.*"
.Wrap = wdFindAsk
.Forward = True
.MatchWildcards = True
If .Execute Then
EmAdr = rng.Text
Else
MsgBox "Email not found"
End If
End With
</code></pre>
<p>If this helps, please mark the answer as accepted.</p>
|
Notificatoin Intent to the app that is running <p>I recently added a notification to my test, It has a Countdown Timer in it and when I pick the time and tap the button, the notification is set to the timer and working. but when i hit the home button when the notification is still running, and tap the notification it gets me to a new page of my app not the one that is running. The fix I'm looking to make is to stop the timer when the notification is tapped and get the user to a reset page of my app.</p>
<pre><code>//Notification Intent
final Intent notifyIntent = new Intent(this , MainActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view.equals(silentButton)) {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
final CountDownTimer counter = new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("Silent ends in: " + "%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
myText.setText(hms);
//Notification
notifyTimer.setSmallIcon(R.mipmap.ic_launcher);
notifyTimer.setTicker("This is a notification");
notifyTimer.setAutoCancel(true);
notifyTimer.setContentTitle(hms);
//Notification Intent
notifyTimer.setContentIntent(pendingIntent);
//issues the notification
nm.notify(uniqueID, notifyTimer.build());
}
public void onFinish() {
myText.setText("TIME'S UP!!"); //On finish change timer text
nm.cancel(uniqueID);
}
}.start();
stopButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
counter.cancel();
myText.setText("Timer has been reset");
nm.cancel(uniqueID);
}
}
);
}
</code></pre>
|
<p>you can set flags to intent for configuring its behavior,for your purpose you can use this</p>
<pre><code> notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
</code></pre>
|
How do I run my PHP code on the click of a button? <p>I'm trying to build a website for school project. I want the schoolResponse() function to happen after clicking the Submit button. If I remove the jQuery function it works but then it shows a default value when I load the page. </p>
<p>Here's my code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>NHG</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="css/normalize.css"/>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<link type="text/css" rel="stylesheet" href="css/resposive.css"/>
</head>
<body>
<header>
<div id="main-head">
<a href="#"><h2 id="main-heading">sKoolBook</h2></a>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<form method="POST">
<select name="school">
<option value="none" name="none">Please Select a School...</option>
<option value="NHG">New Horizon Gurukul</option>
</select>
<input type="submit" class="button"/>
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
?>
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
</form>
</div>
</div>
</section>
<footer>
</footer>
</body>
</html>
</code></pre>
|
<p>You can't achieve it like this. Here is one solution:</p>
<pre><code> <?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
if($_POST['school']) schoolResponse();
?>
</code></pre>
<p>It would be better if you replace <code>error_reporting(0);</code> with <code>error_reporting(E_ALL);</code> for example, because otherwise php errors will be disabled.</p>
<p>And remove this part:</p>
<pre><code> <script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
</code></pre>
<p>But it is very very basic example.</p>
|
SQL Joining Diffrent Size Tables Together With Null Value Replacement <p>I am working on a query for a datatable and I can't seem to get it to display how I want, I don't know if this is even possible in SQL What I am looking to do is get a query to respond with ideally an extra column of Boolean type. </p>
<p>Currently I can run two queries and they both work perfectly but I can't work out how to join them together bellow is the code from my first query what this does is return beers a user has tried this works fine and as expected and returns as expected.</p>
<pre><code>SELECT *
FROM keg.beer
JOIN keg.userbeer
ON beer.id = userbeer.beer_id
WHERE userbeer.username_id = 1;
</code></pre>
<p>The second query is even simpler and is just a select getting the list of beers.</p>
<pre><code>SELECT * FROM keg.beer
</code></pre>
<p>What I want to do is run a query and have it return a list of beers with a Boolean value if the user has tried it or not.</p>
|
<p>You're not going to run into too many scenarios for "Desired Results" that can't be produced with plain 'ol SQL. In this case you'll use a CASE statement to determine if the person has tried a beer. You'll also want a LEFT OUTER JOIN so you don't drop records coming from your <code>beer</code> table when your filtered <code>userid</code> doesn't have a <code>userbeer</code> record for that <code>beer</code>:</p>
<pre><code> SELECT
beer.name,
beer.id,
beer.country,
CASE WHEN userbeer.username_id IS NULL THEN 0 ELSE 1 END AS user_tried_beer_boolean
FROM keg.beer
LEFT OUTER JOIN keg.userbeer
ON beer.id = userbeer.beer_id
AND userbeer.username_id = 1;
</code></pre>
<p>As @SeanLange mentioned in the comments here, the restriction of the WHERE statement for the userid would cause records to be dropped that you want in your result set, so we move the restriction of <code>username_id = 1</code> to the <code>ON</code> portion of the <code>LEFT OUTER JOIN</code> so that the <code>userbeer</code> table results are restricted to just that user <em>before</em> it's joined to the <code>beer</code> table.</p>
<p>Now I need a drink.</p>
|
Parameter Not Valid Error c# while retriving saved image from mysql <p>I have created image column in table as <code>mediumblob</code> </p>
<p>to save image i used following code </p>
<pre><code>byte[] ImageData;
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
ImageData = new byte[Convert.ToInt32(fs.Length)];
fs.Read(ImageData, 0, Convert.ToInt32(fs.Length));
fs.Close();
string qry = "Update admin_info set `img`='"+ ImageData + "' where id='AD001";
using (con = new MySqlConnection(DBConStr))
{
con.Open();
using (cmd = new MySqlCommand(qry, con))
{
cmd.ExecuteNonQuery();
}
}
MessageBox.Show(" Profile Picture Updated Successfully!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
</code></pre>
<p>and it was sucessfull but m getting parameter invalid while retrieving it to picture box using below code</p>
<pre><code>using (MySqlConnection conn = new MySqlConnection("Server = localhost; Port = 3307; database = attendance; uid = root; pwd = MJN45720!"))
{
conn.Open();
string myQuery = "SELECT img FROM admin_info where id='AD001'";
using (MySqlCommand cmd = new MySqlCommand(myQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
byte[] x = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(x);
pictureBox1.Image = new Bitmap(ms); //Parameter invalid in this line
}
}
}
</code></pre>
<p>searched many forums and tired all they suggesting in every posts but im unable to solve.. </p>
|
<p>You don't saving image into DB correctly.
Line <code>string qry = "Update admin_info set ``img``='"+ ImageData + "' where id='AD001";</code> will result in
<code>qry = "Update admin_info set ``img``='System.Byte[]' where id='AD001</code> because you are converting byte array to string which will result in type name only.
You will have to convert byte array to HEX string which should be accepted by SQL engine.</p>
|
Dropdown list to click item to display bold in textbox then type normal <p>When type text display dropdown list click it will display Bold letter in textbox then type continuously normal letter allowed only not bold letter without button.</p>
<p>Eg. <strong>Java</strong>world</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(function(){
var availableName = ["Java","Javascript","PHP","HTML","CSS","Angularjs","SQL",".Net"];
$( "#uname" ).autocomplete({
source: availableName
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: powderblue;
color: Darkblack;
}
h2 {
color: #000080;
font-size: 300%;
}
.name{
font-weight: bold;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div class="row">
<form align="center">
<br> <label for="name"> Name: </label>
<input class="name" type="text" id="uname"> <br>
</form>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/JNgnJ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/JNgnJ.jpg" alt="Example"></a></p>
|
<p>Please look at my solution: <a href="http://jsfiddle.net/ionutmihai1995/32Bck/340/" rel="nofollow">jsfiddle</a></p>
<pre><code>$(document).ready(function () {
$("#suggest").autocomplete({
delay: 100,
source:["Java","Javascript","PHP","HTML","CSS","Angularjs","SQL",".Net"]
}).data( "autocomplete" )._renderItem = function( ul, item ) {
var term = this.element.val(),
regex = new RegExp( '(' + term + ')', 'gi' );
t = item.label.replace( regex , "<b>$&</b>" );
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a style='height:30px;'>" + t + "</a>")
.appendTo( ul );
};
});
</code></pre>
<p>Hope this will help you !.</p>
|
String formatting of floats <p>I would like to convert a number to a string in such a way that it only shows a certain number of significant digits, without superfluous zeros. The following is an example of some desired in/outputs, given that I want 5 significant digits:</p>
<pre><code>0.0000123456789 > 1.2346e-5
0.00123456789 > 1.2346e-3
0.123456789 > 1.2346e-1
1.23456789 > 1.2346
1234.56789 > 1234.6
1234567.89 > 1.2346e6
</code></pre>
<p>The <code>g</code> option of string formatting (<a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">https://docs.python.org/2/library/string.html#format-specification-mini-language</a>) comes pretty close, but its behaviour isn't quite what I'm looking for for numbers smaller than 1, but not <em>much</em> smaller than 1:</p>
<pre><code>"{:.5g}".format(0.000123456789) # returns '0.00012346', I want '1.2346e-4'
</code></pre>
<p>Is it possible to manipulate the behaviour of one of the existing formatters to do this?</p>
|
<pre><code>'{:.4g}'.format(float(input)) if x<=1000 or x>=.0001 else '{:.4e}'.format(float(input))
</code></pre>
|
Implementing paging with hibernate envers <p>I have written an envers query as below;</p>
<pre><code>AuditReader reader = AuditReaderFactory.get(entityManager);
List<Object[]> changes = reader.createQuery()
.forRevisionsOfEntity(cls, true, true)
// Various conditions
.getResultList();
</code></pre>
<p>What I would like to do is get the results in pages as can be done in <code>PagingAndSortingRepository<T,ID></code>, I have this nearly working as shown below</p>
<pre><code>int start = page.getOffset();
int end = (start + page.getPageSize()) > history.size() ? history.size() : (start + page.getPageSize());
Page page = new PageImpl<HistoryEntry>(history.subList(start, end), page, history.size());
</code></pre>
<p>My problem is that when done this way I can't sort the data as expected i.e. <code>size=2&sort=action,desc</code> does not sort no matter what value I use (asc/desc).</p>
<p><code>history</code> is a list of objects with the following fields;</p>
<pre><code>private String timestamp;
private String userName;
private String objectName;
private String objectType;
private String action;
private String field;
private String oldValue;
private String newValue;
</code></pre>
<p>In order to implement paging, filtering and sorting through envers would this need to be done through the original envers query or could paging look after this?</p>
|
<p>It appears that the <code>PageImpl</code> class expects the <code>List<T></code> you provide in the constructor to be the subset of the rows for the given page, already pre-sorted. Therefore, we'll need to apply the sort operations as a part of the Envers query. </p>
<pre><code>List<Object[]> changes = reader.createQuery()
.forRevisionsOfEntity( cls, true, false )
// various predicate conditions
.addOrder( AuditEntity.property( "someField" ).desc() )
.getResultList();
</code></pre>
<p>Apply the sort this way will then allow the code where you selected the subset for the page from the results to work as intended.</p>
|
Why does my valueOf() method not return the value? <p>I'm having a little problem with the valueOf() method of an object.
I've got an Array with objects and object literals in it.
Say it's <code>var Books = [ {"name": "SomeBook"}, {"name": "SomeOtherBook"} ]</code>.
Now I want to write all the literals into some text-inputs via</p>
<pre><code>var i = 0;
book = Books[0];
for (var property in book) {
if (book.hasOwnProperty(property)) {
editInputs[i].value = property.valueOf();
//console.log(property.valueOf());
}
i++;
}
</code></pre>
<p>Why is my output the object's name? When I de-comment the log(), I also get "name" instead of SomeBook. Yet, if I use</p>
<pre><code>editInputs[0].value = book.name;
</code></pre>
<p>It inserts <code>SomeBook</code>.</p>
<p>Why? I don't want to write every field in a single line...</p>
<p>Thanks in advance!</p>
|
<p><code>property</code> is a string containing the name of the property.</p>
<p><code>valueOf</code> gives you the primitive value of that, which is still a string containing the name of the property.</p>
<p>If you want to use that string to get the value of the property name which matches the string stored in <code>property</code> you need to use:</p>
<pre><code>book[property]
</code></pre>
|
One recipe for multiple targets with static pattern rules? <p>what is the best way using make to achieve the following:</p>
<h2>input files</h2>
<pre><code>$PRJ/lib/foo.c
$PRJ/app/bar.c
$PRJ/app/baz.c
</code></pre>
<h2>output files shall be (using GCC):</h2>
<pre><code>$PRJ/obj/foo.o
$PRJ/obj/bar.o
$PRJ/obj/baz.o
</code></pre>
<p>Please notice that the input c-files are not in the same folders and I want to automate the collection of the input files.</p>
<p>This example here (using static pattern rules) only works if the c-files are all in the same folder but how is this gonna work for the above case?</p>
<pre><code>SOURCES = $(shell find $(PRJ)/app -type f -name *.c)
OBJECTS = $(patsubst $(PRJ)/app/%, $(PRJ)/obj/%, $(SOURCES:.c=.o))
.PHONY: build
build: $(OBJECTS)
$(OBJECTS): $(PRJ)/obj/%.o: $(PRJ)/app/%.c)
$(CC) $(CFLAGS) -c -o $@ $<
</code></pre>
|
<p>Use <a href="https://www.gnu.org/software/make/manual/make.html#Selective-Search" rel="nofollow">the vpath directive</a>:</p>
<pre><code>SOURCES := $(shell find $(PRJ) -type f -name "*.c")
# $(PRJ)/lib/foo.c $(PRJ)/app/bar.c $(PRJ)/app/baz.c
SOURCE_DIRS := $(sort $(dir $(SOURCES)))
# $(PRJ)/app/ $(PRJ)/lib/
OBJECTS := $(patsubst %.c,$(PRJ)/obj/%.o, $(notdir $(SOURCES)))
# $(PRJ)/obj/foo.o $(PRJ)/obj/bar.o $(PRJ)/obj/baz.o
.PHONY: build
build: $(OBJECTS)
vpath %.c $(SOURCE_DIRS)
$(OBJECTS): $(PRJ)/obj/%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.