text:
Q: Unique iOS Device ID Across Applications I'm currently working on a suite of iOS applications that will be using the same server for authentication. The server uses a UDID for device authentication. I'm aware that uniqueIdentifier is now deprecated, so I'm wondering what the best practice is for having a unique identifier across applications? (I know how to generate my own and store it in the keychain, but this will be application specific) I have seen postings about identifierForVendor and identifierForAdvertising

A: The docs say:

[uniqueIdentifier is] deprecated in iOS 5.0. Use the identifierForVendor property of this class or the advertisingIdentifier property of the ASIdentifierManager class instead, as appropriate, or use the UUID method of the NSUUID class to create a UUID and write it to the user defaults database.

A: As we know uniqueIdentifier is deprecated in iOS 5.0 so docs recommend you to use CFUUID
instead.
You can get CFUUID using
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (NSString *)CFUUIDCreateString(NULL,uuidRef);
CFRelease(uuidRef);

Please save the uuidString in user defaults or in other place because you can not generate the same uuidString again.
Hope it helps you.


text:
Q: Empirical Distribution Function with Unknown Sample Size Let $X_1, X_2, ..., X_N$ be a sample from a distribution F, and N a positive integer-valued random variable. Thus, the sample size is unknown. Suppose we define the Empirical Distribution Function as per usual:
$$F_N^*(x) = \frac{1}{N} \sum_{i=1}^N I(X \leq x)$$
for $i=1, 2, ...$, and $I(X \leq x)=1$ if $X \leq x$ and $0$ otherwise.
Are there any well known results about this sort of setup? I know of the elegant result for finding $E(S_N)$, where $S_N = \sum_{i=1}^NX_i$, using $E(S_N)=E\{E(S_N | N)\}$, and using this one can show the above has the same expected value as the regular EDF. Then, if we assume $N=n+N'$ for a known n and another positive integer-valued random variable $N'$, I am inclined to believe one can apply the Weak or Strong Law of Large Numbers for $n \to \infty$ and for a fixed $x$ to obtain Consistency. I am also inclined to believe that uniform convergence under the Glivenko-Cantelli Theorem should also hold under such conditions, but I am unsure.
I am also interested in the multidimensional case of this problem, under the same setup as here. I was hoping someone could shed some light on any of the two.
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mapping of Page allocated to user process in Kernel virtual address space When a page is created for a process (which will be mapped into process address space), will that page be mapped into kernel address space ?
If not, then it won't have kernel virtual address. Then how the swapper will find the page and swap that out, if a need arises ?

A: If we're talking about the x86 or similar (in terms of page translation) architectures, at any given time there's one virtual address space and normally one part of it is reserved for the kernel and the other for user-mode processes.
On a context switch between two processes only the user-mode part of the virtual address space changes.
With such an organization, the kernel always has full access to the current user-mode process, because, again, there's only one current virtual address space at any moment for both the kernel and a user-mode process, it's not two, it's one. So, the kernel doesn't really have to have another, extra mapping for user-mode pages. But that's not the main point.
The main point is that the kernel keeps some sort of statistics for every page that if needed can be saved to the disk and reused elsewhere. The CPU marks each page's page table entry (PTE) as accessed when the page is first read from or written to and as dirty when it's first written to.
The kernel scans the PTEs periodically, reads the accessed and dirty markers to update said statistics and clears accessed and dirty so it can detect a change in them later (of course, if any). Based on this statistics it determines which pages are rarely used or long unused and can be repurposed.
If the "swapper" runs in the context of the current process and if it runs in the kernel, then in theory it has enough information from the kernel (the list of rarely used or long unused pages to save and unmap if dirty or just unmap if not dirty) and sufficient access to the pages of interest.
If the "swapper" itself runs as a user-mode process, things become more complicated because it doesn't have access to another process' pages by default and has to either create a mapping or ask the kernel do some extra work for it in the context of the process of interest.
So, finding rarely used and long unused pages and their addresses occurs in the kernel. The CPU helps by automatically marking PTEs as accessed and dirty. There may need to be an extra mapping to dirty pages if they get saved to the disk not in the context of the process that owns them.


text:
Q: Encoding of Process.StartInfo.Arguments I have a .Net application that fires up a process, passing a long argument list through Process.StartInfo.Arguments.  The new process can only handle 8-bit characters in the arguments passed to its main() function.  Therefore, I've encoded the string in Process.StartInfo.Arguments so that each character is an 8-bit value.
The problem is, the new process doesn't see the same 8-bit values that I've used.  For values less than 128, the value pass through unmolested.  Other values get changed somehow, and in fact, the argument list seen by the new process is often longer than what I'd passed in.
What encoding is being used to translate the arguments as they're passed to the new process? Can I modify that encoding?
I see the encodings associated with the process' standard output and standard error; I assume those are irrelevant.

A: This is not something you can fix in .NET code.  The .NET Process class as well as Windows uses Unicode.  The conversion from Unicode to an 8-bit char string happens inside the C Runtime Library embedded in the program you started.  That conversion is based on the current system code page, it uses the WideCharToMultiByte() API function with CodePage = CP_ACP.  There is no way to change that conversion, short from changing the system code page.  Which has drastic effects on the entire operating system.
Of course this is a lossy conversion, it can only handle characters that are defined in the code page.  If you pass it an argument that contains a Unicode character that cannot be represented in the code page then the program will see a question mark in that string.  No amount of string manipulation that you could do in your .NET code can prevent this, short from omitting or substituting that character.  But then you are not passing it the same string anymore.


text:
Q: Grouping by year - mySQL I have a mySQL database with a date field.
I need to find what years are in the entries.
For example. If there are 5 entries which are in 2014, and 1 in 2015. I would like 2014 and 2015 output.
I think this needs to be done by GROUP BY which I have tried. I am just now not sure how to complete an inner query, which is what I think needs to be done.
SELECT field_id_34 AS start_date
FROM exp_channel_data
WHERE channel_id = 5
GROUP BY YEAR(field_id_34)

Can someone tell me if this is what needs to be done? and possibly how?

A: If you want to know the distinct years represented in your data, then you probably want something like this:
SELECT distinct year(field_id_34) AS year
FROM exp_channel_data
WHERE channel_id = 5

I have no idea what field_id_34 is, but I'm inferring from your post that it is a date field. Also, I assume you have reasons for your WHERE filter, although I do not know what those reasons are. But I trust you can fill in those details on your end.


text:
Q: I am getting a TypeError for using the 'in' keyword on an object? I am attempting to write a helper function for myself to check if a property is inside of a given OBJECT. For my own use case, if I come across an array, then I only have to obtain the first (0 index) array to continue. My helper function is to return a boolean value since it is only checking to see if the provided string will work (or not).
Given the OBJECT:
{'object': {
        "promotion": {
            "items": [{
                "startAndEndDate": {
                    "startDate": "2017-11-10",
                    "endDate": "2017-11-29"
                },
                "amount": {
                    "discount": 12
                }
            }]
        }
    }
};

My function:
var propertyInObjectFuncUtil = function (string, obj) {
            var substringArray = string.split('.');

            if (substringArray.length) {
                try {
                    substringArray.reduce(function (prev, curr) {
                        if (curr in prev) {
                            return prev[curr];
                        } else if (curr in prev[0]) {
                            return prev[0][curr];
                        } else {
                            throw ('These are not droids you are looking for...');
                        }
                    }, obj);

                    return true;
                } catch (error) {
                    console.error(error);
                    return false;
                }

            }
        };

Attempting to make it work with the following:
var example1 = propertyInObjectFuncUtil('object.promotion.items.amount.discount',obj) // true
var example2 = propertyInObjectFuncUtil('object.promotion.itemss',obj) // false
var example3 = propertyInObjectFuncUtil('object.promotion.items.startAndEndDate.endDates',obj) //false

However I am getting this TypeError:
TypeError: Cannot use 'in' operator to search for 'itemss' in undefined

A: As the error message says, the in operator cannot be used when the right hand side is undefined, it only works on objects. So add a check for those:
if (Object(prev) === prev && curr in prev) {
    return prev[curr];
} else if (Array.isArray(prev) && Object(prev[0]) === prev[0] && curr in prev[0]) {
    return prev[0][curr];
} else {
    throw new Error('These are not droids you are looking for...');
}

A: itemss witten with 2 's' does not exist, you cannot iterate over an undefined value.
add a check for null/undefined and you should be fine.

A: Your issue occurs when you use an invalid path. If your path is invalid, then curr in obj will be false, thus making you check the next condition. Your first example is working fine, however, your others are not. Consider the values of prev over multiple iterations for the path:
'object.promotion.itemss'

First, prev starts off as:
{
  'object': {
    "promotion": {
      "items": [{
        "startAndEndDate": {
          "startDate": "2017-11-10",
          "endDate": "2017-11-29"
        },
        "amount": {
          "discount": 12
        }
      }]
    }
  }
}

You then check if 'object' is in this object, which is it, so you update prev.
Next iteration your prev is now:
{
  "promotion": {
    "items": [{
      "startAndEndDate": {
        "startDate": "2017-11-10",
        "endDate": "2017-11-29"
      },
      "amount": {
        "discount": 12
      }
    }]
  }
}

You then check to see if 'promotion' is in this object using the first condition of your if, it is, so you update prev.
Third iteration, prev is now:
{
  "items": [{
    "startAndEndDate": {
      "startDate": "2017-11-10",
      "endDate": "2017-11-29"
    },
    "amount": {
      "discount": 12
    }
  }]
}

You now first check to see if 'itemss' is in this object using your first condition in your if. It is not. So you then check your second condition:
} else if (curr in prev[0]) {

The issue is here. prev[0] is trying to access key 0 in your prev object (shown above), however, this key doesn't exist, so prev[0] evaluates to undefined. Using curr in undefined will throw an error as this isn't a valid use case of in. Consider checking if prev[0] is defined (and an object) before using it with the in operator, as shown in this answer


text:
Q: Sciposter setting A0 page dimensions I'm doing my first A0 poster with LaTeX; after some experiences with web examples I´m using a sciposter template (with multicols and sections) which I find very simple; but when I run it I get a PDF file with all the information there but with 1 third of the page all white;
first I assume that geometry package, for setting the page dimensions, would solve the problem, but it seems that nothing works; just need a full page poster… but actually when using \usepackage{fullpage} nothing happens; can somebody please help me out?
\documentclass{sciposter}
\usepackage[latin1]{inputenc}
\usepackage[portuges]{babel}
\usepackage[centertags]{amsmath}
\usepackage{hyperref,amsfonts,multicol}
\usepackage[paperwidth=84cm,paperheight=120cm,centering,textwidth=74cm,textheight=100cm,left=2cm,top=2cm]{geometry}
\hypersetup{pdfpagelayout=SinglePage}
\usepackage{graphicx,colortbl}
\pagestyle{plain}
%\usepackage{fullpage}

A: You don't need geometry, as sciposter has support for A0 paper:
\documentclass[a0]{sciposter}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage[portuges]{babel}

\usepackage[centertags]{amsmath}
\usepackage{amsfonts,multicol}
\usepackage{graphicx,colortbl}

\usepackage{hyperref}
\hypersetup{pdfpagelayout=SinglePage}

\pagestyle{plain}

Note that T1 encoding is recommended for languages with many accented letters and that hyperref should generally be loaded last.


text:
Q: I am unable to fetch the subscription ID from my Google Play Store Console Giving Error Item Not Found I received a message when i going to purchase my subscription from my android app.  Check where i am going to mistake.
i define this code sperate java file config.java
public static final String SUBSCRIPTION_ID = "1monthsubscription";
public static final String MERCHANT_KEY = "xxxxxxxxxxxxxxx" ; // PUT YOUR MERCHANT KEY HERE;
public static final long   SUBSCRIPTION_DURATION = 30; // PUT SUBSCRIPTION DURATION DAYS HERE;

and that is my LoadActivity.java
package com.enjoykids.vod.ui.activities;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.vending.billing.IInAppBillingService;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.Constants;
import com.anjlab.android.iab.v3.TransactionDetails;
import com.greenfrvr.rubberloader.RubberLoaderView;
import com.enjoykids.vod.Provider.PrefManager;
import com.enjoykids.vod.R;
import com.enjoykids.vod.api.apiClient;
import com.enjoykids.vod.api.apiRest;
import com.enjoykids.vod.config.Global;
import com.enjoykids.vod.entity.ApiResponse;
import com.enjoykids.vod.entity.Channel;
import com.enjoykids.vod.entity.Poster;

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

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class LoadActivity extends AppCompatActivity {

private PrefManager prf;
IInAppBillingService mService;
private BillingProcessor bp;
private boolean readyToPurchase = false;
private static final String LOG_TAG = "iabv3";
private static final String MERCHANT_ID=null;

private  Integer id;
private String type;

ServiceConnection mServiceConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name,
                                   IBinder service) {
        mService = IInAppBillingService.Stub.asInterface(service);

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    int time = 3000;
    Uri data = this.getIntent().getData();
    if (data==null){
        Bundle bundle = getIntent().getExtras() ;
        if (bundle!=null) {
            this.id = bundle.getInt("id");
            this.type = bundle.getString("type");
            time = 2000;
        }
    }else{
        if (data.getPath().contains("/c/share/")){
            this.id=Integer.parseInt(data.getPath().replace("/c/share/","").replace(".html",""));
            this.type = "channel";
            time = 2000;
        }else{
            this.id=Integer.parseInt(data.getPath().replace("/share/","").replace(".html",""));
            this.type = "poster";
            time = 2000;
        }
    }

    prf= new PrefManager(getApplicationContext());
    initBuy();
    ( (RubberLoaderView) findViewById(R.id.loader1)).startLoading();
    Timer myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            // If you want to modify a view in your Activity
            LoadActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    checkAccount();

                }
            });
        }
    }, time);

    prf.setString("ADMIN_REWARDED_ADMOB_ID","");

    prf.setString("ADMIN_INTERSTITIAL_ADMOB_ID","");
    prf.setString("ADMIN_INTERSTITIAL_FACEBOOK_ID","");
    prf.setString("ADMIN_INTERSTITIAL_TYPE","FALSE");
    prf.setInt("ADMIN_INTERSTITIAL_CLICKS",3);

    prf.setString("ADMIN_BANNER_ADMOB_ID","");
    prf.setString("ADMIN_BANNER_FACEBOOK_ID","");
    prf.setString("ADMIN_BANNER_TYPE","FALSE");

    prf.setString("ADMIN_NATIVE_FACEBOOK_ID","");
    prf.setString("ADMIN_NATIVE_ADMOB_ID","");
    prf.setString("ADMIN_NATIVE_LINES","6");
    prf.setString("ADMIN_NATIVE_TYPE","FALSE");
}

private void checkAccount() {

    Integer version = -1;
    try {
        PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
        version = pInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (version!=-1){
        Integer id_user = 0;

        if (prf.getString("LOGGED").toString().equals("TRUE")) {
            id_user = Integer.parseInt(prf.getString("ID_USER"));
        }
        Retrofit retrofit = apiClient.getClient();
        apiRest service = retrofit.create(apiRest.class);
        Call<ApiResponse> call = service.check(version,id_user);
        call.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                updateTextViews();
                if (response.isSuccessful()){
                    for (int i = 0; i < response.body().getValues().size(); i++) {
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_REWARDED_ADMOB_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_REWARDED_ADMOB_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_INTERSTITIAL_ADMOB_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_INTERSTITIAL_ADMOB_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_INTERSTITIAL_FACEBOOK_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_INTERSTITIAL_FACEBOOK_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_INTERSTITIAL_TYPE") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_INTERSTITIAL_TYPE",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_INTERSTITIAL_CLICKS") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setInt("ADMIN_INTERSTITIAL_CLICKS",Integer.parseInt(response.body().getValues().get(i).getValue()));
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_BANNER_ADMOB_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_BANNER_ADMOB_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_BANNER_FACEBOOK_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_BANNER_FACEBOOK_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_BANNER_TYPE") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_BANNER_TYPE",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_NATIVE_FACEBOOK_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_NATIVE_FACEBOOK_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_NATIVE_ADMOB_ID") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_NATIVE_ADMOB_ID",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_NATIVE_LINES") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_NATIVE_LINES",response.body().getValues().get(i).getValue());
                        }
                        if ( response.body().getValues().get(i).getName().equals("ADMIN_NATIVE_TYPE") ){
                            if (response.body().getValues().get(i).getValue()!=null)
                                prf.setString("ADMIN_NATIVE_TYPE",response.body().getValues().get(i).getValue());
                        }
                    }
                    if (response.body().getValues().get(1).getValue().equals("403")){
                        prf.remove("ID_USER");
                        prf.remove("SALT_USER");
                        prf.remove("TOKEN_USER");
                        prf.remove("NAME_USER");
                        prf.remove("TYPE_USER");
                        prf.remove("USERN_USER");
                        prf.remove("IMAGE_USER");
                        prf.remove("LOGGED");
                        Toasty.error(getApplicationContext(),getResources().getString(R.string.account_disabled), Toast.LENGTH_SHORT, true).show();
                    }
                    if (id!=null && type !=null){
                        if (type.equals("poster"))
                            getPoster();
                        if (type.equals("channel"))
                            getChannel();
                    }else{
                        if (response.body().getCode().equals(200)) {
                            if (!prf.getString("first").equals("true")){
                                Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                finish();
                                prf.setString("first","true");
                            }else{
                                Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                finish();
                            }
                        }else if (response.body().getCode().equals(202)) {
                            String title_update=response.body().getValues().get(0).getValue();
                            String featurs_update=response.body().getMessage();
                            View v = (View)  getLayoutInflater().inflate(R.layout.update_message,null);
                            TextView update_text_view_title=(TextView) v.findViewById(R.id.update_text_view_title);
                            TextView update_text_view_updates=(TextView) v.findViewById(R.id.update_text_view_updates);
                            update_text_view_title.setText(title_update);
                            update_text_view_updates.setText(featurs_update);
                            AlertDialog.Builder builder;
                            builder = new AlertDialog.Builder(LoadActivity.this);
                            builder.setTitle("New Update")
                                    //.setMessage(response.body().getValue())
                                    .setView(v)
                                    .setPositiveButton(getResources().getString(R.string.update_now), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            final String appPackageName=getApplication().getPackageName();
                                            try {
                                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                                            } catch (android.content.ActivityNotFoundException anfe) {
                                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
                                            }
                                            finish();
                                        }
                                    })
                                    .setNegativeButton(getResources().getString(R.string.skip), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!prf.getString("first").equals("true")){
                                                Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                                                startActivity(intent);
                                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                                finish();
                                                prf.setString("first","true");
                                            }else{
                                                Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                                                startActivity(intent);
                                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                                finish();
                                            }
                                        }
                                    })
                                    .setCancelable(false)
                                    .setIcon(R.drawable.ic_update)
                                    .show();
                        } else {
                            if (!prf.getString("first").equals("true")){
                                Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                finish();
                                prf.setString("first","true");
                            }else{
                                Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.enter, R.anim.exit);
                                finish();
                            }
                        }
                    }
                }else {

                    if (id!=null && type !=null){
                        if (type.equals("poster"))
                            getPoster();
                        if (type.equals("channel"))
                            getChannel();
                    }else{
                        if (!prf.getString("first").equals("true")){
                            Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                            finish();
                            prf.setString("first","true");
                        }else{
                            Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                            startActivity(intent);
                            overridePendingTransition(R.anim.enter, R.anim.exit);
                            finish();
                        }
                    }
                }
            }
            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                updateTextViews();

                if (id!=null && type !=null){
                    if (type.equals("poster"))
                        getPoster();
                    if (type.equals("channel"))
                        getChannel();
                }else{
                    if (!prf.getString("first").equals("true")){
                        Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.enter, R.anim.exit);
                        finish();
                        prf.setString("first","true");
                    }else{
                        Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.enter, R.anim.exit);
                        finish();
                    }
                }
            }
        });

    }else{
        updateTextViews();

        if (id!=null && type !=null){
            if (type.equals("poster"))
                getPoster();
            if (type.equals("channel"))
                getChannel();
        }else{
            if (!prf.getString("first").equals("true")){
                Intent intent = new Intent(LoadActivity.this,IntroActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.enter, R.anim.exit);
                finish();
                prf.setString("first","true");
            }else{
                Intent intent = new Intent(LoadActivity.this,HomeActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.enter, R.anim.exit);
                finish();
            }
        }
    }

}
private void initBuy() {
    Intent serviceIntent =
            new Intent("com.android.vending.billing.InAppBillingService.BIND");
    serviceIntent.setPackage("com.android.vending");
    bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);

    if(!BillingProcessor.isIabServiceAvailable(this)) {
        //  showToast("In-app billing service is unavailable, please upgrade Android Market/Play to version >= 3.9.16");
    }

    bp = new BillingProcessor(this, Global.MERCHANT_KEY, MERCHANT_ID, new BillingProcessor.IBillingHandler() {
        @Override
        public void onProductPurchased(@NonNull String productId, @Nullable TransactionDetails details) {
            updateTextViews();
        }
        @Override
        public void onBillingError(int errorCode, @Nullable Throwable error) {
        }
        @Override
        public void onBillingInitialized() {
            readyToPurchase = true;
            updateTextViews();
        }
        @Override
        public void onPurchaseHistoryRestored() {
            for(String sku : bp.listOwnedProducts())
                Log.d(LOG_TAG, "Owned Managed Product: " + sku);
            for(String sku : bp.listOwnedSubscriptions())
                Log.d(LOG_TAG, "Owned Subscription: " + sku);
            updateTextViews();
        }
    });
    bp.loadOwnedPurchasesFromGoogle();
}
@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(mServiceConn);
}

private void updateTextViews() {
    PrefManager prf= new PrefManager(getApplicationContext());
    bp.loadOwnedPurchasesFromGoogle();
    if(isSubscribe(Global.SUBSCRIPTION_ID)){
        prf.setString("SUBSCRIBED","TRUE");
    }
    else{
        prf.setString("SUBSCRIBED","FALSE");
    }
}
public Boolean isSubscribe(String SUBSCRIPTION_ID_CHECK){

    if (!bp.isSubscribed(Global.SUBSCRIPTION_ID))
        return false;

    Bundle b =  getPurchases();
    if (b==null)
        return  false;
    if( b.getInt("RESPONSE_CODE") == 0){
        ArrayList<String> ownedSkus =
                b.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
        ArrayList<String>  purchaseDataList =
                b.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
        ArrayList<String>  signatureList =
                b.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
        String continuationToken =
                b.getString("INAPP_CONTINUATION_TOKEN");

        if(purchaseDataList == null){
            return  false;

        }
        if(purchaseDataList.size()==0){
            return  false;
        }
        for (int i = 0; i < purchaseDataList.size(); ++i) {
            String purchaseData = purchaseDataList.get(i);
            String signature = signatureList.get(i);
            String sku_1 = ownedSkus.get(i);
            //Long tsLong = System.currentTimeMillis()/1000;

            try {
                JSONObject rowOne = new JSONObject(purchaseData);
                String  productId =  rowOne.getString("productId") ;

                if (productId.equals(SUBSCRIPTION_ID_CHECK)){

                    Boolean  autoRenewing =  rowOne.getBoolean("autoRenewing");
                    if (autoRenewing){
                        Long tsLong = System.currentTimeMillis()/1000;
                        Long  purchaseTime =  rowOne.getLong("purchaseTime")/1000;
                        return  true;
                    }else{
                        // Toast.makeText(this, "is not autoRenewing ", Toast.LENGTH_SHORT).show();
                        Long tsLong = System.currentTimeMillis()/1000;
                        Long  purchaseTime =  rowOne.getLong("purchaseTime")/1000;
                        if (tsLong > (purchaseTime + (Global.SUBSCRIPTION_DURATION*86400)) ){
                            //   Toast.makeText(this, "is Expired ", Toast.LENGTH_SHORT).show();
                            return  false;
                        }else{
                            return  true;
                        }
                    }

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

    }else{
        return false;
    }

    return  false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (!bp.handleActivityResult(requestCode, resultCode, data))
        super.onActivityResult(requestCode, resultCode, data);
}

public Bundle getPurchases(){
    if (!bp.isInitialized()) {
        return null;
    }
    try{

        return  mService.getPurchases(Constants.GOOGLE_API_VERSION, getApplicationContext().getPackageName(), Constants.PRODUCT_TYPE_SUBSCRIPTION, null);
    }catch (Exception e) {
        // Toast.makeText(this, "ex", Toast.LENGTH_SHORT).show();

        e.printStackTrace();
    }
    return null;
}

public void getPoster(){

    Retrofit retrofit = apiClient.getClient();
    apiRest service = retrofit.create(apiRest.class);
    Call<Poster> call = service.getPosterById(id);
    call.enqueue(new retrofit2.Callback<Poster>() {
        @Override
        public void onResponse(Call<Poster> call, Response<Poster> response) {
            if(response.isSuccessful()) {
                if (response.body().getType().equals("serie")) {
                    Intent in = new Intent(LoadActivity.this,SerieActivity.class);
                    in.putExtra("poster", response.body());
                    in.putExtra("from", "true");
                    startActivity(in);
                    finish();
                }if (response.body().getType().equals("movie")){
                    Intent in = new Intent(LoadActivity.this,MovieActivity.class);
                    in.putExtra("poster", response.body());
                    in.putExtra("from", "true");
                    startActivity(in);
                    finish();
                }
            }
        }
        @Override
        public void onFailure(Call<Poster> call, Throwable t) {

        }
    });
}
public void getChannel(){

    Retrofit retrofit = apiClient.getClient();
    apiRest service = retrofit.create(apiRest.class);
    Call<Channel> call = service.geChannelById(id);
    call.enqueue(new retrofit2.Callback<Channel>() {
        @Override
        public void onResponse(Call<Channel> call, Response<Channel> response) {
            if(response.isSuccessful()) {
                Intent in = new Intent(LoadActivity.this,ChannelActivity.class);
                in.putExtra("channel", response.body());
                in.putExtra("from", "true");
                startActivity(in);
                finish();
            }
        }
        @Override
        public void onFailure(Call<Channel> call, Throwable t) {

        }
    });
}
}

Now, when i add the subscription ID and Merchat ID and upload my app on google app console. But after publish when i click on subscription which includes remove ads, can download product, Play premium content its show error item not found. I also add this in my AndroidManifest.xml
<uses-permission android:name="com.android.vending.BILLING" />

but its not working can anyone help me why this error coming and why its not fetching my subscription_ID which i created in my Google Play console.


text:
Q: Add value instead to datagridview if item already exist Hi guys here is my problem. I have 2 datagridview.
What i want to do is whenever i click "add this datagridview1 row(product) to datagridview2" and that product from datagridview1 is already in datagridview2, it will just add the value of a textbox(quantity) to the quantity cell in datagridview2 which have same ID as the one being inserted.
It can already detect if the product your inserting to datagridview2 is already existing but i cant make it add the value of the textbox to the existing cell in the datagridview.
Here are my codes(that is wrong and not working) and pic of the datagridviews.
    private bool alreadyincart()
    {
        foreach (DataGridViewRow row in dgvOrdercart.Rows)
        {
            int productcartID = Convert.ToInt32(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString());
            if (Convert.ToInt32(row.Cells[0].Value) == productcartID)
            {
                MessageBox.Show("Item already exist, Adding the quantity instead.");
                int textboxquantity = Convert.ToInt32(bakss.Text);
                int dgvquantity = Convert.ToInt32(row.Cells[3].Value);
                int dgvnewquantity;
                dgvnewquantity = dgvquantity + textboxquantity;
                dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity;
                return false;

            }
        }
        return true;
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        if (!validate())
        {
            return;
        }
        else if (!alreadyincart())
        {
            return;
        }
        else
        {
            addData(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString(),
                dgvOrderproductlist.CurrentRow.Cells[1].Value.ToString(),
                dgvOrderproductlist.CurrentRow.Cells[2].Value.ToString(),
                bakss.Text, lblPrice.Text, totalprayss.Text, cboOrderSupplier.SelectedItem.ToString());
        }
    }

A: Try to change
dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity;

to
row.Cells[3].Value = dgvnewquantity;


text:
Q: How to find a type by FQN in a solution? I am writing a Rider/ReSharper nav-from-here plugin which is supposed to determine a target type based on a symbol I am standing on using some simple rules, and finally, navigate to it.
The first part is okay, I have managed to form the FQN needed, but I am struggling with the navigation. I found this StackOverflow post, and thought I might try this approach. So I have been trying to use TypeFactory.CreateTypeByCLRName for like two hours to create an IDeclaredType instance to be able to get the IDeclaredElement using GetTypeElement() and eventually get its declarations. But the API seems to have changed and no matter what I do I cannot get my code to work.
Here is what I've got so far:
// does not work with Modules.GetModules(), either
foreach (var psiModule in solution.GetPsiServices().Modules.GetSourceModules())
{
    var type = TypeFactory.CreateTypeByCLRName("MyNamespace.MyClassName", psiModule);
    var typeElement = type.GetTypeElement();

    if (typeElement != null)
    {
        MessageBox.ShowInfo(psiModule.Name); // to make sure sth is happening
        break;
    }
}

The weird part is, I actually see a message box - but only when the tab with MyClassName.cs is active. When it is in focus, everything is fine. When it's not or the file is closed, the class does not get resolved, type.IsResolved is false.
What am I doing wrong?

A: To do this, you should have a IPsiModule instance from the context where you plan to use the type you're looking for. You can get it from some syntax node you're working with via .GetPsiModule() method or via many other ways (like dataContext.GetData(PsiDataConstants.SOURCE_FILE)?.GetPsiModule().
void FindTypes(string fullTypeName, IPsiModule psiModule)
{
  // access the symbol cache where all the solution types are stored
  var symbolCache = psiModule.GetPsiServices().Symbols;

  // get a view on that cache from specific IPsiModule, include all referenced assemblies
  var symbolScope = symbolCache.GetSymbolScope(psiModule, withReferences: true, caseSensitive: true);

  // or use this to search through all of the solution types
  // var symbolScope = symbolCache.GetSymbolScope(LibrarySymbolScope.FULL, caseSensitive: true);

  // request all the type symbols with the specified full type name
  foreach (var typeElement in symbolScope.GetTypeElementsByCLRName(fullTypeName))
  {
    // ...
  }
}


text:
Q: Is it possible to replace the result of the SQL Select query? I'm writing a select query and is it possible to replace the data displayed from select statement. For ex, result from the my select query looks like
Name    Date    Total
----    ----    ----
No1    6/30/15    20
No2    6/29/15    35
No3    6/20/15    40
No4    6/30/15    65
No5    6/27/15    25

I want to do a calculation based on the date and replace the entire data in the cell with NULL or N/A.For above table, If the date is todays date then all the fields should remain intact else it should update as blank.
Name    Date    Total
----    ----    ----
No1    6/30/15    20
No2    6/29/15
No3    6/20/15
No4    6/30/15    65
No5    6/27/15

A: You could use either of:

*

*DECODE

*CASE
Using DECODE(looks shorter):
SELECT name,
  DATE,
  DECODE(DATE, TRUNC(SYSDATE), total, NULL) AS "Total"
FROM table_name;

Using CASE(looks verbose):
SELECT name,
  DATE,
  CASE
    WHEN DATE = TRUNC(SYSDATE)
    THEN total
    ELSE NULL
  END AS "Total"
FROM table_name;


text:
Q: phpMyAdmin how to run an output query? run a batch? In phpMyAdmin the code below just outputs a list of sql statements for each table:
SET @DATABASE_NAME = 'my_db';
SELECT  CONCAT('ALTER TABLE `', table_name, '` ENGINE=InnoDB;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'MyISAM'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;

How would I actually execute this to change all the tables? I've seen people say "batch" but I'm not sure if that is what I'm looking for.

A: It is actually easiest to simply copy&paste the SQL statements.  Don't bother with trying to find and "eval".
It is even easier in the mysql commandline tool.
Here are my tips on gotchas that sometimes occur in the conversion from MyISAM to InnoDB:  http://mysql.rjweb.org/doc.php/myisam2innodb


text:
Q: Optional navigation property is not being loaded I can't for the life of me figure out why Entity Framework (4.1, Code First) is not materializing an optional navigation property.
POCOs:
public class PlanMember {
    public Int64 Id { get; set; }

    public String FirstName { get; set; }

    public virtual SystemUser CaseManager { get; set; }

    public String LastName { get; set; }

    public virtual PlanMemberStatus Status { get; set; }
}

public class SystemUser {
    public String EMail { get; set; }

    public String FirstName { get; set; }

    public String Id { get; set; }

    public String LastName { get; set; }
}

public class PlanMemberStatus {
    public Int32 Id { get; set; }

    public String Code { get; set; }
}

Configuration Classes:
public class ForPlanMemberEntities:EntityTypeConfiguration<PlanMember> {
    public ForPlanMemberEntities(String schemaName) {
        this.HasOptional(e => e.CaseManager)
            .WithMany()
            .Map(m => m.MapKey("CaseManagerID"));
        this.HasRequired(e => e.Status)
            .WithMany()
            .Map(m => m.MapKey("StatusID"));
        this.ToTable("PlanMember", schemaName);
    }
}

public class ForSystemUserEntities:EntityTypeConfiguration<SystemUser> {
    public ForSystemUserEntities(String schemaName) {
        this.ToTable("SystemUser", schemaName);
    }
}

public class ForPlanMemberStatusEntities:EntityTypeConfiguration<PlanMemberStatus> {
    public ForPlanMemberStatusEntities(String schemaName) {
        this.ToTable("PlanMemberStatus", schemaName);
    }
}

Context:
public class Context:DbContext {
    public DbSet<PlanMember> PlanMemberDbSet { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        var schemaName = Properties.Settings.Default.SchemaName;
        modelBuilder.Configurations
            .Add(new Configuration.ForPlanMemberEntities(schemaName))
            .Add(new Configuration.ForPlanMemberStatusEntities(schemaName))
            .Add(new Configuration.ForSystemUserEntities(schemaName))
            ;
    }
}

Based on that configuration, if I run a query like the following it will not populate the CaseManager property. The PlanMemberStatus property loads just fine.
var test = (from member in PlanMemberDbSet
            where member.CaseManager != null
            select member).First();
var cm = test.CaseManager;

In my example cm is always null, despite the fact that - logically speaking - it should be impossible. Any thoughts?
EDIT - If I do PlanMemberDbSet.Include("CaseManager") then it works as expected. Why is this necessary? In other scenarios I haven't had to do this.

A: My guess is that the CaseManagerID foreign key column value in the PlanMember table is different to the Id primary key column value in table SystemUser - different for .NET but not for SQL Server (with standard sorting system), for example different in casing: "a" in CaseManagerID but "A" in Id.
Querying for != null (translates into IS NOT NULL in SQL) works, so you get indeed only the PlanMember entities which have a SystemUser assigned in the database. Also the query by the CaseManager (triggered by lazy loading) is correctly executed in the database (INNER JOIN) and transmitted to the client. Even the object materialization works (there are 2 objects in the context). But EF fails to relate the loaded PlanMember with the loaded CaseManager because the keys are not identical (for example with respect to capital/small letters). As a result your navigation property is null.
This doesn't occur with the Status navigation property because the key is an Int32.
The problem looks closely related to this one: EF 4.1 Code First bug in Find/Update. Any workaround? Should it be reported?


text:
Q: Make App Engine for PHP load BCMath or php.ini I'm running the latest php-cgi from Arch Linux's repos. I enabled the BCMath module on php.ini and it works when I run php, php-cgi and php in Apache. However, when dev_appserver.py runs php, somehow it loses the configuration I set in php.ini. Causing both BCMath, soap and my locale settings to not load, causing:
dev_appserver.py --php_executable_path /usr/bin/php-cgi appengine-try-php
PHPEnvironmentError: The PHP runtime requires the "bccomp" function, which is not defined.

php-cgi -i | grep -i bcmath returns BCMATH enabled.
php -i | grep -i bcmath returns BCMATH enabled.
php -r "echo bccomp('1.0001', '1', 5);" returns 1.
Is there any way to make dev_appserver.py load the module or php.ini?

A: Here's the code that fails - we check if the function exists.
if (!function_exists('bccomp')) {
  echo "The PHP runtime requires the \"bccomp\" function, which is not ";
  echo "defined.\n";
  echo "If you built PHP using \"configure\" then please rebuild with:\n";
  echo ' ./configure  --enable-bcmath';
  exit(1);
}

I don't know why you'd have the extension enabled but the function not existing. Probably try listing the functions that are available to double check it's there.
 php -r 'print_r(get_defined_functions());' | grep -i bccomp

A: google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/php/runtime.py
Supports loading a php.ini file from the project directory, as such you can just drop a php.ini file in the project directory. It will by default ignore the php.ini file in /etc/php/php.ini unlike all other instances of php. Here is the php.ini script I'm using. It likely has extra modules and modules that are missing compared to the production App Engine.
date.timezone = America/New_York
extension=bcmath.so
extension=bz2.so
extension=curl.so
extension=gd.so
extension=gettext.so
extension=mcrypt.so
extension=mysqli.so
extension=mysql.so
extension=openssl.so
extension=pdo_mysql.so
extension=soap.so
extension=zip.so

Happy Apping.


text:
Q: How to connecet to SQL database using Singleton Design Pattern java ? Also, who can show the difference from native code? For example, connect to the database with Java and do it with Singleton Design pattern. What are advantages of using it?

A: Your connection instance should be preserved and you can only retrieve your connection via getConnection() method (getInstance of the Singleton pattern)
Here is a sample code;
A - Sample Database Utility Based On Singleton Design Pattern of Gang Of Four
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

    private final String HOST;
    private final String PORT;
    private final String DB_NAME;
    private final String USER;
    private final String PASSWORD;

    private final String TARGET_TABLE;
    private final String COLUMN_NAME;

    private final String CONNECTION_STRING;

    private final String SELECT_ALL_SQL;
    private final String SELECT_COLUMN_SQL;
    private final String INSERT_SQL;

    private Connection conn;

    public DBUtil() {
        // Database Parameters
        HOST                    = "your_host_here";
        PORT                    = "your_port_number_here";
        DB_NAME                 = "your_database_name";
        USER                    = "your_databse_user_here";
        PASSWORD                = "your_database_password_here";

        // Database Tables
        TARGET_TABLE            = "your_table_name";
        COLUMN_NAME             = "your_tables_column_name";

        CONNECTION_STRING       = String.format("jdbc:mysql://%s:%s/%s", HOST, PORT, DB_NAME);

        // Query Strings
        SELECT_ALL_SQL          = String.format("SELECT * FROM %s.%s WHERE id=?", DB_NAME, TARGET_TABLE);
        SELECT_COLUMN_SQL       = String.format("SELECT %s FROM %s.%s WHERE id=?", COLUMN_NAME, DB_NAME, TARGET_TABLE);
        INSERT_SQL              = String.format("INSERT INTO %s.%s (id, name) values (?, ?)", DB_NAME, TARGET_TABLE);

        printConfiguration();

        conn = null;
    }

    private void printConfiguration() {
        System.out.println("******************************************************************************");
        System.out.println("DB_NAME                    : " + DB_NAME);
        System.out.println("USERNAME                   : " + USER);
        System.out.println("PASSWORD                   : " + PASSWORD);
        System.out.println("CAMT TABLE                 : " + TARGET_TABLE);
        System.out.println("******************************************************************************");
    }

    private void getConnection() {
        if(conn != null) {
            System.out.println("Connection already established with db");

            return;
        }

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(CONNECTION_STRING, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            System.out.println("Connection FAILED");
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void closeConnection() {
        if(conn == null) {
            return;
        }

        try {
            conn.close();

            conn = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public int insert(int id, String column) {
        int rowNum;

        getConnection();
        PreparedStatement preparedStatement = null;

        try {
            preparedStatement = conn.prepareStatement(INSERT_SQL);
            System.out.println("SQL: " + INSERT_SQL);
            preparedStatement.setInt(1, id);
            preparedStatement.setString(2, column);

            rowNum = preparedStatement.executeUpdate();

            System.out.println(rowNum + " rows are inserted");

            return rowNum;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return -1;
    }

    public Model getModel(int id) {
        getConnection();
        PreparedStatement preparedStatement = null;
        Model model = new Model();

        try {
            preparedStatement = conn.prepareStatement(SELECT_ALL_SQL);
            System.out.println("SQL: " + SELECT_ALL_SQL);
            preparedStatement.setInt(1, id);

            ResultSet rs = preparedStatement.executeQuery();

            if(rs.next()) {
                model.setId(rs.getInt("id"));
                model.setName(rs.getString("name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return model;
    }

    public String getName(int id) {
        getConnection();
        PreparedStatement preparedStatement = null;
        String name = null;

        try {
            preparedStatement = conn.prepareStatement(SELECT_COLUMN_SQL);
            System.out.println("SQL: " + SELECT_ALL_SQL);
            preparedStatement.setInt(1, id);

            ResultSet rs = preparedStatement.executeQuery();

            if(rs.next()) {
                name = rs.getString("name");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return name;
    }

}

B - Model Used in Singleton Database Utility Demo
public class Model {

    private int id;
    private String name;

    public Model() {}

    public Model(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
Q: Kinematics of a rolling disk on a static disk (variation of the Euler disk) I'm puzzled by the following problem.  Consider a simple tilted disk $\mathcal{D}$ of radius 1 (in any unit) rolling without sliding on top of a static horizontal disk $\mathcal{S}$.  The normal $\mathbf{N}$ of $\mathcal{D}$ has a constant tilt $\alpha$, relative to the vertical $z$ axis.  The disk $\mathcal{S}$ has a radius of $\cos \alpha$, so the center $\mathcal{C}$ should stay fixed (no horizontal translation of the center $\mathcal{C}$).  See the picture below:

If the moving disk $\mathcal{D}$ was sliding on the static disk $\mathcal{S}$, the point $\mathcal{A}$ would simply rotate around the border of $\mathcal{S}$.  In this simple case, the center $\mathcal{C}$ remains static (vertically and horizontally).  The normal vector $\mathbf{N}$ and the radius $\mathbf{CA}$ would precess like this (I put the cartesian axes origin at the bottom, in the center of the static disk):
\begin{align}
\mathbf{N}(t) &= \sin \alpha \, \cos \omega t \, \mathbf{x} + \sin \alpha \, \sin \omega t \, \mathbf{y} + \cos \alpha \, \mathbf{z}, \tag{1} \\[2ex]
\mathbf{CA}(t) &= \cos \alpha \, \cos \omega t \, \mathbf{x} + \cos \alpha \, \sin \omega t \, \mathbf{y} - \sin \alpha \, \mathbf{z}, \tag{2} \\[2ex]
\mathbf{r}_{\mathcal{A}}(t) &= \cos \alpha \, \cos \omega t \, \mathbf{x} + \cos \alpha \, \sin \omega t \, \mathbf{y}. \tag{3}
\end{align}
I want to describe the motion of the material point $\mathcal{A}$ when $\mathcal{D}$ is rolling on $\mathcal{S}$, instead of simply sliding on it.  In this case, the material point $\mathcal{A}$ should get a vertical oscillation and wouldn't rotate around $\mathcal{S}$, so (2) and (3) aren't right.  How the material point $\mathcal{A}$ and vectors $\mathbf{N}$, $\mathbf{CA}$ should move?  My intuition tells me that $\mathbf{N}(t)$ should stay the same as (1) but I'm not sure this is right.  I'm expecting an oscillation of $\mathcal{A}$ around the fixed height $z_{\mathcal{C}} = \sin \alpha$, something like
$$\tag{4}
\mathbf{r}_{\mathcal{A}}(t) = \cos \alpha \, \cos \varphi_{\mathcal{A}} \, \mathbf{x} + \cos \alpha \, \sin \varphi_{\mathcal{A}} \, \mathbf{y} + \sin \alpha \, (1 - \cos(\varphi_{\mathcal{A}} - \omega t)) \, \mathbf{z},
$$
where $\varphi_{\mathcal{A}}$ is the static angular coordinate of the material point along the edge of the static disk.  Vector (4) is such that setting $\varphi_{\mathcal{A}} = \omega t$ (in the rotating reference frame) gives back vector (3).  But how can we prove that vector (4) describes a rolling disk without sliding?
The following video on YouTube shows the illusion of two rings rolling on top of each other:
https://www.youtube.com/watch?v=x7zZzPqfhlg
But it is clear that the rings are just rotating around the vertical axis, and aren't actually rolling on each other.

A:
I think that to obtain the rolling condition you have to allows additional
rotation of disc D
in this case the relative velocity at point A is:
$$v_r=\omega_d\rho_d-\omega_s\rho_s$$
the rolling condition is fulfilled if the velocity $~v_r~$  equal zero.
thus the angular velocity of disc D must be:
$$\omega_d=\frac{\rho_s}{\rho_d}\,\omega_s$$


text:
Q: Regarding the unique subfields of a cyclotomic field extension What are the unique subfields $L$ of $\mathbb{Q}(\zeta_{13})$ such that $[L:\mathbb{Q}]=2, 3, 4$, and $6$? I get that the Euler's totient function of $13$ is $12$ and that must have some relation, as its factors are listed above. Let's take the first case, $[L:\mathbb{Q}]=2$ and I'll show you why I'm confused.
I would assume for $[L:\mathbb{Q}]=2$ we have $\mathbb{Q}$-basis $\{e,\sigma\}$ where $\sigma: \zeta^x\mapsto\zeta^{x+6}$, because this cycles round our $\zeta^1$ to $\zeta^{12}$ in $2$ steps, however, why can we just miss out $\zeta^{13}=1$? Surely when it cycles from, say, $\zeta^6$ it goes $\zeta^6\mapsto \zeta^{12}\mapsto \zeta^{18}=\zeta^5\mapsto \zeta^{11}$ etc and we generate the whole group? Then $[L:\mathbb{Q}]\neq2$?
Sorry I'm not phrasing myself very well, but I honestly don't know how to. Thanks to all in advance!

A: The subfields of $\mathbb{Q}(\zeta_p)$ for $p$ prime correspond to the subgroups of its Galois group $U(p)\cong C_{p-1}$. For $p=13$ we have to find the subgroups of the cyclic group $C_{12}$. We know that for each divisor $d\mid 12$ there exists exactly one subgroup of order $d$, because $C_{12}$ is cyclic - see here.


text:
Q: How to revamp a website from wordpress to wix without changing the domain & without losing the mailbox linked with that domain? I want to change a website from wordpress to wix. The challenge is that- If I connected the existing domain directly to wix, will I lose my mailbox?
Please suggest how to connect mailbox to wix without losing it?

A: It's a bit of a strange question.
Wix is indeed a SaaS, providing hosting, a domain, ... which means that in order to use Wix, you either develop your platform within their SaaS environment OR you use their SaaS environment to provide services to an external platform.
I see only one option to adhere to the requirements you shared. If you want to keep the current host, but you want to use Wix, you'll have to provide services from Wix to your external website.
For the moment, this sounds more like an architectural question, so you might want to be more explicit.


text:
Q: Codename One: Invoke codename code from native interface I am writing a real time library for Codename one by wrapping the native libraries of Ably. I am invoking native interfaces to include the libraries for each platform, but how can I call Codename one code from the native interface or emit an event? For example, if I subscribe from an iOS client, how can tell the normal Codename One code that a message has been received?

A: In the advanced section of the developer guide look for the section titled "Native Code Callbacks".
This is pretty challenging as it differs between platforms so it's recommended to keep the callback to a minimum when possible.


text:
Q: Recently used an old script using Ngrok but now it doesnt work Basically I just booted up an older script that I made 1-2 months ago and which worked perfectly at the time, but now when I try to connect to the ngrok tunnel i get a 404 and a "Tunnel xxxx not found"
I have a non-paying user, which didn't use to be a problem and I cant see anywhere that they changed their terms of service and I can find the tunnel on the dashboard but not connect, any idea what is wrong and if they changed something?
I just booted an old super simple test script which also doesn't work, I can see the tunnel but it returns "Funnel xxxx not found" and server 404:
from flask import Flask
from flask_ngrok import run_with_ngrok

app = Flask(__name__)
run_with_ngrok(app)   #starts ngrok when the app is run
@app.route("/")
def home():
    return "
Running Flask on Google Colab!
"

app.run()


text:
Q: Again, proving that specific preorder on the set of measurable functions is symmetric This question is followup to the previous similar question. There I was trying to find good sufficient condition for abstract preorder to be symmetric, but now, as I have found good formalization of my specific preorder, I'll better ask about it directly.
Let's say we have arbitrary finite measure space $\langle \Omega, \mathfrak{I}, \mathbb{P} \rangle$. For any functions $\rho : Y \rightarrow X$ and measurable $f : \Omega \rightarrow X$ with any finite $X$ and $Y$ we define $H_{\rho}(f) = \{\mathbb{P} \circ g^{-1} \mid f = \rho \circ g, g \text{ is measurable}\}$ – set of functions $Y \rightarrow \mathbb{R}_{\ge 0}$ characterizing internal structure of $f$ induced by $\rho$. Preorder $\precsim$ is defined on set of measurable functions $\{ f : \Omega \rightarrow X \}$ as follows – $f_1 \precsim f_2 \iff H_{\rho}(f_1) \subseteq H_{\rho}(f_2), \forall \rho$.
I believe that such preorder is symmetric ($f_1 \precsim f_2 \Leftrightarrow f_2 \precsim f_1, \forall f_1, f_2$) due to external reasons (it has respective game-theoretical interpretation), but I'm unable to prove it as defined. Can anyone help me, please?
UPDATE: Please, take note, $\forall \rho$ here means for all $\rho$ across every possible finite $Y$, not just one externally fixed.
UPDATE: To keep you guys interested and maybe bootstrap thoughts, I'll add some facts.

*

*$f_1 \precsim f_2 \Rightarrow \xi \circ f_1 \precsim \xi \circ f_2, \forall f_1, f_2, \xi$ – this follows trivially from definition of $H_{\rho}$.

*Consequentially, symmetry of $\precsim$ is easily provable for $f_2 = \pi \circ f_1, \pi : X \leftrightarrow X$. Because of $f_1 \precsim f_2 \Rightarrow \pi \circ f_1 \precsim \pi \circ f_2$ we can build infinite chain of $f_1 \precsim \pi \circ f_1 \precsim \pi \circ \pi \circ f_1 \precsim \ldots$. Combinatorics says that there must be finite cycle $\pi \circ ... \circ \pi$ synonymous to identity permutation, which leads to $f_2 = \pi \circ f_1 \precsim \pi \circ ... \circ \pi \circ f_1 = f_1$.

*Consequentially, symmetry of $\precsim$ is easily provable for measure spaces with finite algebra. In such case any measurable function $f_i$ can be derived from singular function $g$, that transforms each atom to its own element of codomain, as $f_i = \xi_i \circ g$. For such $g$ and its permutations $g \precsim \pi \circ g \Leftrightarrow \pi \circ g \precsim g \Leftrightarrow \mathbb{P} \circ g^{-1} = \mathbb{P} \circ (\pi \circ g)^{-1}$ which leads to $f_1 \precsim f_2 \Leftrightarrow f_2 \precsim f_1$ by definition of $H_{\rho}$.

Unfortunately, here my progress bumps into wall – going from this subcases to generic case seems to be beyond my knowlegde. And this is sad, because symmetry of preorder in question is a cornerstone of formal argumentation for very interesting new result in game theory. I would be very grateful even for slightest hints.

A: I think I found a counterexample.
Let $Y=\{1\}$, $X=\Omega=\{1,2\}$, $f_1(\omega)=\omega$, $f_2(\omega)=1$.
Then for all $\rho:Y\to X$ there exists no $g$ such that $f=\rho \circ g$,
thus $H_\rho(f_1)$ is empty and $f_1\precsim f_2$.
On the other hand, for $\rho = x\mapsto 1$ we have $H_\rho(f_2)=\{\mathbb P(\Omega)\}$.
Thus $f_2\not\precsim f_1$.

A: I did it, finally. Without going into much detail, it is possible to prove following fact - if there exists at least one pair of measurable $f_1, f_2 : \Omega \rightarrow X, f_1 \prec f_2 \equiv f_1 \precsim f_2 \cap \neg (f_1 \succsim f_2)$, then for any measurable $g_1 : \Omega \rightarrow Y$ it is possible to construct measurable $g_2 : \Omega \rightarrow Y$ for which $g_1 \prec g_2$. This is not possible though, because space of measurable functions with finite codomain is compact in Tychonoff topology, so for any partial order there must be at least one maximal element.
UPDATE: For people interested here is line of reasoning:

*

*I introduce pseudometric $d(f_1, f_2) = \mathbb{P}(f_1 \ne f_2)$ for space of $\Omega \rightarrow X$ and metric $d(\mu_1, \mu_2) = \max \lvert \mu_1 - \mu_2 \rvert$ for space of $Y \rightarrow \mathbb{R}_{\ge 0}$. Under this $H_\rho(f)$ is continuous in Hausdorff sense, so $H_\rho^{-1}(\mu) = \{\text{measurable } f \mid \mu \in H_\rho(f)\}$ is continuous too.

*Consequentially, if $f_1 \precsim f_2$, then for any measurable $g_1$ such that $f_1 = \rho \circ g_1$ it is possible to construct measurable $g_2$ such that $f_2 = \rho \circ g_2$ and $g_1 \precsim g_2$. Proof here uses triviality of building $g_2$ which $H_\rho(g_2)$ contains any finite subset of $H_\rho(g_1)$.

*Because of $f_1 \precsim f_2 \Rightarrow \rho \circ f_1 \precsim \rho \circ f_2$ previous statement holds for strict relation $\prec$ too.

*Supposing $f_1 \prec f_2 : \Omega \rightarrow X$, for any $g_1 : \Omega \rightarrow Y$ we build $h_1 = (f_1, g_1) : \Omega \rightarrow X \times Y$ and $\rho(x, y) = x, \xi(x, y) = y$. As $f_1 = \rho \circ h_1$ there exists measurable $h_2$ such that $f_2 = \rho \circ h_2$ and $h_1 \prec h_2$. Let's say $g_2 = \xi \circ h_2$ and because of $g_1 = \xi \circ h_1$ holds $g_1 \prec g_2$. Fortunately, this contradicts with compactness of space of measurable functions with finite codomain.


text:
Q: Binding an Ordered Relationship with an NSArrayController How does one bind an NSArrayController's content to the entities in an ordered to-many relationship?
I have an unordered to-many relationship in my Core Data model, and an NSArrayController whose Content Set is bound to that relationship from the parent entity. This works fine, the data is accessible from the NSArrayController, no problem.
I decided during development that it would be better to allow users to manually reorder these child objects, so I changed the relationship to an ordered one. Now, when my NSArrayController is being created from my nib, the following error is presented:
Cannot create NSSet from object Relationship '...' fault on managed object ... of class _NSFaultingMutableOrderedSet

Now actually, I think this all makes sense: It's an ordered relationship, so now I'm getting an ordered set. Binding it to Content Array also would be inappropriate, since it's now an NSOrderedSet, not an array. My question is: Now how do I bind this relationship's data back into the NSArrayController?

A: The fundamental problem is that a Core Data ordered to-many relationship returns an NSOrderedSet, and NSOrderedSet is not a subclass of NSSet. Any array controller bindings that expect an NSSet will fail.
Tom Fewster has a detailed blog post describing the use of NSValueTransformer to work around this shortcoming, converting between NSOrderedSet and NSArray on the fly. He also provides a sample implementation on Github.

A: I came across this discussion while searching to see if there've been any new developments on this front. In a shipping app I currently bind the array controller's content array to orderedSetKey.@array and it works just fine, not sure if I discovered that myself or if someone else suggested it somewhere.


text:
Q: Google maps as a background of the widget in wordpress I'm trying to implement a google maps as a background of my widget. I have two divs, one for map, and another one for the text which should be on top of the map. To achieve that I use different values of the z-index in the css file. Here is the code of the widget:
echo $before_widget;
  $bg_image_style = '';
  if ( !empty( $background_image ) ) {
     $bg_image_style .= 'background-image:url(' . $background_image . ');background-attachment:' . $bg_attachment . ';background-repeat:no-repeat;background-size:cover;';
  }else {?>
  <?php }?>
  <?php if ( !empty( $background_image ) ) {?>
       <div class="call-to-action-content-wrapper clearfix"  style="<?php echo $bg_image_style; ?>">
  <?php } else {?>

  <?php }?>

        <?php if( !empty( $text_main ) ) { ?>

              <?php echo esc_html( $text_main );
              if( !empty( $button_text ) ) { ?>
                 <a class="call-to-action-button" href="<?php echo $button_url; ?>" title="<?php echo esc_attr( $button_text ); ?>"><?php echo esc_html( $button_text ); ?>
              <?php } ?>
              <?php if( empty( $button_text ) ) { ?>
                  Contact us
              <?php } ?>

        <?php } ?>

  <?php echo $after_widget;

If the background image $background_image is not empty, I use:
<div class="call-to-action-content-wrapper clearfix"  style="<?php echo $bg_image_style; ?>">

However, when its empty, I want to have a map in the background, so I use another div:

And after the ending tag of the "container" div I put a map div:

Here is the CSS:
    .business-template .widget.widget_call_to_action_block .call-to-action-    content-wrapper {
      padding: 100px 0;
    }

    .call-to-action-content-wrapper h3 {
    padding-bottom: 0;
    font-size: 26px;
    color: #ffffff;
    line-height: 2;
    text-align: center;
    }

    #map-canvas {
    height: 500px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 0;
    }

    #container {
    z-index: 100;
    position: relative;
    }

    .clearfix:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;
    }
    .clearfix {
    display: inline-block;
    }

   .inner-wrap {
    max-width: 1100px;
    margin: 0 auto;
    z-index: 9999;
    }

   .business-template .widget.widget_call_to_action_block > .inner-wrap,
   .business-template .widget.widget_portfolio_block > .inner-wrap {
    max-width: 100%;
    }

However, the map is always on top, despite the z-index. Do you have any suggestions in the html and css? Maybe I do something wrong.


text:
Q: Data.table assign value to existing column I am performing an apparently simple assignment in a data.table object.
library(RODBC)
library(data.table)
library(ffbase)
library(plyr)
library(doBy)
library(reshape2)

ST_a = Sys.Date()-7
ST = paste("'",as.character(format(ST_a,"%d.%m.%Y")),"'",sep="")
rd_a = Sys.Date()- 41
rd = paste("'",as.character(format(rd_a,"%d.%m.%Y")),"'",sep="")

ch<-odbcConnect("db",uid="user",pwd="psw")

chunks <- c(seq.Date(from=rd_a, to=ST_a, by = 20),ST_a)

started.at <- proc.time()
Sys.sleep(1)

memory.limit(size=4095)

for (i in 1:(length(chunks)-1)){

start <- paste("'",as.character(format(chunks[i],"%d.%m.%Y")),"'",sep="")
end <- paste("'",as.character(format(chunks[i+1],"%d.%m.%Y")),"'",sep="")

query <- paste("Select * from DATA_LOCAL_V
        where id='EHPFCMO' and timestamp>",rd," and reference_date>=",start," and reference_date<",end,sep="")

EHPFC.ck <- data.table(sqlQuery(ch,query,stringsAsFactors=FALSE))

EHPFC.ck[,TIMESTAMP:=TIMESTAMP-60^2]
EHPFC.ck[, pod:=7]
EHPFC.ck[as.POSIXlt(EHPFC.ck$TIMESTAMP)$hour %in% c(20:23), pod:=23]
EHPFC.ck[as.POSIXlt(EHPFC.ck$TIMESTAMP)$hour %in% c(8:19), pod:=19]
EHPFC.ck[,day:=as.Date(trunc(TIMESTAMP))]
EHPFC.ck[,TIMESTAMP:=NULL]
EHPFC.ck <- EHPFC.ck[,mean(VALUE),by=list(ID,REFERENCE_DATE,day,pod)]
setnames(EHPFC.ck,"V1","price")

EHPFC.ck <- as.ffdf(EHPFC.ck)

if (i==1){
EHPFC <- EHPFC.ck
} else {
EHPFC <- ffdfappend(EHPFC,EHPFC.ck[,])
}
rm(EHPFC.ck)
gc()

}

EHPFC <- data.table(EHPFC[,])
EHPFC <- orderBy(~day+pod+REFERENCE_DATE, data=EHPFC)
a <- c(0,log(EHPFC[-1,price]/EHPFC[-nrow(EHPFC),price]))
EHPFC <- EHPFC[,RoR:=a]

By doing that I get the following error msg:
error in `[.data.table`(EHPFC, , `:=`(RoR, a)) :
  At an earlier point, this data.table has been copied by R. Avoid key<-, names<- and attr<- which in R currently (and oddly) all copy the whole data.table. Use set* syntax instead to avoid copying: setkey(), setnames() and setattr(). If this message doesn't help, please ask on datatable-help.

The object EHPFC looks like the following:
EHPFC
           ID REFERENCE_DATE        day pod    price RoR
 [1,] EHPFCMO     2012-10-27 2012-10-27   7 35.34625   0
 [2,] EHPFCMO     2012-10-28 2012-10-27   7 35.34625   0
 [3,] EHPFCMO     2012-10-29 2012-10-27   7 35.34625   0
 [4,] EHPFCMO     2012-10-30 2012-10-27   7 35.34625   0
 [5,] EHPFCMO     2012-10-31 2012-10-27   7 35.34625   0

I am a bit confused why this is happening.
Any idea? Thanks in advance.


text:
Q: awk print 2 lines back if match I have some output that looks like the following:
Gathering data for drive 1 ...
Drive name:  id1,sd@n5000cca17096
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 2 ...
Drive name:  id1,sd@n5000cca24156
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 3 ...
Drive name:  id1,sd@n5000cca8749
Drive Model: HUH721010AL4204
failed to get drive stats

Gathering data for drive 4 ...
Drive name:  id1,sd@n5000cca19183
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 5 ...
Drive name:  id1,sd@n5000cca4607
Drive Model: HUSMH8010BSS204
failed to get drive stats

Gathering data for drive 6 ...
Drive name:  id1,sd@n5000cca10152
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

I would like to print the "Drive name" for any drive in which the drive stats cannot be returned (so matching on failed to get drive stats).
I know how to get the previous line with:
awk '$0=="failed to get drive stats" && $2>1 {print f} {f=$0}'

But that doesn't help me.
Desired output:
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

Edit:
For some reason when the output is redirected it doesn't appear the same way as it does on the terminal.  If I run:
command >out.txt 2>&1

The output file will look like:
failed to get drive stats
failed to get drive stats

Gathering data for drive 1 ...
Drive name:  id1,sd@n5000cca17096
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

Gathering data for drive 2 ...
Drive name:  id1,sd@n5000cca24156
Drive Model: HUH721010AL4204
Drive Speed: 7200 RPMs
Drive Temp:  41 C

....

Both awk answers provided work but I just have other issues I guess

A: $ awk -F ':' '$1 == "Drive name" { saved = $0 } $0 == "failed to get drive stats" { print saved }' file
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

This first sets the input field separator to a :. It then saves the line in the variable saved whenever a line specifying a drive name is found.
If a line says failed to get drive stats, the current value of saved is printed.

A: This is why awk has a "paragraph mode", all you need is:
$ awk -v RS= -F'\n' '/failed to get drive stats/{print $2}' file
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607

A: Tried with Below method and it worked fine
awk '{a[++i]=$0}/failed/{for(x=NR-2;x<NR;x++)print a[x]}' filename| sed -n '1~2p'

output
Drive name:  id1,sd@n5000cca8749
Drive name:  id1,sd@n5000cca4607


text:
Q: Outbound link autometic converted into linkdirect , and not opening Outbound links are automatically converted into linkdirect link, and not opening. But internal links are fine. I use wp Nofollow plugin, currently, I deleted the plugin but no luck.
Please check my article:- https://www.holidaystory.in/visit-love-india-travel-rough-guides/
The error is :-{"error":"Sorry, User is not available"}


text:
Q: Why are all the strings I read ending up equal when I print them? I am learning C++ and there is a question in the book.

Q: Write a program that defines a vector of pointers to strings. Read the vector,
  printing each string and its corresponding size.

Code:
vector<string*> v;
string str;
cout<<"Enter your string:"<<endl;

while(cin >> str)                            // input
{
          string *ps=&str;
          v.push_back(ps);
}

vector<string*>::iterator iter=v.begin();
while( iter!=v.end())                         // output
   cout<< **iter++<<" "<<(**iter).size()<<endl;

When I input "a sd fgh", I expect the output to be "a 1; sd 2; fgh 3"; but the output is "fgh 3; fgh 3; fgh 3."   Anyone know where is going wrong?

A: You get the same output because all your string point to the same place - namely, your str variable. You should create new strings using the buffer str's data, like this:
std::string *ps = new string(str);

After you do that, don't forget to delete the strings that you allocated by calling delete ptr on each string pointer at the end of your function, when you no longer need the strings.

A: I'll give you a clue: std::string *ps = &str is a very bad idea. Each pointer will need its own memory.


text:
Q: Parity of Harmonic oscillator in 2 and 3 dimensions: the case of $l_z$ From doing exercises and trying to understand their solutions, i figured in two dimensions, not all values of $l_z$ can be taken by the particles (this is to conserve parity). For example, for n=0, the only l possible is 0, so $l_z=0$. For n=1, l=(1,0), but it's z projection can only be $l_z=\pm$1, so l=0 is discarted. n=2 means $l_z=(\pm$2,0) , n=3 we got $l_z=(\pm3,\pm1)$ and so on. In three dimensions though, all values of the projections are available. Why can $l_z$ take all values in 3D and not 2D?

A: $\let\phi=\varphi \let\dag=\dagger \def\half{{\textstyle{1 \over 2}}}
\def\PD#1#2{{\partial#1 \over \partial#2}} \def\ket#1{|#1\rangle} $
Your question can't be answered in a simple way. It implies a rather
deep matter falling under the title "Group theory and quantum
mecahnics". IMO it's very far from a "homework-and-exercise". I'll try
to give an answer but I don't know how far you'll be able to follow
it.
To begin with, your approach requires some qualifications. First:
I wouldn't use $l_z$ for angular momentum in 2D. The $z$ dimension
simply doesn't exist. There are just two coordinates, $x$ and $y$,
and two conjugate momenta $p_x$, $p_y$. All operators are expressed as
functions thereof. In a more sophisticated jargon, those four
operators generate the full algebra of observables for your quantum
system.
Hamiltonian is written
$$H = {1 \over 2m}\,(p_x^2 + p_y^2) + \half k\,(x^2 + y^2).$$

not all values of $l_z$ can be taken by the particles (this is to
  conserve parity).

Surely parity plays an important rôle but not the one you're
saying (see later).
Let's look for conserved quantities. There are two. The first is what
you called $l_z$ and I prefer to name $L$. It's the angular momentum
in plane $(x,y)$ around origin. Its expression as an operator is
$$L = x\,p_y - y\,p_x.$$
In Schrödinger representation
$$L = -i\hbar \left(\!x\,\PD{}y - y\,\PD{}x\!\right) =
-i\hbar\,\PD{}\phi.$$
It's not exactly trivial to verify that $[L,H]=0$, but it can be done, using commutation relation among canonical variables.
The second is $P$, which I'll define as
$$P:\ x \mapsto -x,\ y \mapsto y.\tag1$$
Some notes are necessary.
1) I've defined $P$ as $x$-inversion, not as combined inversion of $x$
and $y$. There is a difference between 2D and 3D cases. In 2D the
simultaneous inversion of both coordinates is obtained by a rotation
of an angle $\pi$, and as a rotation is already included in $L$
symmetry. On the contrary in 3D the inversion of all three coordinates isn't a rotation and must explicitly added as a further symmetry.
2) To completely define $P$ we must also specify its action on momenta:
$$P:\ p_x \mapsto -p_x,\ p_y \mapsto p_y.\tag2$$
It's important to observe that (1) and (2) together leave commutation
relations invariant. This is necessary if $P$ is to be a unitary
operator. It's easy to verify that $P$ leaves $H$ invariant, i.e.
$$P\,H\,P^\dag = H \qquad P\,H = H\,P \qquad [P,H] = 0.$$
3) In place of reflecting about $y$-axis we could reflect about $x$ as
well, or about any other axis through origin. These are all different
symmetries, but each one is obtained from any other by combining it
with rotations. So in a sense they're all equivalent.
4) A distinction is needed between the operation of space inversion
and its eigenvalue. Parity has a special property: as a symmetry
operation it's represented by a unitary operator:
$P\,P^\dag = P^\dag P = I$. But if $P$ is applied twice it reproduces
the initial state and observables: $P^2 = I$. Then $P^\dag = P$ ($P$
is hermitian) and its only eigenvalues are $p=\pm1$. A state belonging
to $+1$ is said even, one with $p=-1$ is odd.

We've encountered thus far 3 important observables: $H$, $L$, $P$ and
ve've seen that both $L$ and $P$ commute with $H$. Let's add now that
$L$ and $P$ don't commute:
$$P\,L\,P = -L \qquad P\,L = -L\,P.$$
How could we use $H$, $L$, $P\,$'s eigenvalues to classify states? How
could we discover the known degeneracy of $H\,$?
A general theorem ensures us that both couples: $(H,L)$ and $(H,P)$
share a complete set (a base) of eigenvectors. So two classifications
are allowed: $\ket{e_n,l_n}$ and $\ket{e_n,p_n}$, where $e_n$ is n-th
$H$ eigenvalue, $l_n$ n-th $L$ eigenvalue (up to an $\hbar$ factor),
$p_n$ is n-th $P$ eigenvalue, and $n$ runs over integers. We can't
expect instead that a base of common eigenkets exists, something like
$\ket{e_n,l_n,p_n}$.
Note however that the cited theorem doesn't say anything about
degeneracy, meaning that for two different $n$'s we have $e_n=e_{n'}$.
But the following may be proven:
Theorem. For any $\ket{e_n,l_n}$ with $l_n\ne0$ there is $n'$ such
that $e_n=e_{n'}$, $l_n=-l_{n'}$.
Proof. Define
$$\ket\xi = P\,\ket{e_n,l_n}.$$
Then
$$H\,\ket\xi = H\,P\,\ket{e_n,l_n} =
P\,H\,\ket{e_n,l_n} = e_n\,P\,\ket{e_n,l_n} = e_n\,\ket\xi.$$
This shows that $\ket\xi$ is an eigenket of $H$ for the eigenvalue $e_n$.
Moreover
$$L\,\ket\xi = L\,P\,\ket{e_n,l_n} =
-P\,L\,\ket{e_n,l_n} = - l_n\,P\,\ket{e_n,l_n} = -l_n\,\ket\xi$$
and this shows that $\ket\xi$ is an eigenket of $L$ for the
eigenvalue $-l_n$.
So $\ket\xi$ is a simultaneous eigenket of $H$, $L$ for eigenvalues
$e_n$, $-l_n$. If $l_n\ne0$ it's a different eigenket than $\ket{e_n,l_n}$ and we have shown that there is an $n'\ne n$ such that
$$P\,\ket{e_n,l_n} = \ket{e_{n'},l_{n'}}.$$
qed.

Our theorem has proven that a twofold degeneracy exists, for opposite
eigenvalues of $L$. But we know the 2D harmonic oscillator has a
higher degeneracy. Where does it come from? To answer a much richer
symmetry must be introduced. Since this post has already been rather
long I stop here and defer the complete proof to an edit to be
expected tomorrow or later.


text:
Q: Ordered and unordered choices How do I use one of the following formulas:
$$n^r$$
$${n+r-1 \choose r}$$
$$\frac{n!}{(n-r)!}$$
$${n \choose r}$$
(Where $n$ is the set size and $r$ is the number of elements being chosen)
to solve: $$x_1 + x_2 + x_3=101$$
The answer is apparently ${100 \choose 98}={100 \choose 2}=4950$ but I don't understand how they got this answer and what they substituted into which formula.
Can someone please help me understand this?

A: (I assume $x_1, x_2, x_3$ are positive integers.) We want to divide 101 stars between 3 people such that every person has at least one star. Imagine the 101 stars in a row:
$$\star\ \star\ \star\ \dotsb\ \star$$
Now, we want to put 2 bars in this line of stars such that each bar is between two stars. How many places are there for the bars? We can see that there are 100 spaces between adjacent stars, where we can put the bars. So, we can choose the places for the bars in $\binom{100}{2}$ ways (I hope you understand how we get the binomial). Then the first person gets all stars to the left of the first bar, the second person gets all the stars between the two bars, and the last person gets the stars beyond the second bar.
Above, I used 101 stars and 3 people. Can you extend this argument for $n$ stars and $k$ people? What do you get? What if the numbers $x_1, x_2, x_3$ can be 0 as well? Can you change the variables somewhat to accommodate this?


text:
Q: Using Flow designer how do I open a record for editing that was created within the same flow process I am using the Standard 'Order' object called Orders and have installed the Salesforce Labs 'Generate Orders' app.  The app generates a new Order from the Opportunity, pulling in specified fields (Close Date, etc.) - When the process is complete the Order has been created but the user is left on the Opportunity and must navigate to the Related Lists to find and open the new Order.  I want to have the process open the Order after it has been created so that the user can immediately start to fill in the Order (PO number, Amount, etc.) - Here is the flow...

A: If retrieve the created Order into an sObject variable, e.g. sovOrder, then you can create a screen after the Fast Update where the order is activated and use the fields on that screen to capture the Order details then Assign these fields to the relevant sObject and use another Fast Update to assign the updated sObject values to the Order record.
If you have any fields where you want to display values from the order you can set these as the Default values for those fields as follows:-


text:
Q: What can be said about $\{\deg(f),\deg(g),\deg(h)\}$, such that $k[f,g,h]=k[t]$? Let $f=f(t),g=g(t),h=h(t) \in k[t]$, $k$ is a field of characteristic zero.
Denote $\deg(f)=a$, $\deg(g)=b$, $\deg(h)=c$. Assume that $a \geq 2, b \geq 2, c \geq 2$.
Assume that $k[f,g] \neq k[t]$, $k[f,h]\neq k[t]$ and $k[g,h]\neq k[t]$,
but $k[f,g,h]=k[t]$.

What can be said about $a$, $b$ and $c$?

For example, $f=t^2+t$, $g=t^3$, $h=t^6+t^2$; here $a=2$,$b=3$,$c=6$. (How to show that $k[f,h]\neq k[t]$?).
Of course, the inspiration for this question is Abhyankar-Moh-Suzuki theorem.
See also this question.
Any comments are welcome!


text:
Q: Numpy array slicing transposes internal data I am writing a C extension that shall deal with numpy arrays. I have written a function to read and output the numpy array. Using it, I noticed a weird behavior that appears when I use slicing in the input array.
The C function to read the (boolan) array:
char **pymatrix_to_CarrayptrsChar(PyArrayObject *arrayin) {
    char **result, *array;
    int i, n, m, j;

    n = arrayin->dimensions[0];
    m = arrayin->dimensions[1];
    result = ptrvectorChar(n, m);

    array = (char *) arrayin->data; /* pointer to arrayin data as int */
    for (i = 0; i < n; i++) {
      result[i] = &array[i * m];
    }
    printArrChar(result, n, m);
    return result;
}

ptrvectorChar is a function for memory allocation:
char **ptrvectorChar(long dim1) {
    char **v;
    if (!(v = malloc(dim1 * sizeof(char*)))) {
        PyErr_SetString(PyExc_MemoryError,
              "In **ptrvectorChar. Allocation of memory for character array failed.");
        exit(0);
    }
    return v;
}

And printing is done with:
void printArrChar(char **arr, int dim1, int dim2) {
    int i, j;
    for (i = 0; i < dim1; i++) {
        for (j = 0; j < dim2; j++) {
            printf("%i ", arr[i][j]);
        }
        printf("\n");
    }
}

My python script for reproducing the error is:
import numpy as np
import MyExtension
np.random.seed(1)

x = np.array((1,1,1,1,1,1)).astype(bool)
a = np.round(np.random.rand(trialNr, lakeNr)).astype(bool)
aSlicing = a[:, x]

print("a:")
print(a + 0)

print("aSlicing:")
print(aSlicing + 0)

print("C output for a:")
MyExtension.MyFunction(a)

print("C output for aSlicing:")
MyExtension.MyFunction(aSlicing)

Output is:
a:
[[0 1 0 0 0 0]
 [0 0 0 1 0 1]
 [0 1 0 1 0 1]
 [0 0 1 1 0 1]
 [1 1 0 0 0 1]
 [0 0 1 1 1 0]
 [1 1 0 1 1 1]
 [0 1 0 0 1 0]
 [0 0 0 1 0 0]
 [0 0 1 0 1 1]]

aSlicing:
[[0 1 0 0 0 0]
 [0 0 0 1 0 1]
 [0 1 0 1 0 1]
 [0 0 1 1 0 1]
 [1 1 0 0 0 1]
 [0 0 1 1 1 0]
 [1 1 0 1 1 1]
 [0 1 0 0 1 0]
 [0 0 0 1 0 0]
 [0 0 1 0 1 1]]

C output for a:
0 1 0 0 0 0
0 0 0 1 0 1
0 1 0 1 0 1
0 0 1 1 0 1
1 1 0 0 0 1
0 0 1 1 1 0
1 1 0 1 1 1
0 1 0 0 1 0
0 0 0 1 0 0
0 0 1 0 1 1

C output for aSlicing:
0 0 0 0 1 0
1 0 0 0 1 0
1 0 1 0 1 1
0 0 0 0 0 1
0 1 0 0 0 1
0 1 1 1 0 1
1 0 1 0 0 0
0 0 0 1 1 1
0 1 0 1 1 1
1 0 1 0 0 1

As can be seen easily, a and aSlicing are the same arrays for python. However, the C function that reads the data in sees the data as kind of transposed. C regards aSliced as if it were
a.T.reshape((10,6))

Does anyone know why this error appears and how to properly circumvent it? Of course, transposing within the C code is easy. However, I want my program to be able to deal with both types of arrays.
I would prefer a solution within my C extension, i.e. useres of my extension shall not have to care about whether their input is "sliced" or not. Nevertheless, I tried to put a deep copy of aSliced into my extension - which had the same wrong result as aSliced had.
I am working with python 3.4 64bit, numpy 1.9.1, Win8 64bit and Visual Studio 10 64bit C compiler.

A: As hpaulj pointed out, it is possible to figure out the memory structure using the flag F_CONTIGUOUS. I spent a lot of time trying to find a way to read this flag from within C. As far as I found out, it can be done with evaluating the value of trials_array->flags % 2. However, I did not find any reference with a clear explenation for this issue.
trials_array->flags is an integer number. The numpy flag constants NPY_C_CONTIGUOUS, NPY_F_CONTIGUOUS, etc. are integers which are powers of two. It seems to be true that the flag is set if the respective position in the binary representation of trials_array->flags is 1.
Even with knowing the memory structure it is not as trivial as I thought to read the array in. I found a much easier way to convert numpy arrays to C arrays: Use
char *myArray;
PyArrayObject *myArray_Numpy;

PyArray_AsCArray(&myArray_Numpy, (void *) &myArray, myArray_Numpy->dimensions, 2, PyArray_DescrFromType(NPY_BOOL));

//Do something with the array

PyArray_Free(myArray_Numpy, myArray);

I found an example for using these functions here.


text:
Q: GEE, scatter plot. ERROR: array length mismatch In Google Earth Engine i am trying to find scatter between elevation and occurrence but i am getting common number of array vectors
'''
var data=ee.Image("JRC/GSW1_3/GlobalSurfaceWater").clipToBoundsAndScale(geometry);
var dem=ee.Image("USGS/SRTMGL1_003").clipToBoundsAndScale(geometry);
var mask = data.select(['occurrence']).gt(0);
var data = data.updateMask(mask);
var dem = dem.updateMask(mask);
Map.addLayer(dem,'','dem');
Map.addLayer(data,'','data');
Map.addLayer(mask,'','Mask');
var pixelValsY = data.reduceRegion(
    {reducer: ee.Reducer.toList(), geometry: geometry, scale: 30});

var pixelValsX = dem.reduceRegion(
    {reducer: ee.Reducer.toList(), geometry: geometry, scale: 30});

var x = ee.List(pixelValsX.get('elevation'));
var y = ee.List(pixelValsY.get('occurrence'));

var chart = ui.Chart.array.values({array: y, axis: 0, xLabels: x});
print(chart);
'''

Erroe msg is
'Error generating chart: xLabels must be the same length as the 1-D vectors from the array.'
please help me out

A: Worked when specificying the crs field in .reduceRegion so that the two images are in a common projection. Example:
var pixelValsY = data.reduceRegion(
    {reducer: ee.Reducer.toList(), geometry: geometry, scale: 30});

var pixelValsX = dem.reduceRegion(
    {reducer: ee.Reducer.toList(), geometry: geometry, scale: 30, crs: data.projection()});

Alternatively,
var pixelVals = data.addBands(dem).reduceRegion(
    {reducer: ee.Reducer.toList(), geometry: geometry, scale: 30})
var x = ee.List(pixelVals.get('elevation'));
var y = ee.List(pixelVals.get('occurrence'));

In this second example (two less lines of code), it appears that stacking the images sets them to some sort of common projection.


text:
Q: How to display   in XML output I am generating the XML output using XSLT. I need to display   in the XML output. I have tried few options to display   but it displays  . Can anyone help me on this issue?
Thanks.

A: Unless your XML has a DTD which says what   means, you cannot use  . The only reason this works in HTML is because the XHTML DTD defines what it means (for XHTML) or it's just baked in to the parser (HTML).
In general you should not use named character entities in XML because such documents cannot be parsed properly without their DTD. (And DTDs are a big hassle.) Use the character directly, or use a numeric character reference.
For a non-breaking space, you can use   or  , which are the decimal and hexadecimal unicode code point numbers respectively.

A: I don't know if this is what you want, but, here it is anyways
<?xml version="1.0"?>
<hello>&nbsp;</hello>

output:
<hello> </hello>

A: Define nbsp entity inline:
<!DOCTYPE inline_dtd[
<!ENTITY nbsp " ">
]>


text:
Q: Problems installing RCPLEX I get an error while I try to install RCPLEX on my Computer and I can't figure out what to do. There is no information what so ever on the internet regarding my problem.
R Marcel$ R CMD INSTALL --configure-args="PKG_CFLAGS='-m64 -fPIC' PKG_CPPFLAGS=-I/Users/Marcel/Applications/CPLEX_Studio129/cplex/include/ilcplex PKG_LIBS='-L/Users/Marcel/Applications/CPLEX_Studio129/cplex/lib/x86-64_osx/static_pic -lcplex -lm -m64 -lpthread -framework CoreFoundation -framework IOKit'" Rcplex
* installing to library '/Users/Marcel/Library/R/3.5/library'
* installing *source* package 'Rcplex' ...
** Paket 'Rcplex' erfolgreich entpackt und MD5 Summen überprüft
checking for gcc... clang
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether clang accepts -g... yes
checking for clang option to accept ANSI C... none needed
checking how to run the C preprocessor... clang -E
checking for egrep... grep -E
checking for ANSI C header files... rm: conftest.dSYM: is a directory
rm: conftest.dSYM: is a directory
no
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking ilcplex/cplex.h usability... no
checking ilcplex/cplex.h presence... no
checking for ilcplex/cplex.h... no
configure: error: CPLEX header cplex.h not found
ERROR: configuration failed for package 'Rcplex'
* removing '/Users/Marcel/Library/R/3.5/library/Rcplex'

I am using Mac OS Mojave and I followed every step from this instruction and everything worked out fine until step 2:
http://jrzubizarreta.com/INSTALL
R, IBM CPLEX, R studio, my computer... everything is 64 bit as required.
The path and the file "cplex.h" is there. I checked it.
I sadly have no experience with makefiles or compilers.
I would be grateful if someone could please help me!