Q: Latitude and Longitude are null I'm working on an app getting user's current location  and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
@Override
public void onLocationChanged(Location location) {

    TextView tvLocation = (TextView) findViewById(R.id.tv_location);

    // Getting latitude of the current location
    double latitude = location.getLatitude();

    // Getting longitude of the current location
    double longitude = location.getLongitude();

    // Creating a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Showing the current location in Google Map
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    // Setting latitude and longitude in the TextView tv_location
    tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

}

Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
 01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
 EXCEPTION: main
  Process: io.xgear.geotag, PID: 29286
  java.lang.NullPointerException
      at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
      at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
      at android.view.View.performClick(View.java:4633)
      at android.view.View$PerformClick.run(View.java:19270)
      at android.os.Handler.handleCallback(Handler.java:733)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:146)
      at android.app.ActivityThread.main(ActivityThread.java:5602)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
      at dalvik.system.NativeStart.main(Native Method)

this is the piece of code for getting latitude and longitude to send
 public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());

        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

and this is the full code
package io.xgear.geotag;

import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import io.xgear.geotag.helper.Post;

public class MainActivity extends FragmentActivity implements LocationListener {
    GoogleMap googleMap;
    private GeoTagTask mAuthTask = null;
    GPSTracker gps;
    private JSONObject jsonObj;

    // UI references.
    private EditText txtShopCode;
    private EditText lblAddress;
    private View mProgressView;
    private View mGeoTagForm;
    private Button btnGeoTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtShopCode = (EditText) findViewById(R.id.txtShopCode);
        btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
        mGeoTagForm = (View) findViewById(R.id.geoTagForm);
        mProgressView = findViewById(R.id.geoTagProgress);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }

        btnGeoTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String shopid = txtShopCode.getText().toString();
                boolean cancel = false;
                View focusView = null;

               //txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);

                if (TextUtils.isEmpty(shopid)) {
                    txtShopCode.setError(getString(R.string.error_field_required));
                    focusView = txtShopCode;
                    cancel = true;

                }
                else {

                    showProgress(true);
                    mAuthTask = new GeoTagTask(shopid);
                    mAuthTask.execute((Void) null);
                }
            }

        });

    }

//

//    public void btnGeoTag_Click(View v){
//
//    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
            mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());

        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("jsonObj", jsonObj.toString());
//                startActivity(intent);
                txtShopCode.getText().clear();
                txtShopCode.requestFocus();
                Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();

            } else {
//                if(isConnect){
//                    mPasswordView.setError(getString(R.string.error_incorrect_password));
//                    mPasswordView.requestFocus();

//                }
//                else
                    Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.activity_main, menu);
//        return true;
//    }
}

UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
 if( location != null){
            onLocationChanged(location);
       }
     locationManager.requestLocationUpdates(provider, 20000, 0, this);

is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);

        Location location = locationManager.getLastKnownLocation(provider);

A: inside GeoTagTask location object  is different one and also doesn't initilized.
    Location location;
    private String lat = Double.toString(location.getLatitude());
    private String lng = Double.toString(location.getLongitude());

A: Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());

You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
    Location location;
    void onCreate() {
        ....
        location = locationManager.getLastKnownLocation(provider);
        ....
    }
}

Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());
        ...
}


Q: Merge multiple mutually exclusive factor columns into a single column Say I have three columns in a data frame.  I want to merge these into a single column.  Each of the three columns is a binary attribute such as green/yellow, red/blue, black/white, etc.
I want to merge all of these into a single column with multiple
 row1=c(0,0,1)
 row2=c(1,0,0)
 row3=c(0,1,0)
 df=data.frame(rbind(row1,row2,row3))

Is there a way to merge each of these columns into a single column?  The single column would now have to have six different factors instead of the two it already has.
Can anyone show me how to code this?

A: You can encode these as you would encode a binary number, by assigning increasing powers of two for each column.  You want to multiply each row by c(1,2,4) and then take the sum.
# The multiplier, powers of two
x <- 2^(seq(ncol(df))-1)
x
## [1] 1 2 4

# The values
apply(df, 1, function(row) sum(row*x))
## row1 row2 row3
## 4    1    2

To add this as a new column:
df$new <- apply(df, 1, function(row) sum(row*x))
df
##      X1 X2 X3 new
## row1  0  0  1   4
## row2  1  0  0   1
## row3  0  1  0   2

A: Try:
> df
     X1 X2 X3
row1  0  0  1
row2  1  0  0
row3  0  1  0
>
>
> mm = melt(df)
No id variables; using all as measure variables
>
> mm$new = paste(mm$variable,mm$value,sep='_')
>
> mm
  variable value  new
1       X1     0 X1_0
2       X1     1 X1_1
3       X1     0 X1_0
4       X2     0 X2_0
5       X2     0 X2_0
6       X2     1 X2_1
7       X3     1 X3_1
8       X3     0 X3_0
9       X3     0 X3_0

mm$new is the column you want.

A: Maybe this is what you want:
> df$X1 = ifelse(df$X1==0,'green','yellow')
> df$X2 = ifelse(df$X2==0,'red','blue')
> df$X3 = ifelse(df$X3==0,'black','white')
>
> df
         X1   X2    X3
row1  green  red white
row2 yellow  red black
row3  green blue black
>
> unlist(df)
     X11      X12      X13      X21      X22      X23      X31      X32      X33
 "green" "yellow"  "green"    "red"    "red"   "blue"  "white"  "black"  "black"


Q: Why doesn't the ttf fonts work with Vue CLI? I am working with Vue CLI, and I want to use a font downloaded from the Internet. I think I have configured everything but it just doesn't work.
The structure of the project is like this:
+--node_modules
+--public
|  +--index.html
+--src
|  +--assets
|  |  +--css
|  |  +--font
|  |  |  +--font.css
|  |  |  +--FZYXJW.ttf
|  +--components
|  +--App.vue
|  +--main.js
+--babel.config.js
+--vue.config.js
+--package.json

Here are the relative codes:
// font.css
@font-face {
  font-family: 'Youxian';
  src: url("FZYXJW.ttf");
}

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
        .rule('font')
        .test(/\.(woff2?|eot|ttf|otf)(\?.*)?$/)
        .use('url-loader')
        .loader('url-loader')
        .end()
  }
};

// App.vue
<template>
  <div id="app">
      <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app'
}

</script>

<style>
  @import "/assets/font/font.css";

  #app {
    font-family: 'Youxian';
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }

</style>

I expected the font to change to "Youxian", but actually nothing happened.


Q: Cannot upload chunked video to twitter I have been trying to upload video chunks to twitter using twurl as in the example on the page: https://blog.twitter.com/2015/rest-api-now-supports-native-video-upload
However, I get the "unsupported video" error. I am able to upload smaller sized videos without breaking them into chunks.
I am running twurl on Ubuntu 12.04

A: It means exactly "unsupported video".
Twitter has a strict video format requirement: https://dev.twitter.com/rest/public/uploading-media#videorecs.
Example: sample mp4 files containing 6-channel audio won't be supported.
Check out my project: https://github.com/mtrung/TwitterVideoUpload.


Q: Android Studio, on Windows: ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart' I downloaded Android Studio on windows, and I am trying to run the default HelloWorld application. However, when I run that app, I get a dialog box with the following:
ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart'

I've searched for solutions online and most of it was to kill the adb server and start it again manually, but when I do so in the command line I get:
sdk\platform-tools>adb kill-server
* server not running *

sdk\platform-tools>adb start-server
adb server is out of date.  killing...
ADB server didn't ACK
* failed to start daemon *

And the first error keeps showing. I restarted my machine, and the problem is still there. Any ideas? Thanks.
I tried this fix: http://visualgdb.com/adbfix/#adbfix_download but it did not work. It showed: "No Conflicts Found".
Note: I need the app to run on my device. Not on emulator

A: I was also facing same issue and I followed these steps and problem went away:
1.close all program in your system then
2.then go to start button and search for %temp% then delete all files inside this folder
3.install Cclean software and clean your system.
4.restart your system

A: I was facing same issue in win7 and I took these steps to resolve the problem:
When starting Android Studio, it warns you with ADB not responding.
If you'd like to retry, then please manually kill the process. You should enter cmd, and input adb kill-server for ten times or more.
When the building has finished, input adb start-server and you will see
daemon not running.
starting it now on port 5037
daemon started successfully


Q: Query regarding looping a response data array using async await I am working with an existing class components based React application and was dumbfounded when I spent almost 3 hours to figure out the root cause of the following code snippet.
In componentDidMount which is async btw, I am calling backend API designed with Node.js using axios like this
(Note state below is in Class Component which I skipped for obvious reasons)
state = {
  grades = [];
}

try {
    const res = await axios.get(
      `/assignments/getStudentAssignment/${this.props.studentId}`
    );

    const assignments = res.data.assignment.assignments;

    assignments.forEach((assignment) => {
       this.setState({grades: [...this.state.grades, assignment.grade]})
    }))

} catch (err) {
    'some logic'
}

Where res.data.assignment.assignments is an array of each student assignments, and from each assignment I am pushing a new grade in grades array state. In console.log using Chrome browser I saw that the grades array had 8 elements but I couldn't view them in console.log, and the length of array was also set to 0.
I consoled assignment within forEach array and also set a counter in order to see that is forEach looping through the entire array or just first element. Console.log only printed first counter number and also first array element
I figured out that since the assignments is an array of promises that are yet to be resolved, I cannot loop through the entire array, and then I changed my code to this
await assignments.forEach((assignment) => {
       this.setState({grades: [...this.state.grades, assignment.grade]})
}))

And viola, it worked like a charm but I am confused on a couple of things.

*

*Isn't await supposed to resolve promise res.data.assignment.assignments,
meaning I can loop through resolved array data

*Why did forEach work for only first element of
res.data.assignment.assignments if the array was yet to be resolved?

I tried on MDN, by creating a sample array in a promise and then looping through the contents of array in a then chain where each element was printed on console perfectly. Any help will be appreciated
EDIT
I have changed the original code, axios returns an assignment object which also contains an array of assignments
I worked with the following code once again without await, and its working fine. This is the second time, I had trouble with React setState, first time setState wasn't firing for some reason, and then after deleting node_modules and installing all required packages it worked, even though it wasted a day
   state = {
     grades = [];
   }

   try {
       const res = await axios.get(
          `/assignments/getStudentAssignment/${this.props.studentId}`
       );

       const assignments = res.data.assignment.assignments;

       assignments.forEach((assignment) => {
         this.setState({grades: [...this.state.grades, assignment.grade]})
       }))
    } catch (err) {
    'some logic'
    }


Q: Adding new variables to existing data that correlate with one or two existing ones How can I add two more variables with the following conditions?

*

*Variable "c" that has a 0.7 correlation with variable "a".

*If possible, variable "d" that correlates simultaneously with "a" and "b".

Simulated data
n = 100

d = tibble(a = rnorm(n, 50, 20),
           b = rnorm(n, 10, 0.4))

d

Tidyverse solutions are much appreciated!

A: Here is a small function that take a vector x and a desired rho and returns a vector such that cor(<vector>,x) == rho`).
f <- function(x,rho) {
  orth = lm(runif(length(x))~x)$residuals
  rho*sd(orth)*x + orth*sd(x)*sqrt(1-rho^2)
}

Now we apply the function to column a to create a column c such that cor(a,c) == 0.7
d %>%  mutate(c = f(a,.7))

A: The second is actually more easier (for me at least): just make z-scores out of both a and b and add or average them. It will correlate with both a and b with 0.7
d <- d %>%
  mutate(d=((a - mean(a)) / sd(a)) +
           ((b- mean(b)) / sd(b)))

A: Using the Iman and Conover method (1982) developed in the mc2d package (a rank correlation structure).
library(mc2d)
cc <- rnorm(n,50,20)
cc <- cornode(cbind(d$a,cc), target=0.7)[,"cc"]
d$c <- cc
cor(d)

For more than one variable, you have to build a matrix of correlation.
## Target
(corrTarget <- matrix(c(1, 0.7, 0.7, 0.7, 1, 0.7, 0.7, 0.7, 1), ncol=3))

dd <- rnorm(n,50,20)
dd <- cornode(cbind(a=d$a,b=d$b,dd), target=corrTarget)
cor(dd)
d$b <- dd[,"b"]
d$d <- dd[,"dd"]

cor(d)

The final correlation structure should be checked because it is not always possible to build the target correlation structure.


Q: maximum number of possible rules of a sequence? Read this
http://www.mathsisfun.com/algebra/sequences-finding-rule.html
and also
http://en.wikipedia.org/wiki/The_Oxford_Murders_%28film%29
where the scene about the murder note left behind contains a sequence of numbers, and it is said that the next number can be pretty much anything
a few more googling eventually lead me into this
http://en.wikipedia.org/wiki/Wittgenstein_on_Rules_and_Private_Language
which said that all rules are subjected to interpretations, and that you cannto be sure which is the correct one
So my question then becomes:
Given a sequence
$$S=a_1,a_2,a_3,a_4 \cdots$$
What is the maximum number of possible rules that can be used to produce the next term, or is it impossible in general for all sequences S to have a finite number of rules that can produce all given terms and the next terms?
A more concrete example:
$$S_1=1,1,2,3 \cdots$$
We knew that one of the rules that fit $S_1$ is the Fibonacci Sequence, but is there a maximum number of rules that can fit $S_1$ but does NOT generate the Fibonacci Sequence?
If we have a function F(S,$\lambda$) which is defined as follows
$$F(S,\lambda)=max(no. of rules for a given S)$$
where S is a sequence and $\lambda$ is the number of known first few terms in the sequence (e.g. $\lambda$=2 means we are given $a_1,a_2$
What is the first starting point in choosing S (so as to make it less ambigurious) such that the behavior of F can be investigated without loss of (too much) generality?

A: I am pretty sure that $F$ is always infinite. Given sequence $S = a_1, a_2, \dotsc$ with $\lambda = 2$, we can consider these as two points $(1,a_1)$ and $(2,a_2)$. Given these two points, there are a countably infinite number of cubic polynomials that satisfy these two points (one for each integer choice of $a_3$).
We can say that our rule is $a_i = fi^2 + gi + h$ for the $f,g,h$ that agree with our first two terms $a_1$ and $a_2$ and produce any chosen value of $a_3$ for $i=3$.
More generally, I suppose I would define a rule to be the ability to produce on demand any given term of a sequence. Given some $S$ with $\lambda = n$, if we are requested to produce the $m^{\mathrm{th}}$ term of $S$, there are infinitely many degree $n+1$ polynomials (one for each possible choice of the $m^{\mathrm{th}}$ term) that can serve as a rule to our $S$. Then if we are requested to produce some other term, we can choose any of the infinitely many degree $n+2$ polynomials that satisfies the terms we have so far and give us then next requested term. Et cetera.
This doesn't quite work, though, if we allow $\lambda$ to be infinite.


Q: 'in' operator with boost::python I have a class which .defines the __getitem__, __setitem__ methods (and keys and items as well), and behaves like a dictionary, where keys are strings.
However, the in operator does not behave as expected:
>>> myObject=MyClass()
>>> 'abc' in myObject.keys()
False
>>> 'abc' in myObject
ArgumentError: Python argument types in
    MyClass.__getitem__(MyClass, int)
did not match the C++ signature:
    __getitem__(MyClass {lvalue}, std::string)

Why is python trying to call __getitem__ with int, when I use the str key?

A: It seems that
'abc' in myObject

is being evaluated as:
for i in myObject:
    if myObject[i] == 'abc':
        return true

Where i is an integer.
Try implementing the __contains__(self, value) magic method.


Q: Uncaught TypeError: Cannot read property 'getElementsByClassName' of null | HTML |JS I have an Html page with cards for my memory card game, The user is supposed to match a pair of cards and win an offer mentioned in the card. The offers are for an online grocery shopping application. I get the following error when I flip the card.

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        25 % OFF on
Soft Drinks

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        10 % OFF on
Fruits
&
 Vegetables

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        25 % OFF on
Soft Drinks

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        10 % OFF on
Fruits
&
 Vegetables

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        15 % OFF on
Dairy Products

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        15 % OFF on
Dairy Products

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Buy any can of
Pringles and get
another for FREE!

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Buy any can of
Pringles and get
another for FREE!

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Oreo Party Pack
for only
Rs.1500.00

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Oreo Party Pack
for only
Rs.1500.00

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Get a Free Pack
of Dilmah tea
of your choice.

                    <svg class="Rectangle_13">
                        <rect id="Rectangle_13" rx="8" ry="8" x="0" y="0" width="141" height="172">
                        </rect>
                    </svg>
                    <svg class="Rectangle_1">
                        <rect id="Rectangle_1" rx="32" ry="32" x="0" y="0" width="64" height="64">
                        </rect>
                    </svg>

                            Joey’s

                    <svg class="Rectangle_31">
                        <rect id="Rectangle_31" rx="8" ry="8" x="0" y="0" width="140" height="171">
                        </rect>
                    </svg>

                        Get a Free Pack
of Dilmah tea
of your choice.

and the script to flip the cards and see if they are matched is in the script.js file
class AudioController{
    constructor() {
        this.flipSound = new Audio('Assets/audio/flip.wav');
        this.matchSound = new Audio('Assets/audio/match.wav');

    }
    flip(){
        this.flipSound.play();
    }
    match(){
        this.matchSound.play();
    }
}
let hasFlippedCard = false;
let firstCard, secondCard;
class MixORMatch{
    constructor(totalChances,cards) {
        this.cardsArray = cards;
        this.totalChances = totalChances;
        this.chancesRemaining = totalChances;
        this.chances = document.getElementById('chances-remaining');
        this.audioController = new AudioController();

        //shuffle cards
        this.shuffleCards();

        //start game
        this.cardToCheck = null;
        this.totalClicks = 0;
        this.chancesRemaining = this.totalChances;
        this.matchedCards = [];

    }
    startGame(){
        this.cardToCheck = null;
        this.totalClicks = 0;
        this.chancesRemaining = this.totalChances;
        this.matchedCards = [];

    }

    flipCard(card) {
        if(this.canFlipCard(card)){
            this.audioController.flip();
            this.totalClicks++;
            card.classList.add('visible');

            //first click
            hasFlippedCard = true;
            firstCard = this;

            if (this.canFlipCard(card)){
                this.checkForCardMatch(card);
            }else{
                this.cardToCheck = card;
            }

        }else{
            //second click
            hasFlippedCard = false;
            secondCard = this;
            console.log("flipped")
        }
    }
    hideCards() {
        this.cardsArray.forEach(card=> {
            card.classList.remove('visible');
            card.classList.remove('matched');
        });
    }
    checkForCardMatch(card) {
        if (this.getCardType(card)===this.getCardType(this.cardToCheck)){
            this.cardMatch(card,this.cardToCheck);
        }else{
            this.cardMisMatch(card,this.cardToCheck);
        }
        this.cardToCheck = null;
    }
    cardMatch(card1,card2){
        this.matchedCards.push(card1);
        this.matchedCards.push(card2);
        card1.classList.add('matched');
        card2.classList.add('matched');
        this.audioController.match();
        if(this.matchedCards.length === this.cardsArray.length){
            console.log("win");
        }
    }

    cardMisMatch(card1,card2){
        setTimeout(()=>{
            card1.classList.remove('visible');
            card2.classList.remove('visible');
        },1000);
    }
    shuffleCards(cardsArray){
       let cardscount = cardsArray,length;
        for(let i =cardscount; i>0; i--){
            let randIndex = Math.floor(Math.random() * (i+1));
            cardsArray[randIndex].style.order = i;
            cardsArray[i].style.order = randIndex;
        }
    }

    getCardType(card){
        return card.getElementsByClassName('match-value')[0].src;
    }

    canFlipCard(card){
         return true;//(!this.busy && !this.matchedCards.includes(card) && card!== this.cardToCheck);
    }

}
function ready(){
    let cardDeck = Array.from(document.getElementsByClassName('deck'));
    let cards = Array.from(document.getElementsByClassName('card'));
    let game = new MixORMatch(3,cards);
   /* overlays.forEach(overlay => {
        overlay.addEventListener('click',()=>{
            overlay.classList.remove('visible');
            //game.startGame();
        });
    });*/

    cards.forEach(card =>{
        card.addEventListener('click',()=>{
            //flipping card game
            game.startGame();
            game.flipCard(card);

        });
    });
}

if(document.readyState === 'loading'){
    document.addEventListener('DOMContentLoaded',ready);
}else{
    ready();
}

I'm not sure why I'm getting this error I have defined the cards to match class as "match-value" which is the image, I the get image src and check whether it matches the one the card user has flipped earlier. But when I flip both cards I get the above mentioned error. In the script in "getCardType".
Uncaught TypeError: Cannot read property 'getElementsByClassName' of null

A: The issue is in your getCardType() function. You wrote:
getCardType(card) {
    return card.getElementsByClassName('match-value')[0].src;
}

It should be:
getCardType(card){
    return document.getElementsByClassName('match-value')[0].src;
    //     ^--- you wrote 'card' here
}


Q: How to set the value of the SelectedItem property in devexpress combobox BarItem? It is example Combobox in which everything is working good and selected value varies depending on changes CurrentPlanSet.
       <dxe:ComboBoxEdit ItemsSource="{Binding PlanSets, Mode=TwoWay}"
                               DisplayMember="Name"
                               ValueMember="Name"
                               SelectedItem="{Binding CurrentPlanSet, Mode=TwoWay}"
                               />

In this example the selected value does not change depending on CurrentPlanSet changes.
<dxb:BarEditItem Content="Plan Sets" EditWidth="350">
                <dxb:BarEditItem.EditStyle>
                    <Style TargetType="{x:Type dxe:ComboBoxEdit}">
                        <Setter Property="SelectedIndex" Value="{Binding     CurrentPlanSet, Mode=TwoWay}"/>
                    </Style>
                </dxb:BarEditItem.EditStyle>
                <dxb:BarEditItem.EditSettings  >
                    <dxe:ComboBoxEditSettings ItemsSource="{Binding PlanSets, Mode=TwoWay}" ValueMember="Id" DisplayMember="Name" />
                </dxb:BarEditItem.EditSettings>
            </dxb:BarEditItem>

How to correctly set the value of the SelectedItem property in second code example?

A: SelectedIndex is not the same as SelectedItem.
This is the same as with the default WPF Controls.
SelectedIndex is the Index of the CollectionItem, you have selected/set selected (Integer). The SelectedItem is the Item Object itself.
Example:
Lets take this Collection: new ObservableCollection<string>(){ "String1", "String2", String3"}
If the SelectedItem is/should be String1 the SelectedIndex is 0.
So just replace
<Setter Property="SelectedIndex" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/>

with
<Setter Property="SelectedItem" Value="{Binding CurrentPlanSet, Mode=TwoWay}"/>


Q: Coroutines: Can't return value after finish work In my android app I need after executed some long network operation to return result (e.g. after 10 seconds)
here snippet:
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

 GlobalScope.launch(Dispatchers.Main) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                return response
            }

but I get compile error in this line:
return response

Error message:
'return' is not allowed here

A: It doesn't work like that. Your return is not allowed there because you are inside a coroutine context on those { }
But actually the best way to do it is to create some method and handle that response instead of returning it. On your case I'm a little confused:
Transform:
GlobalScope.launch(Dispatchers.Main) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                return response
            }

Into:
GlobalScope.launch(Dispatchers.IO) {
                lateinit var response: Response<Void>
                response = executeOperations.await()
                 withContext(Dispatchers.Main){
                  handleResponse(response)
               }
            }

Plus, your heavy work musn't happen in the Dispatchers.Main but in Dispatchers.IO


Q: How do I do a Quicksearch or autocomplete on a selectbox populated from a database? I have a select box populated a from a database and would like to do a quicksearch or a autocomplete to search the elements inside the select box. Below is my code:
    <?
           print("
");
        print("
");
            print("");
            //print("
");  //
            print("
Search: <input type='text' id='searchFILE' size='33' autocomplete='off' />
");
            print("<select name='lktyp' id='lktypSearch' size='10' >");
            //Create new SQL object
            $db = new NSC_SQL($db2config);
            $db->from($bllcust1,"BCUST#,BNAME");
            $db->order("BCUST#");
            $db->select();
            $results = $db->fetchAssoc();
            $db->dspSQL();
            foreach($results as $row)
            {
                $bcust = trim($row['BCUST#']);
                $bname = trim($row['BNAME']);
                print("<option value='$bcust'>$bcust ~ $bname</option>");
            }
            print("</select>");
            print("
");
            print("	");
        print("
");
        print("
");
            print("");
            //print("<input type='submit' name='search' value='Search'>");
            print("<input type='button' value='Select' onclick='lkp();'>");
            print("<input type='button' name='cancel' value='Cancel' onClick='parent.$.fancybox.close();'>");
            print("	");
        print("
");
    print("
");

?>

A: The simplest way would be to implement Jquery autocomplete. I won't do the code for you but if you find it difficult create a new question posting some of the code you tried and someone will help.

A: Two nice alternatives to jQuery autocomplete which was already mentioned are Chosen and Select2. Both of these require jQuery or another supported JS framework. jQuery autocomplete and Select2 have great support for remote datasets.


Q: How to export summary statistics of a regression from R studio to Excel I have ran a lm function and produced summary results which I wish to export onto a excel document.
Is there a specific package/code that allows me to do this? If so which is best for report presenting?

A: Let's assume we have model called "mod"
mod <- lm(v1 ~ v2, data= df)
You can use "broom" function.
library(broom)

#create dataframes with results
res_mod <- as.data.frame(tidy(mod))
res_mod2 <- as.data.frame(glance(mod))

#then export as two csvs
write.csv(res_mod, "res_mod.csv")
write.csv(res_mod2, "res_mod2.csv")


Q: Heroku Dataclip, How to export date column into XLS When a column contains a Date field, the dataclip displays it. When the "Export/Share" link is clicked and XLS selected, the resulting Date column is treated like a TEXT column in XLS.
Changing the Format in XLS does not seem to have an effect on it.
Is there a proper format for export that will make it into a Date cell?
I have tried 'MM-DD-YYY', 'MM/DD/YYY' and left it as default display (which puts the date and time in the column).
None of these are "dates" in XLS.
Thanks

A: I have done some tests and I think dates are exported as YYYY-MM-DD.
I really don't have Excel installed on this computer right now, but I downloaded an xls file from dataclips and imported it on Googlesheets. Dates were correct without any conversion needed.


Q: WordPress: External call to wp-load.php causes CPU and memory spikes One of my websites on my server is causing big CPU and memory spikes. I've been looking for the cause, and I believe that I've found it.
I've been digging in the access logs and every time a peak occurs, there is an external call to wp-load.php. This call looks like this (I've changed a few values):
52.56.220.94 - - [16/Oct/2018:12:57:20 +0200] "POST /wp-load.php?pubkey=c924c49878aec6f8295874888c0d14c1&bvTime=1539687440&bvVersion=0.1&bvMethod=getdata&sha1=true&sig=6d3a8735567bd7baa7e5e12af885afab0d6a399d HTTP/1.0" 200 4809 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

The calls come from a limited range of IP-addresses:
52.56.220.94
54.179.150.144
45.77.97.238
Does anyone recognize this and/or does anyone know a way to track down to which piece of software this call belongs to?
Any help is highly appreciated.

A: You should add the following to your .htaccess file:
<Files "wp-load.php">
  Order Deny,Allow
  Deny from all
  Allow from localhost
  Allow from 127.0.0.1
</Files>

I can't think of a reason to bootstrap WordPress from an external server ....


Q: count  in div after drop event I have 5 pieces of a image in a div sortable1 which i have to drag and drop in another div sortable2to complete the image. After the image is dropped in another container it will stick to the previous image present in this container.http://jsfiddle.net/binit/JnYB9/
After every drop event i want to check whether all the 5 pieces are collected in 2nd div and if it is yes then change button text. Something like this.
if $('#sortable2').find('img').length == 5:
    document.getElementById('btn-start').text = "end";

But i don't know where to use this logic in my code or what should be the syntax
My code:
javascript
$(function() {

  $( "#sortable1" ).sortable({
  connectWith: "div"
  });

  $( "#sortable2" ).sortable({
  connectWith: "div",
  change: function( event, ui ) {
  var theID = ui.item.attr('id');
  ui.item.addClass(theID + '-style');
 }
 });

 });

HTML

  Start

A: Use stop function of sortable evry time you sort the element from div with id sortable1.
Working Demo
stop: function( event, ui ) {
   if($('#sortable2').find('img').length==5)
   $('#btn-start').html("end");
 }

A: You can write a callback function on the sortable method like the following:
 $( "#sortable1" ).sortable({
   connectWith: "div",
   stop: function() {
           // your logic goes here
   }
 });

You can also use the start callback.


Q: Functions work even when headers have not been included - Visual Studio I routinely notice while working in Visual C++ that some functions work even when their headers have not been included. For example, tolower() works even when ctype.h is not included.
This behaviour causes problems for me when I participate in online programming competitions, the program works fine and dandy when I run it on my computer but on submission, gives a function not defined error. Is there any way to stop this behaviour?

A: Possible explanations:

*

*You have your warning level turned right down.

*You're using precompiled headers that are including the right files.

A: The declaration of your tolower() is in fact included. It could be so in one of the following ways:

*

*<cctype> or <ctype.h> is included in one of the headers (even standard headers) that you have included. The standard does not forbid standard headers to include other standard headers

*one of the headers you have included has the declaration of that funciton. For example, <algorithm> could have int tolower(int); somewhere in its code.
You cannot forbid this behavior. What you can do is learn where the function has to be defined/declared and never rely on inclusion of that header by other headers. You know where tolower is declared, so do include <cctype> every time you use this function.


Q: Confused about proof that $G\bmod K$ is a group THM: If $K$ is normal to $G$, then $G/K$ := {$aK : a \in G$}, called $GmodK$, is a group under the operation $aK$*$bK$ = $abK$, for all $a$, $b$ $\in G$.
Proof: using the normality of $K$ I was able to show the sets $aKbK$ and $abK$ are equal.
$aKbK = ${$akbk' : k,k' \in K$} = {$abk''k' : k'',k' \in K$} = {$abk''' : k''' \in K$}, since $K$ is normal.
My professor then writes: " $\phi : G \rightarrow G/K$, $\phi:a \longmapsto ah$ Is a homomorphism."
What I'm confused about: what is the map $\phi$? I showed $aKbK = abK$ which seems to me is the property $f(xy) = f(x)f(y)$, so yeah I can see how taking an element $a \in G$ and multiplying that coset with the coset of a another distinct element in $G$ will produce the coset of the product of those elements in $G$, and that is exactly a homomorphism? But what exactly do I say the map $\phi$ is? The map which induces a coset?
Thanks for the help.


Q: WPF control similar to ObjectListView I'm writing an application using WPF, and I need to make something that looks like this (see image):

What control should I use for this?

A: If you don’t need the groupings (the “Hire as chef” and “Seek dinner invitation” headings), then DataGrid should get you close. You can bind its ItemsSource to your collection of items, and define custom columns bound to your items’ properties.
For example, you can use a DataGridTextColumn for “Occupation”, DataGridCheckBoxColumn for “Tells Jokes?”, and DataGridTemplateColumn for more complex properties which require a custom DataTemplate to visualize, such as the main “Person” column or “Cooking skill”.
Edi: It appears that the DataGrid does support grouping as well.

A: You should go for ListView
http://msdn.microsoft.com/en-us/library/ms754027(v=vs.90).aspx


Q: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function Problem: React Hook "React.useEffect" is called in function "selectmenu" which is neither a React function component or a custom React Hook function.
Target: I want to Mount Component('component DidMount/WillUnmount) (using useEffect()) only when I click on a button, rather than, mounting while the file (or whole Component) is being loaded.

Actual Goal: I want to select(or highlight) a file (custom ) on click. But when the user clicks outside the dimensions of the file (), then the selected file should get deselected (remove highlight).
export default function Academics() {
  let [ ismenuselected, setmenuselection] = useState(0)

  const selectmenu = () => {

    console.log("Menu to Select")

    React.useEffect(() => {
      console.log('Component DidMount/WillUnmount')

      return () => {
         console.log('Component Unmounted')
      }
    }, [isfolderselected]);
  }

  return (

  )
}

Note:

*

*I've tried with the UPPER case of SelectFolder #56462812. Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

*I want to try something like this. But with a click of a button (useEffect() should invoke onClick event).

A: I think I got what you're trying to accomplish. First, you can't define a hook inside a function. What you can do is trigger the effect callback after at least one of its dependencies change.
useEffect(() => {
  // run code whenever deps change
}, [deps])

Though for this particular problem (from what I understood from your description), I'd go something like this:
export default function Academics() {
  let [currentOption, setCurrentOption] = useState()

  function handleSelectOption(i) {
    return () => setCurrentOption(i)
  }

  function clearSelectedOption() {
    return setCurrentOption()
  }

  return (options.map((option, i) =>
    <button
      onClick={handleSelectOption(i)}
      className={i === currentOption ? 'option option--highlight' : 'option'}
      onBlur={clearSelectedOption}
    ></button>
  ))
}


Q: Remove UIBarButtonItem from master view controller when detail view controller is visible I am converting my view controllers into a split view controller with a Universal Storyboard to show two views on screen at the same time, which will only appear on iPad - only one will be visible on iPhone. I have a situation where a UIBarButtonItem is only relevant when only one view controllers is on screen. I want this button removed or hidden when both view controllers in the split view controller are visible.
I cannot use Size Classes to do this, since the button I want removed is in the master view controller (actually I have button in both the master and detail that should be removed), which won't have a size class of Regular w Regular h. Plus Interface Builder doesn't provide an "Installed" option for UIBarButtonItems, and I cannot check size classes in code because the app will also run on iOS 7.
How can I remove/hide a UIBarButtonItem when both the master and detail view controller are on screen? Or I could not add this button in IB, then add it in code when deemed appropriate, but how would I know if both view controllers will be on screen?

A: Here's a nice solution that works great for iOS 8 and iOS 7 on iPhone and iPad. You simply detect if there is a split view controller and if so, check if it's collapsed or not. If it's collapsed you know only one view controller is on screen. Knowing that info you can do anything you need to.
//remove right bar button item if more than one view controller is on screen
if (self.splitViewController) {
    if ([UISplitViewController instancesRespondToSelector:@selector(isCollapsed)]) {
        if (!self.splitViewController.collapsed) {
            self.navigationController.navigationBar.topItem.rightBarButtonItem = nil;
        }
    } else {
        self.navigationController.navigationBar.topItem.rightBarButtonItem = nil;
    }
}


Q: Should I use ANOVA or paired t-test? For my statistical analysis, I want to find out:
If there is a statistical significant difference in PM2.5 levels in 2019 and in 2020**.
If there is a statistical significant difference in PM10 levels in 2019 and in 2020**.
If there is a statistical significant difference in NO2 levels in 2019 and in 2020**.
If there is a statistical significant difference in O3 levels in 2019 and in 2020**.
So as you can see, I'm not comparing the pollutants with each other – there's no reason to do so in my study. I'm just comparing 2019 and 2020, using 4 different pollutants. Therefore I am confused as to whether I should use an ANOVA (would it not just end up comparing NO2 against O3, PM10, PM2.5 and vice versa?) or if I should do four paired t-tests?
(I'm aware their are issues with doing time series, about things being autocorrelated and all that, but for the sake of this analysis I don't need to get into deep complexity. I'm just doing a simple analysis!)
** It's not for the entire year, just for Jan, Feb, March, April but I don't need to break it up by month, I can just compare 2019 to 2020.If there is an easy way to to break it down by month, please do mention, but it's not necessary!


Q: Is it possible to define a scoped callback function in a C struct? The C struct AvCodecContext in libav (ffmpeg) has a callback function called get_format. I have a class where each instance has its own AvCodecContext instance, so each one will have an specific callback.
Is it possible to create different callbacks for each instance?
Here's what the callback should look like:
    enum AVPixelFormat get_hw_format(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts)
    {
        const enum AVPixelFormat *p;

        for (p = pix_fmts; *p != -1; p++) {
            if (*p == hw_pix_fmt)
                return *p;
        }

        fprintf(stderr, "Failed to get HW surface format.\n");
        return AV_PIX_FMT_NONE;
    }

each callback should have a different AVPixelFormat hw_pix_fmt.
If the project was C++ only, I could use lambda functions, but it's not.
Is there a way?


Q: How do I find the sampling distribution for variance from sampling distribution of $\bar{X}$? Suppose some people are asked to each randomly pick 30 apples and put into a bag.
In this case, the weights of all the bags will surely be different because different apples weigh differently. So for one of the bag, if let $X_1$ be the weight of the first apple, $X_2$ be the second apple, and all the way to $X_{30}$ the weight of the $30th$ apple, then $X$, which is the weight of the bag is $X=X_1+X_2+\cdots+X_{30}$.
Now, if I want to approximate the sampling distribution of $\bar{X}$, I presume that I can simply just say $\bar{X}=\frac{1}{30}\sum _{ i=1 }^{ 30 }{ X_{ i } } $. Is this right?
In the problem, I need to continue to find the sampling distribution for the variation of the weights of the bags from the approximated sampling distribution of $\bar{X}$ that I have found. I am stuck at this part. I don't see how $\bar{X}$ links with the variance of the bag weights.

A: Look up Central Limit Theorem.  Often, the heuristic is to sample from a distribution with a sample size of at least 30.  The CLT doesn't require that the $X_i$'s are IID normal random variables, they just need to be IID random variables from some fixed distribution with mean $\mu$ and variance $\sigma^2$.  CLT then says that the sampling distribution of the mean of a sample of size $n$ (for large enough $n$, where $n\geq 30$ is one often used heuristic) is approximately normal with mean $\mu$ and variance $\sigma^2/n$, where recall that the $\mu$ and $\sigma^2$ come from the distribution of the underlying population (which, in this case, is the distribution of the weights of apples).
To estimate $\mu$ from the data, we generally use $\bar{X}$.  To estimate $\sigma^2$ from data, we generally use $s^2$, which divides by $n-1$ instead of $n$.  Using $s^2$ makes the distribution tough to deal with, but here if your population is normally distributed then the sampling distribution is approximately a $t$ distribution with $n-1$ degrees of freedom.

A: The simplest way to make inference about the sampling distribution of $\bar{X}$ is to first consider the population parameters. If each of your $X_n$ is i.i.d $\sim N(\mu,\sigma^2)$, then the sampling distribution of the sample mean is $\sim N(\bar{X},\frac{\sigma}{\sqrt{n}})$.


Q: How to print value of a Variable using its memory address? Suppose 0xfe2200 is the memory address of a variable var2 and I want to display the value stored in it, E.g
cout<< "Value stored in the given address is :  " << 0xfe2200 << "    ";

I tried following but all in vain
cout << "Value is :  " << *0xfee2200 << " ;
cout << "Value is :  " << &0xfee200 << "  ;

A: Assuming the address points to int, you may do:
cout << "Value is :  " << *reinterpret_cast<int*>(0xfee2200);

as literal 0xfee2200 is an interger type whereas you expected a pointer.

A: You have to decide as what type of data you want to interpret the memory content and cast it accordingly:
const char* tmp = "foofoo"; // Valid ptr for this example
const void* address = tmp; // Set to your address

const int* i = reinterpret_cast<const int*>(address);
const unsigned short* us = reinterpret_cast<const unsigned short*>(address);
const char* c = reinterpret_cast<const char*>(address);

std::cout << "i: " << (*i)
          << "\nus: " << (*us)
          << "\nc: " << (*c);

Output:

i: 1718579046
  us: 28518
  c: f


Q: Publish applet with maker webhook I want to publish my applet with a maker webhook to my raspberry pi. For some reason it doesn't allow me to publish the app when I use a maker webhook in it.I'm not sure why it doesn't allow me or if it's even possible at all.
There isn't any error in the applet either as it works perfectly fine in private mode. I also have seen some applets by other users that use the maker webhooks in their applet. So I think it must be possible.
If somebody could answer this question who has published an applet before with webhooks or what I could be doing wrong. Thanks in advance !


Q: I am getting error as unrecognized rule in this lex program %{
#include<stdio.h>
int vowel=0;
%}

%%

[aeiouAEIOU]
{
vowel++;
}

%%

int main()
{
  char str[200];
  gets(str);
  yylex();
  printf("Vowels:",vowel);
}

A: If that is the way you wrote the program, then the error is correct. In Flex, the action for a rule must start on the same line as the pattern.
From the flex manual:

5.2 Format of the Rules Section
The rules section of the flex input contains a series of rules of the form:
 pattern   action

where the pattern must be unindented and the action must begin on the same line.

As written, you have supplied { as a pattern. That's not a valid pattern, and so flex complains.


Q: Is the successor of a non finite ordinal a non finite ordinal? Definition:
$$\alpha \text{ is finite iff } \forall\: \beta \: \text{ordinal}, \: \beta \leq  \alpha\: \text{and}\: \beta \: \neq \emptyset \: \Rightarrow \exists \gamma( \beta=\gamma\cup\{\gamma\}) $$
(definition corrected thanks to suggestion)
Question: Does this hold true ?
$$\alpha \ \  \text{non finite} \Rightarrow \: \alpha + 1 \ \ \text{non finite} $$
If it is true, then a non finite ordinal can have a predecessor but a limit ordinal cannot have a predecessor, am I right ?

A: Your definition is slightly wrong. It merely states that every smaller ordinal is $0$ or a successor, but this much is also true for $\omega$, which is certainly not finite, what with it being the least infinite ordinal.
You can fix this by changing $\forall\beta<\alpha$ to $\forall\beta\leq\alpha$.
Now, to your question, of course that the successor of an infinite ordinal is infinite. If $\alpha$ is infinite there is a witness for the fact that $\alpha$ is not finite, which is either $\alpha$ or some $\beta<\alpha$. This will remain a witness when we consider $\alpha+1$.
Finally, a limit ordinal is defined as an ordinal which is not a successor.1 So again, quite trivially, limit ordinals are not successors.

*

*In some places $0$ is also separated from the limit ordinals, in which case a limit ordinal is a non-zero ordinal which is not a successor.


Q: Registering Entity in Objectify having issue during test cases We have an project developed with Objectify4 and Spring3.1 and deployed and running on GAE and we are using IDE as STS.
When I do project build locally using Maven(cmd mvn install) the test cases are failing and throwing the following exception.
From the exception I observe it is failing while injecting Class1Service service class in test class Class1UnitTest (this is not only in this test class it is giving same exception in every test class wherever we are injecting any service class that extends AbstractBaseImpl).
In the exception stacktrace I see it is pointing to line of registering the Entity class(EntityClassA) in  AbstractBaseImpl.
In the Entitiy class EntityClassA we have used @Mapify, if I remove the @Mapify annotation in the entity class the test case are running without any bean initialisation issues.
I tried building project from STS and also from command still getting the same issue.
From the functionality point of view the application is working fine if I skip the testcases while building.Can anyone see similar issue with the entity having @Mapify defined and getting issue while registering in test case.
Thanks for your time
Here are the details,
EntityClassA.java
@Entity
public class EntityClassA {

    @Index @Mapify( ChildClassAMapper.class )
    private Map<Integer, ChildClassA> intervalToReward = new LinkedHashMap<>();

    @Embed
    public static class ChildClassA extends ClassA {
        private static final long serialVersionUID = 49769454099624971L;
        private int …;
        private long …;

        public ChildClassA(  ) {
            …..
        }
    }

    public static class ChildClassAMapperMapper implements Mapper<Integer, ChildClassA> {

        @Override
        public Integer getKey( ChildClassA value ) {
            return value.getInterval();
        }
    }
}

AbstractBaseImpl.java
@Component
public abstract class AbstractBaseImpl implements BaseService {

    static {
Line-12     ObjectifyService.register( EntityClassA.class );
    }
}

ChallengeServiceImpl.java
@Service
@Slf4j
public class Class1ServiceImpl extends AbstractBaseImpl implements Class1Service {

    // method to store data using objectify..

}

CoreBaseTest.java
@ContextConfiguration(
    locations = { "classpath*:META-INF/spring/core-applicationContext.xml" } )
@RunWith( SpringJUnit4ClassRunner.class )
public abstract class CoreBaseTest {

    private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
        new LocalDatastoreServiceTestConfig().setApplyAllHighRepJobPolicy(),
        new LocalBlobstoreServiceTestConfig(),
        new LocalTaskQueueTestConfig(),
        new LocalMemcacheServiceTestConfig() );
}

Class1UnitTest.java
public class Class1UnitTest extends CoreBaseTest {

    @Resource( name = "class1Service" )
    private Class1Service class1Service;

    //Testcases…

}

core-applicationContext.xml

<bean id="class1Service" class="com.suvs.app.core.spring.services.Class1ServiceImpl" />

Exception
TestCrud(test.core.Class1UnitTest')  Time elapsed: 0.163 sec  <<< ERROR!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test.core.Class1UnitTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'class1Service' defined in URL [file:/Users/suvs/core-app/target/classes/META-INF/spring/core-applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.AssertionError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:443)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:417)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:304)
    ... 32 more
Caused by: java.lang.AssertionError
    at com.googlecode.objectify.impl.translate.CreateContext.enterCollection(CreateContext.java:70)
    at com.googlecode.objectify.impl.translate.CollectionTranslatorFactory.create(CollectionTranslatorFactory.java:49)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52)
    at com.googlecode.objectify.impl.translate.EmbedClassTranslatorFactory.create(EmbedClassTranslatorFactory.java:43)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.MapifyTranslatorFactory.create(MapifyTranslatorFactory.java:62)
    at com.googlecode.objectify.impl.translate.TranslatorRegistry.create(TranslatorRegistry.java:90)
    at com.googlecode.objectify.impl.translate.ClassTranslator.(ClassTranslator.java:52)
    at com.googlecode.objectify.impl.translate.EntityClassTranslator.(EntityClassTranslator.java:46)
    at com.googlecode.objectify.impl.Transmog.(Transmog.java:49)
    at com.googlecode.objectify.impl.ConcreteEntityMetadata.(ConcreteEntityMetadata.java:58)
    at com.googlecode.objectify.impl.Registrar.register(Registrar.java:74)
    at com.googlecode.objectify.ObjectifyFactory.register(ObjectifyFactory.java:180)
    at com.googlecode.objectify.ObjectifyService.register(ObjectifyService.java:62)
    at com.suvs.app.core.spring.services.AbstractBaseImpl.(AbstractBaseImpl.java:12)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
    ... 45 more

A: Does ChildClassA also contain a collection, thus you are trying to nest two embedded collections? It looks like it from that stacktrace. This is not possible in Objectify4. I highly recommend the upgrade to 5.


Q: Segmentation Fault using double pointers I'm getting segmentation fault while handling with double pointer in the below code. I've spent way too much time and couldn't find what the error was.
#include<iostream>
using namespace std;
int main(){
    int *p,**pp,n=2;
    p=new int;
    pp=&p;

    for(int i=0;i<n;i++)
    {
        cin>>*(*(pp+i))>>*(*(pp+i)+1);
    }
    for(int i=0;i<n;i++)
    {
        cout<<*(*(pp+i))<<" "<<*(*(pp+i)+1)<<endl;
    }
    return 0;
}

Not sure if this is a noob question.

A: Maybe this is what you need:
int *p, **pp, n = 2;
p = new int[n * 2];
pp = &p;

for(int i = 0;i < n;i++)
    cin >> *(*pp + n*i + i) >> *(*pp + n*i + i + 1);
for(int i = 0;i < n;i++)
    cout << *(*pp + n*i + i) << " " << *(*pp + n*i + i + 1) << endl;

delete []p;
return 0;


Q: NSURLConnectionDownloadDelegate methods not getting called when downloading files over 50 MB via cellular Supposing I have a snippet of code like this:
[assetDownload downloadWithDelegate:self];

All the three delegate methods are implemented:
– connection:didWriteData:totalBytesWritten:expectedTotalBytes:
– connectionDidResumeDownloading:totalBytesWritten:expectedTotalBytes:
– connectionDidFinishDownloading:destinationURL:

And everything works (the delegate methods get called) fine when there is a WI-FI connection for files of any size, and for files under 50 MB when on cellular network. When the file is bigger and the connection is cellularnone of the methods get called. Is this a normal behavior and what should I do to handle it properly?


Q: using will and will be in proper places I have confusion in a sentence.
If restaurants sell pizza, their sales will double.
or, If restaurants sell pizza, their sales will be doubled.

*

*Will / will be which one is correct and why?

*their sales why we use verb(sale)+s? Although the subject is restaurants which is clearly a plural form of restaurant.
Thank you.

A: A "sale" is a noun in this context, meaning the event of selling something - in this specific context it refers in a general way to the money made from the sale, i.e. "Sales" means "the total amount of money made from all of the sales".

Sales will double. ("double" is a verb)

This refers to the process of that amount doubling, more transactions/sales, etc.

Sales will be double. ("double" is an adjective)

This refers to the fact that the end result/amount will be double ("twice as much as") what it would have been.


Q: peculiar Java 7 Web Start failure I maintain a legacy application that was written with the Java 6 JDK.  We deploy it as a stand alone application downloaded from the web as a JNLP.  The application talks to a servlet that serves up data from a database, and since the data involved can get lengthy, the JNLP app provides a 'progress meter' to show how much data has transferred and how much is left to go.  It was working all just fine - until, apparently, the latest Java 7 update.  Now, when the JNLP application is run, during data transfer from the servlet, the progress meter stops working.  It appears to get hung, yet data is continuing to be transferred (the servlet part is working just fine).  But to our end users, the app appears to fail!  I can run the app locally without Webstart, and it works fine.  Any idea what the problem could be, and how to fix it?.


Q: python create an arbitrary score based off certain criteria I want to create a formula that will create an arbitrary score based on certain variables. For example, given a dataframe with the following columns:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Name': ['Joe', 'Bob'], 'Score': [0.75, 0.8], 'Length': [10, 20]})

I want to create a new column, Result, based off the following criteria, In this order of importance

*

*Length closest to 10 has the most weight

*The highest score has the most weight

*'Bob' has more weight than 'Joe'

Some more info:

*

*Opt. assume that there are more than 2 names, with an option to specify which names are more important than the others

*Score is a decimal from 0 to 1

*Length is an int from 1-200

Basically, I am having trouble coming up with a function that captures these desires weights/importances. What would such a function look like?

A: You can set up a temporary DataFrame with custom columns to sort and use its index to reorder the original:
idx = (df
  .assign(Length=-df['Length'].sub(10).abs(),
          Name=pd.Categorical(df['Name'], categories=['Joe', 'Bob'], ordered=True)
          )
  .sort_values(by=['Length', 'Score', 'Name'], ascending=False)
  .index
)

# reorder values based on priority
sorted_df = df.loc[idx]

Alternative if only some names have a priority:
d = {'Bob': 2}
# in the assign of the previous code
#.assign(
  Name=df['Name'].map(d).fillna(0)
#)

If you want to add a rank instead of sorting:
df.loc[idx, 'rank'] = range(len(df))


Q: how to create VMDK file in Virtualbox for adding USB as a new OS? I have a USB which has OSes on it. Now I want to create VMDK file to use them in VirtualBox.
I read many articles but never found how I can use them. In an article I found the way that:
C:\Program Files\Oracle\VirtualBox > VBoxManage internalcommands createrawvmdk -filename D:\usb.vmdk -rawdisk \\.\physicalDrive<Disk 1> -register

It's not working. I try it without register but nothing happened. If I open my diskmsgmt.msc then they show me the drive's name is Disk 1  Removable
I want to know how I can do this. The problem is that when I run the command the system tells me file not found.
I tried checking the USB. It's working fine. I think that there is may be two reasons for the problem:

*

*The disk name has whitespace so I think it doesn't work because of that.

*I'm missing something in the commands.

Can anyone explain what commands I need to use so that it works for me?
(I tried the commands with VirtualBox not VMware)

A: Simply open a terminal on Linux or a command-line tool on Windows (Win+R cmd) and change directory to your VirtualBox folder.
cd "C:\Program Files\Oracle\VirtualBox"

Then we run the VBoxManage command with the following options to link the USB Drive to a vmdk file (Virtual Machine Disk):
VBoxManage internalcommands createrawvmdk -filename usb.vmdk -rawdisk "path_to_usb"

For example on Linux if I want to save in /home/thomas/.VirtualBox/usb.vmdk a virtual machine disk that links to my USB in /dev/sdb, I type the following line:
VBoxManage internalcommands createrawvmdk -filename /home/thomas/.VirtualBox/usb.vmdk -rawdisk /dev/sdb

On Windows, if I want to save the virtual machine disk in C:\Users\Thomas.VirtualBox\usb.vmdk that links to my USB in in Disk 1 (according to the previous Disk Management), I type the following line:
VBoxManage internalcommands createrawvmdk -filename C:\Users\Thomas\usb.vmdk -rawdisk \\.\PhysicalDrive1

Replace the 1 in \\.\PhysicalDrive1 by YOUR device number of the USB drive (for example \\.\PhysicalDrive2).
If any path contains spaces, write it between quotation marks (") to make it work. Example:
VBoxManage internalcommands createrawvmdk -filename "C:\Documents and Settings\Carletdesiles\.VirtualBox\usb.vmdk" -rawdisk \\.\PhysicalDrive1

That's it, you have done a Virtual Machine disk that should be very tiny (~1KB) and links to your USB drive.
You just need to import this hard drive in VirtualBox and use it as primary hard drive (to boot on) for your new system.


Q: R - How to pass encrypted password in a GET request I am pulling data from a server using this API. In order to get an authToken I need to pass my username and password. The password input description says "Hashed password. May be passed as clear text, or as RSA-encrypted hash
(see above for RSA public key)."
To encrypt the password I am using the below code.
library(openssl)

aqKey <- read_pubkey("public_key.pem")
user_name <- "UserName"
password <- rsa_encrypt(charToRaw(askpass()), aqKey)
pw <- rawToChar(password)

This gives me a string with a bunch of unusable characters that produce a 400 error when used in the URL.
/GetAuthToken?user=USERNAME&encPwd=ˆ Ù\026Õ©1tÐÆ®IßÊ/ÛÅÆwéÙeµèB¾kz–V\t–ü˜ÞO«~=ñcÑªÿC'p‰-zòjEü,\r¯eÑ}d‹ã\fÀ\030DR·W\026Â\022‰Å:™¶í©«cózÆlE\032Ï4$é¹Þ,ù«…s\021…–ì\026}h¯~?\nC\021ôj-†\032K}ò\026

If I use base64_encode() or URLencode() on either password or pw I get a 200 status but do not receive a token. This is equivalent to an incorrect password. When I pass the password as plaintext I get a token.
My question is, how should I be formatting the password once it has been encrypted so that the server will recognize it as an encrypted password?


Q: "Msiexec REINSTALL=ALL REINSTALLMODE=vamus" is not cleaning old entries I created an installer "test.msi" . It is version-1. test.msi contains  2 components "comp1", "comp2"
comp1 contains 2 files "comp1_file1", "comp1_file2"
In version 2 of  test.msi ,
--> a new component added "comp3". It contains 1 file "comp3_file1"
--> "comp1" component is updated. "comp1_file2" file removed and new file "comp1_file3" added  Now it contains 2 files (comp1_file1, comp1_file3)
if i upgrade test.msi from version-1 to version-2 using "msiexec /i test.msi REINSTALL=ALL REINSTALLMODE=vamus", in installation folder still i can see version-1 file "comp1_file2".
if i downgrade from version-2 to version-1 using  "msiexec /i test.msi REINSTALL=ALL REINSTALLMODE=vamus", in installation folder version-2 related files exist (comp3_file1, comp1_file3).
How to remove old entries(components/files) at reinstall time?
i am using installshield 2008 premier edition.

A: Transitive components are the way to go.  MS describes them here: http://msdn.microsoft.com/en-us/library/aa372462%28v=vs.85%29.aspx
To follow up on what Chris said, playing with the reinstallmode can do some nasty things.  This is particularly true if you're including any shared components.  You can backlevel components that other applications are depending on, and you can find yourself prompted to stop seemingly unrelated applications based on files in the shared components being in use.  It's a really good thing to avoid if you possibly can.

A: As Cosmin suggested you cannot remove components during repair, but you can uninstall the previous versions before starting the install process for the new version.
One way to go with InstallShiled 2008 is to create a major upgrade that will do this.
Video Tutorial.
Edit
As Christopher said: There are ways to remove components in minor upgrades / repairs.
Comment below.


Q: Import big xls file into mysql database I want to import big xlsx ( spreadsheet file ) into mysql database.
I did it before by phpmyadmin , but this file is too big ( 205000 rows ).
so when I wanna do it by phpmyadmin,it has taken a long time and wasn't done.
what is best and fast way to import it to mysql database?

A: You can do it using the LOAD DATA command in MySQL:
http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html

Save your Excel data as a csv file (In Excel 2007 using Save As)
Check the saved file using a text editor such as Notepad to see what it actually looks like, i.e. what delimiter was used etc.
Start the MySQL Command Prompt (I usually do this from the MySQL Query Browser – Tools – MySQL Command Line Client to avoid having to enter username and password etc.)
Enter this command:
LOAD DATA LOCAL INFILE ‘C:\\temp\\yourfile.csv’ INTO TABLE database.table FIELDS TERMINATED BY ‘;’ ENCLOSED BY ‘”‘ LINES TERMINATED BY ‘\r\n’ (field1, field2);
[Edit: Make sure to check your single quotes (') and double quotes (") if you copy and paste this code]
Done!

A: You can try use Navicat MySQL. I've done this with 250MB+ xlsx file and Navicat handle it flawlessly without breaking a sweat.
Just make sure your MySQL is configured to be able to receive large amount of data by changing the max_allowed_packet option in your my.ini to a larger amount, say, 128M.

A: Toad for MySQL (Freeware) would be another alternative.


Q: How to return a collection of strings from C# to C++ via COM interop I hav created a com componet for some Display method in C# it returns a String List
as shown below. In v++ i hav used std::lst to catch the return value from Disp() but it
gives compiler error that Disp is not a member of class. I i make return type a s void then
it works fine. what i can modify so that Disp return a List and in main(c++) i have to use
this return value.
Public interface ITest
{
    List<string> Disp();
}

class TestLib:ITest
{
    List<string> Disp()
    {
        List<string> li=new List<string>();
        li.Add("stack");
        li.Add("over");
        li.Add("Flow");

        return li;
    }
}

compiled and created Test.dll successfully and also test.tlb.
 Now in main function that is written in c++
#include<list>
#import "..\test.tlb"
using namespace Test;
void main()
{
    HRESULT hr=CoInitialize(null);

    ITestPtr Ip(__uuidof(TestLib));

    std::list<string> li=new std::list<string>();

    li=Ip->Disp();
}

What's wrong in my code when i try to compile this it shows

'Disp':is not a member of TestLib:ITest

how to solve this plz help me ....when i make it return type as void in Class it works fine .what mistake i did????

A: This just isn't going to work, even if you fix the typos. COM interop doesn't have a standard mapping from List<T> to something in COM, and it certainly won't map it to std::list. Generics aren't allowed to appear in COM interfaces.
UPDATE
I tried using ArrayList as the return type, as that's non-generic I thought maybe the tlb would include type information for it. That didn't work so I tried IList. That didn't work either (the #import statement produced a .tlh file that referred to IList but had not definition for it.)
So as a workaround I tried declaring a simple list interface. The code ends up like this:
[Guid("7366fe1c-d84f-4241-b27d-8b1b6072af92")]
public interface IStringCollection
{
    int Count { get; }
    string Get(int index);
}

[Guid("8e8df55f-a90c-4a07-bee5-575104105e1d")]
public interface IMyThing
{
    IStringCollection GetListOfStrings();
}

public class StringCollection : List<string>, IStringCollection
{
    public string Get(int index)
    {
        return this[index];
    }
}

public class Class1 : IMyThing
{
    public IStringCollection GetListOfStrings()
    {
        return new StringCollection { "Hello", "World" };
    }
}

So I have my own (very simplistic) string collection interface. Note that my StringCollection class doesn't have to define the Count property because it inherits a perfectly good on from List<string>.
Then I have this on the C++ side:
#include "stdafx.h"
#import "..\ClassLibrary5.tlb"

#include <vector>
#include <string>

using namespace ClassLibrary5;

int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(0);

    IMyThingPtr thing(__uuidof(Class1));

    std::vector<std::string> vectorOfStrings;

    IStringCollectionPtr strings(thing->GetListOfStrings());
    for (int n = 0; n < strings->GetCount(); n++)
    {
        const char *pStr = strings->Get(n);
        vectorOfStrings.push_back(pStr);
    }

    return 0;
}

I have to manually copy the contents of the string collection a proper C++ standard container, but it works.
There may be a way to get proper type info from the standard collection classes, so you don't have to make your own collection interfaces, but if not, this should serve okay.
Alternatively, have you looked at C++/CLI? That would work pretty seamlessly, although it still wouldn't convert CLR collections to std containers automatically.

A: There look like there are several typos.  In the C# you declare a class called TestLib, but are trying to construct a TestCls.  In addition, neither the class not the method are public (which should be a compile error at least on Disp, since the interface has to be implemented publicly).

A: Guess: Disp() is not declared public


Q: If, g , h are functions such that f(n) = O(g(n)) and g(n) = O(h(n)) prove f(n) = O(h(n)) I'm currently taking my first discrete math class and I'm having a bit of trouble. This is my first encounter with big Oh and I'm having a bit of trouble understanding this particular problem.
I understand proofing that n <= O(n) because I can mathematically prove that there is such constant that will hold true for all values of n >= k
if f, g , h are functions such that f(n) = O(g(n)) and g(n) = O(h(n))
use the definition of big oh given in class to prove that f(n) = O(h(n))
My answer was
|f(n)| <= U1|g(n)| for all n >= k
|g(n)| <= U2|h(n)| for all n >= j
thus
|f(n)| <= U3|h(n)| for all n >= i
Hence f(x) = O(h(x))
I tried to see the professor in her office hours but she said my proofing was incorrect, but would't really say why. I've spent so long on this I don't even know what to do. Any help would be great...

Okay! Let me try this again!
|f(n)| <= U1|g(n)| for all n >= k
|g(n)| <= U2|h(n)| for all n >= j
let i equal the largest of either k ∨ j.
let U3 equal U1 * U2
f(n) <= U3|h(n)| for all n >= i
thus
f(n) = O(h(n))
Better?

A: Using Big O definition:
f = O(g) iff exist c, n0 > 0 such that forall n >= n0 then 0 <= f(n) <= cg(n)

g = O(h) iff exist k, n1 > 0 such that forall n >= n1 then 0 <= g(n) <= kh(n)

Now take the last unequality and divide all members by c: 0 <= f(n)/c <= g(n) and we can substitute g(n) in the second inequality: 0 <= f(n)/c <= kh(n). Finally multiply all members by c and you obtain 0 <= f(n) <= kch(n) that is the definition of f = O(h):
f = O(h) iff exist j, n2 > 0 such that forall n >= n2 then 0 <= f(n) <= jh(n)

In our case it is: n2 = max(n0, n1) and j = ck.

A: You can use limits interpretation of Bachmann–Landau notations.
Then you can use the following reasoning:

A: If you substitute the second inequalty into the first you should end up with U3 = U1 * U2, but  what you called "i" is the crucial point. I think (but my theoretic days are far away in the past, so I could be wrong) that you could end up elegantly with a n >= argmax{ k, j }.