问:
Java - can you create a helper class with methods with same name but possibly can take diff arguments
looking for some help...
In Java - i am trying to find if i can have a helper class which basically has several methods:

```<code> class helper{
method1(){doing something}
method2(){doing something}
method_important(String a, String b){doing something}
method_important(String a, int b, String b){doing something}
}
</code>```

Notably i want to call helper class with method_important from other classes but want a flexiblity to pass desired arguments as i it can be two strings or i may have to pass String, int, String....
is it even possible? if no? what is best way to achieve it?
Problem is from my other methods i need to pass different type of variables..

答: That's perfectly posible in Java, and it is called method overloading. Check this out https://www.javatpoint.com/method-overloading-in-java</p>

Body:
looking for some help...
In Java - i am trying to find if i can have a helper class which basically has several methods:

 class helper{
method1(){doing something}
method2(){doing something}
method_important(String a, String b){doing something}
method_important(String a, int b, String b){doing something}
}

Notably i want to call helper class with method_important from other classes but want a flexiblity to pass desired arguments as i it can be two strings or i may have to pass String, int, String....
is it even possible? if no? what is best way to achieve it?
Problem is from my other methods i need to pass different type of variables..


来源: stackexchange

问:
Volley error occurs while swiping between fragments/viewpager
In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping.  After this , no data is available on fragment and any of the other pages. This is my code</p>

```<code>fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);

    public class FragmentParent extends Fragment {
        private TabLayout tabLayout;
        private ViewPager viewPager;
        private ViewPagerAdapter1 adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });
    }

    public void addPage(String pagename, String id,String shop_id) {
        Bundle bundle = new Bundle();
        bundle.putString("data", id);
        bundle.putString("shop_id", shop_id);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }
}

public class FragmentChild extends Fragment {
    String childname,shoppe_id;
    RecyclerView imgflag;
    CategoryItemAdapter categoryItemAdapter;
    HttpStack stack;
    List<ShopDetails> cat_item_list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        Bundle bundle = getArguments();
        childname = bundle.getString("data");
        shoppe_id=bundle.getString("shop_id");
        stack = new HurlStack();
        imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
        cat_item_list = new ArrayList<ShopDetails>();
        categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
        GridLayoutManager layoutManager
                = new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
        imgflag.setLayoutManager(layoutManager);
        imgflag.setAdapter(categoryItemAdapter);
       getCategoryItem(childname);
        return view;
    }

    public void getCategoryItem(String cat_id)
    {

        stack = new HurlStack(null, createSslSocketFactory());
        final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
        String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.equals("0 results"))
                {

                }
                else
                {

                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        for(int i=0;i<jsonArray.length();i++)
                        {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);
                            ShopDetails shopDetails=new ShopDetails();
                            shopDetails.setItem_name(jsonObject.getString("item_name"));
                            shopDetails.setItem_image(jsonObject.getString("image"));
                            shopDetails.setItem_price(jsonObject.getString("price"));
                            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
                            cat_item_list.add(shopDetails);
                        }
                        if(cat_item_list!=null)
                        {

                            categoryItemAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("shoppe_id", shoppe_id);
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        stringRequest.setShouldCache(false);
        requestQueue.add(stringRequest);
    }
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};

        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
          Log.e(TAG, StringUtils.EMPTY, e);
        } catch (KeyManagementException e) {
           Log.e(TAG, StringUtils.EMPTY, e);
        }
        return sslSocketFactory;
    }
    public final boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

            return true;
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {

            return false;
        }
        return false;
    }
}
</code>```

答:
you need to use validation while receiving response from volley just use condition like that :

```<code> if(response!=null&&response.length()>10){
    try {
        JSONArray jsonArray=new JSONArray(response);
        for(int i=0;i<jsonArray.length();i++)
        {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            ShopDetails shopDetails=new ShopDetails();
            shopDetails.setItem_name(jsonObject.getString("item_name"));
            shopDetails.setItem_image(jsonObject.getString("image"));
            shopDetails.setItem_price(jsonObject.getString("price"));
            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
            cat_item_list.add(shopDetails);
        }
        if(cat_item_list!=null)
        {

            categoryItemAdapter.notifyDataSetChanged();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}else{
    Log.e("invalid","invalide responce");
}
</code>```

OR
 also add condition on :
cat_id!=0 OR cat_id!=null
 String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;

ContentLicense: CC BY-SA 3.0

Body:
In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping.  After this , no data is available on fragment and any of the other pages. This is my code

fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);

    public class FragmentParent extends Fragment {
        private TabLayout tabLayout;
        private ViewPager viewPager;
        private ViewPagerAdapter1 adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);
        getIDs(view);
        setEvents();
        return view;
    }

    private void getIDs(View view) {
        viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
        adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
        viewPager.setAdapter(adapter);
    }

    int selectedTabPosition;

    private void setEvents() {

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                viewPager.setCurrentItem(tab.getPosition());
                selectedTabPosition = viewPager.getCurrentItem();
                Log.d("Selected", "Selected " + tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                Log.d("Unselected", "Unselected " + tab.getPosition());
            }
        });
    }

    public void addPage(String pagename, String id,String shop_id) {
        Bundle bundle = new Bundle();
        bundle.putString("data", id);
        bundle.putString("shop_id", shop_id);
        FragmentChild fragmentChild = new FragmentChild();
        fragmentChild.setArguments(bundle);
        adapter.addFrag(fragmentChild, pagename);
        adapter.notifyDataSetChanged();
        if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);

        viewPager.setCurrentItem(adapter.getCount() - 1);
        setupTabLayout();
    }

    public void setupTabLayout() {
        selectedTabPosition = viewPager.getCurrentItem();
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
        }
    }
}

public class FragmentChild extends Fragment {
    String childname,shoppe_id;
    RecyclerView imgflag;
    CategoryItemAdapter categoryItemAdapter;
    HttpStack stack;
    List<ShopDetails> cat_item_list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child, container, false);
        Bundle bundle = getArguments();
        childname = bundle.getString("data");
        shoppe_id=bundle.getString("shop_id");
        stack = new HurlStack();
        imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
        cat_item_list = new ArrayList<ShopDetails>();
        categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
        GridLayoutManager layoutManager
                = new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
        imgflag.setLayoutManager(layoutManager);
        imgflag.setAdapter(categoryItemAdapter);
       getCategoryItem(childname);
        return view;
    }

    public void getCategoryItem(String cat_id)
    {

        stack = new HurlStack(null, createSslSocketFactory());
        final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
        String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.equals("0 results"))
                {

                }
                else
                {

                    try {
                        JSONArray jsonArray=new JSONArray(response);
                        for(int i=0;i<jsonArray.length();i++)
                        {
                            JSONObject jsonObject=jsonArray.getJSONObject(i);
                            ShopDetails shopDetails=new ShopDetails();
                            shopDetails.setItem_name(jsonObject.getString("item_name"));
                            shopDetails.setItem_image(jsonObject.getString("image"));
                            shopDetails.setItem_price(jsonObject.getString("price"));
                            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
                            cat_item_list.add(shopDetails);
                        }
                        if(cat_item_list!=null)
                        {

                            categoryItemAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("shoppe_id", shoppe_id);
                return params;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        stringRequest.setShouldCache(false);
        requestQueue.add(stringRequest);
    }
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};

        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
          Log.e(TAG, StringUtils.EMPTY, e);
        } catch (KeyManagementException e) {
           Log.e(TAG, StringUtils.EMPTY, e);
        }
        return sslSocketFactory;
    }
    public final boolean isInternetOn() {
        ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

            return true;
        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {

            return false;
        }
        return false;
    }
}

Body:
you need to use validation while receiving response from volley just use condition like that :

 if(response!=null&&response.length()>10){
    try {
        JSONArray jsonArray=new JSONArray(response);
        for(int i=0;i<jsonArray.length();i++)
        {
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            ShopDetails shopDetails=new ShopDetails();
            shopDetails.setItem_name(jsonObject.getString("item_name"));
            shopDetails.setItem_image(jsonObject.getString("image"));
            shopDetails.setItem_price(jsonObject.getString("price"));
            shopDetails.setItem_desc(jsonObject.getString("ingredients"));
            cat_item_list.add(shopDetails);
        }
        if(cat_item_list!=null)
        {

            categoryItemAdapter.notifyDataSetChanged();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}else{
    Log.e("invalid","invalide responce");
}

OR
 also add condition on :
cat_id!=0 OR cat_id!=null
 String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;


问:
JavaScript changing CSS not working inside of if statement
Here is my html :

```<code><a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php" onmouseover="rotateBtn()"> Sign up »</a>
</code>```

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

```<code>function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

答:
Actually there were few more issues; I created a wrapper div added css transform on that div. Now it works

document.getElementById("signUpBtn").onmouseover = rotateBtn;
document.getElementById("signUpBtn").onmouseout = unrotateBtn;

function commonStyle() {
document.getElementById("wrapperDiv").style.transformOrigin = "top center";
document.getElementById("wrapperDiv").style.transition = "1s ease-in-out";
}

function rotateBtn() {
commonStyle()
document.getElementById("wrapperDiv").style.transform = "rotate(90deg)";
}

function unrotateBtn() {
commonStyle()
document.getElementById("wrapperDiv").style.transform = "rotate(0deg)";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height:100px;
  width:100px;
}</code>```

     Sign up »

```

Body:
Here is my html :

 Sign up »

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

Body:
Actually there were few more issues; I created a wrapper div added css transform on that div. Now it works

document.getElementById("signUpBtn").onmouseover = rotateBtn;
document.getElementById("signUpBtn").onmouseout = unrotateBtn;

function commonStyle() {
document.getElementById("wrapperDiv").style.transformOrigin = "top center";
document.getElementById("wrapperDiv").style.transition = "1s ease-in-out";
}

function rotateBtn() {
commonStyle()
document.getElementById("wrapperDiv").style.transform = "rotate(90deg)";
}

function unrotateBtn() {
commonStyle()
document.getElementById("wrapperDiv").style.transform = "rotate(0deg)";
}

div {
  height:100px;
  width:100px;
}

<div id="wrapperDiv">
<a class="btn btn-primary btn-lg" id="signUpBtn"
     href="./pages/createaccount.php" >
     Sign up &raquo;</a>
 </div>


问:
In opencv,It's too slow by use Mat type to calculate the Mahalanobis distance. How can i improve the efficiency？
```<code>Mat imv;
Mat_<double>end(1, 1);
double distance;
Mat_<double>Point(1, 3);
...
imv = Point.t();
end = Point*inv[m]*imv;
distance = sqrt(end(0, 0));
</code>```

there is the definition of the variable type and the calculation process of mahalanobis distance.

答:
I am sorry about the expression is not clear.I try to traverse every pixel in the image, calculate the Mahalanobis distance between them and the color model and is too slow.I've always thought that optimization should be done from the efficiency of matrix multiplication.Today I improve the efficiency by use Multi-threaded to improve circulation speed and it is useful.</p>

```<code>#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Mat_<double>end(1, 1);
                double distance = 1000;
                Mat_<double>Point(1, 3);
                 Point(0, 0) = double(data3[j * 3]) - mean1[m].at<double>(0, 0);
                Point(0, 1) = double(data3[j * 3 + 1]) - mean1[m].at<double>(0, 1);
                Point(0, 2) = double(data3[j * 3 + 2]) - mean1[m].at<double>(0, 2);

                end = Point * inv[m] * Point.t();
                distance = sqrt(end(0, 0));
                }
            }
</code>```

Body:
Mat imv;
Mat_<double>end(1, 1);
double distance;
Mat_<double>Point(1, 3);
...
imv = Point.t();
end = Point*inv[m]*imv;
distance = sqrt(end(0, 0));

there is the definition of the variable type and the calculation process of mahalanobis distance.

Body:
I am sorry about the expression is not clear.I try to traverse every pixel in the image, calculate the Mahalanobis distance between them and the color model and is too slow.I've always thought that optimization should be done from the efficiency of matrix multiplication.Today I improve the efficiency by use Multi-threaded to improve circulation speed and it is useful.

#pragma omp parallel for num_threads(6)
            for (int m = 0; m < k_num; m++) {
                Mat_<double>end(1, 1);
                double distance = 1000;
                Mat_<double>Point(1, 3);
                 Point(0, 0) = double(data3[j * 3]) - mean1[m].at<double>(0, 0);
                Point(0, 1) = double(data3[j * 3 + 1]) - mean1[m].at<double>(0, 1);
                Point(0, 2) = double(data3[j * 3 + 2]) - mean1[m].at<double>(0, 2);

                end = Point * inv[m] * Point.t();
                distance = sqrt(end(0, 0));
                }
            }


问:
Custom Cell Row Height setting in storyboard is not responding
I am trying to adjust the cell height for one of the cells on my table view. I am adjusting the size from the "row height" setting inside the "size inspector" of the cell in question. When I run the app on my iPhone the cell has the default size set from the "row size" in the table view.

If I change the "row size" of the table view then the size of all cells changes. I do not want to do that as I want a custom size only for one cell. I have seen a lot of posts that have a programmatic solution to the problem, but I would prefer to do it through storyboard, if that is possible.

答:
The same problem occurred when working on XCode 9 using Swift 4.

Add AutoLayout for the UI elements inside the Cell and custom cell row height will work accordingly as specified.


问:
Gluu redirect after registration
I have just started working with Gluu, and mostly it is working exactly as I want it to.
However I am experiencing some difficulties with registration.
Currently when a user registeres he/she is redirected to the gluu page. What I would like to happen is the user being redirected back to the page that sent the user to the registration page(or at the very least a static page).

I know that this needs to be done in the postRegistration part och the user registration script, however I am not quite sure about what it is that I need to do.

So has anyone done something like this before?

Edit:

So this is where I am currently at...
The postRegistration function takes in 4 parameters, self, user, requestParameters and configurationAttributes.

self I assume is just a reference to itself and therefore it is not really valuable in this case as there are no set functions that redirects in that class and it does not seem to hold any valuable parameters.

user is the user that is about to be registered and is sent down from org.gluu.oxtrust.action.RegisterPersonAction and is a org.gluu.oxtrust.model.GluuCustomPerson Object.
I believe that this is my best bet at fixing this problem... although I am not sure about how.
It does have a function setSourceServerName that seemed promising, but setting it did not change the outcome in any way.

requestParameters is just the query parameters sent in the URL. I tried setting these to valid openid code authentication parameters, but it had no effect.

configurationAttributes is simply the static parameters sent into the script from Gluu (just parameters set statically to the script)

Moreover the function must return a boolean so I assume that what needs to be done is changing the input parameters as a side effect and thus my only two options are the user object and requestParameters. requestParameters seems to be just a private map object in the registerPersonAction class, which does not seem to do anything special with it, so changing this shouldn't have the outcome that I want.
Therefore it must be the user object that I need to modify. However as previously stated, I do not yet know in what way

答: As a dirty hack you can edit the gluu pages to insert javascript that redirects the user</p>

Title: Gluu redirect after registration


问:
Why React's PureComponent is recommended to have all its children "pure"
Having read the official React documentation, I've came across this regarding PureComponent:

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop
  updates for the whole component subtree. Make sure all the children
  components are also “pure”.

Why exactly does skipping props updates for the whole subtree means avoiding non-pure components? what would be the consequences of a non-pure component inside a PureComponent's component subtree (both in general and in the case when it's not designed/supposed to respond to props change).

答:
Each prop should be immutable. It needs to easier debug.
For example. You put array of users via props. But, one of components do: user.name = value.
Children components may be much, and you will difficult understand, what is  component updates the user?</p>


问:
Laravel update Query not work Call to a member function fill() on null
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

```<code>  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}
</code>```

Here is venue model function for parameter

```<code>    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}
</code>```

Here is my venueparameter model

```<code><?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }
</code>```

Here is what i gt when i dd($request->all())

```<code>                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0
</code>```

Here is what i gt when i dd($venue)

```<code>  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"
</code>```

]

How can i overcome on this problem?

答:
Becuase you are doing it wrong way here

$venue = false;

according to api doc object must be the instance of laravel Model.

so try changing it to the respective model

$venue = new Venue();

if your model is Venue

Body:
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}

Here is venue model function for parameter

    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}

Here is my venueparameter model

<?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }

Here is what i gt when i dd($request->all())

                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0

Here is what i gt when i dd($venue)

  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"

]

How can i overcome on this problem?


问:
Update error in mysql Query taking data from another table
I am trying to update the orgaization_id in location table which is primary key in Organization table.

```<code>update location set organization_id=org.old_id from organization as org
where location.old_id=org.old_id;
</code>```

Facing syntax error please help..

答:
You can use join to perform update from another table</p>

```<code>update location l
join organization as o
on l.old_id=o.old_id
set l.organization_id=o.old_id;
</code>```

Body:
I am trying to update the orgaization_id in location table which is primary key in Organization table.

update location set organization_id=org.old_id from organization as org
where location.old_id=org.old_id;

Facing syntax error please help..

Body:
You can use join to perform update from another table

update location l
join organization as o
on l.old_id=o.old_id
set l.organization_id=o.old_id;


问:
ActionBlock never completes on Faulted State
I am trying to make a simple program to better understand TPL Dataflow. I am trying to create a long running task that will restart a dataflow block if it has completed.

My current RestartActionBlock Task is able to await completion of the ActionBlock if I explicitly call complete on the block by entering "-1". But when I try to raise an exception to fault the block or call the blocks Fault() interface method, the ActionBlock's Completion Task never completes. In this situation the await singleTestFlow.Completion; call never continues.

After raising the Exception or calling the Fault() method, I can be sure the block is in the faulted state by trying to enter another input into the program and debugging the code to see that the block is in the faulted state:

If the block is in the faulted state, why did the await singleTestFlow.Completion; never return?

```<code>class Program
{
    private static ActionBlock<string> singleTestFlow;

    static void Main(string[] args)
    {
        //start thread that should restart a completed action block
        Task.Run(RestartActionBlock);

        Console.WriteLine("Enter -0 to exit, -1 to complete flow, -0- to throw an exception, Anything else otherwise");
        var input = Console.ReadLine();

        //allow user to input text until "-0" is entered
        while (!input.Equals("-0"))
        {
            if (input.Equals("-1"))
            {
                singleTestFlow.Complete();
            }

            singleTestFlow.Post(input);

            input = Console.ReadLine();
        }

        async Task RestartActionBlock()
        {
            var iterations = 0;
            while (true)
            {
                singleTestFlow = new ActionBlock<string>(s =>
                {
                    if (s.Equals("-0-"))
                    {
                        //throw new Exception("Something went wrong in here");
                        ((IDataflowBlock)singleTestFlow).Fault(new Exception("Something went wrong in here"));
                    }
                    Console.WriteLine($"{iterations}: " + s);

                }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount });

                await singleTestFlow.Completion;

                var completionTask = singleTestFlow.Completion;

                var message = $"action block: {iterations} ";
                switch (completionTask.Status)
                {
                    case TaskStatus.RanToCompletion:
                        message += "ran to completion";
                        break;
                    case TaskStatus.Canceled:
                        message += "was canceled";
                        break;
                    case TaskStatus.Faulted:
                        message += "has faulted";
                        Console.WriteLine(completionTask.Exception);
                        break;
                }
                Console.WriteLine(message);
                iterations++;
            }
        }
    }

}
</code>```

The point in the console where i entered "eee" is where the faulted block debug screenshot was taken.

答:
Here's the simple fix:

Replace

```<code>await singleTestFlow.Completion; // Throws if Completion is faulted, breaking your loop.
</code>```

with

```<code>await Task.WhenAny(singleTestFlow.Completion);
</code>```

or

```<code>await singleTestFlow.Completion.ContinueWith(_ => { });
</code>```

What the above does is avoid propagating the Completion task exception. This allows your RestartActionBlock loop to execute forever as you intended (as opposed to dying right after your block faults).

Ideally, however, you should not be disregarding the return values of the following two statements:

```<code>Task.Run(RestartActionBlock); // Unobserved Task. Usually a bad idea.
</code>```

and

```<code>singleTestFlow.Post(input);
</code>```

If you were observing the return values of the above, you'd actually notice that they start screaming for help as soon as your ActionBlock<string> faults.

The task returned by Task.Run(RestartActionBlock) transitions to Faulted state as soon as await singleTestFlow.Completion throws - but you never get notified, because you don't keep a reference to said task, or check its status.

Similarly, right after your ActionBlock<string> faults, subsequent calls to singleTestFlow.Post(input) actually return false, meaning that no more items get posted to the block. They are simply discarded.

Body:
I am trying to make a simple program to better understand TPL Dataflow. I am trying to create a long running task that will restart a dataflow block if it has completed.

My current RestartActionBlock Task is able to await completion of the ActionBlock if I explicitly call complete on the block by entering "-1". But when I try to raise an exception to fault the block or call the blocks Fault() interface method, the ActionBlock's Completion Task never completes. In this situation the await singleTestFlow.Completion; call never continues.

After raising the Exception or calling the Fault() method, I can be sure the block is in the faulted state by trying to enter another input into the program and debugging the code to see that the block is in the faulted state:

If the block is in the faulted state, why did the await singleTestFlow.Completion; never return?

class Program
{
    private static ActionBlock<string> singleTestFlow;

    static void Main(string[] args)
    {
        //start thread that should restart a completed action block
        Task.Run(RestartActionBlock);

        Console.WriteLine("Enter -0 to exit, -1 to complete flow, -0- to throw an exception, Anything else otherwise");
        var input = Console.ReadLine();

        //allow user to input text until "-0" is entered
        while (!input.Equals("-0"))
        {
            if (input.Equals("-1"))
            {
                singleTestFlow.Complete();
            }

            singleTestFlow.Post(input);

            input = Console.ReadLine();
        }

        async Task RestartActionBlock()
        {
            var iterations = 0;
            while (true)
            {
                singleTestFlow = new ActionBlock<string>(s =>
                {
                    if (s.Equals("-0-"))
                    {
                        //throw new Exception("Something went wrong in here");
                        ((IDataflowBlock)singleTestFlow).Fault(new Exception("Something went wrong in here"));
                    }
                    Console.WriteLine($"{iterations}: " + s);

                }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount });

                await singleTestFlow.Completion;

                var completionTask = singleTestFlow.Completion;

                var message = $"action block: {iterations} ";
                switch (completionTask.Status)
                {
                    case TaskStatus.RanToCompletion:
                        message += "ran to completion";
                        break;
                    case TaskStatus.Canceled:
                        message += "was canceled";
                        break;
                    case TaskStatus.Faulted:
                        message += "has faulted";
                        Console.WriteLine(completionTask.Exception);
                        break;
                }
                Console.WriteLine(message);
                iterations++;
            }
        }
    }

}

The point in the console where i entered "eee" is where the faulted block debug screenshot was taken.

Body:
Here's the simple fix:

Replace

await singleTestFlow.Completion; // Throws if Completion is faulted, breaking your loop.

with

await Task.WhenAny(singleTestFlow.Completion);

or

await singleTestFlow.Completion.ContinueWith(_ => { });

What the above does is avoid propagating the Completion task exception. This allows your RestartActionBlock loop to execute forever as you intended (as opposed to dying right after your block faults).

Ideally, however, you should not be disregarding the return values of the following two statements:

Task.Run(RestartActionBlock); // Unobserved Task. Usually a bad idea.

and

singleTestFlow.Post(input);

If you were observing the return values of the above, you'd actually notice that they start screaming for help as soon as your ActionBlock<string> faults.

The task returned by Task.Run(RestartActionBlock) transitions to Faulted state as soon as await singleTestFlow.Completion throws - but you never get notified, because you don't keep a reference to said task, or check its status.

Similarly, right after your ActionBlock<string> faults, subsequent calls to singleTestFlow.Post(input) actually return false, meaning that no more items get posted to the block. They are simply discarded.


问:
HTML Chrome Extension
Trying to retrieve current URL from the tab. The goal is to be able to click on this extension and it automatically pulls the search information for the domain of the current chrome table. trying to use this search url to pull whatever "www.apple.com" tab window url is currently being visited into the extension to get company information. </p>

<p>Heres what I have:
popup.html
    </p>

```<code>    <head>

        <title>
            Chrome Extension
        </title>

        <script src="offline.js"></script>

    </head>

    <body>

        <iframe src="https://www.owler.com/iaApp/browsecompanyprofiles.htm?searchTerm=$activeTab” oncontextmenu="return false;">
            ERROR, can't load content
        </iframe>

    <script>
  chrome.tabs.query({active: true, currentWindow: true}, function(arrayOfTabs) {
     var activeTab = arrayOfTabs[0];
     var activeTabId = activeTab.id;
  });
function getCookie(cname)
    {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');

        for(var i = 0; i <ca.length; i++)
        {
            var c = ca[i];
            while (c.charAt(0) == ' ')
        {
        c = c.substring(1);
    }

    if (c.indexOf(name) == 0)
    {
    return c.substring(name.length, c.length);
    }
}
return "";
}

if(getCookie('hostinger')) {
document.cookie = 'hostinger=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';location.reload();
}
var notification = document.getElementsByClassName('notice notice-success is-dismissible');
if(notification.length > 0) {
notification = notification[0];
notification.setAttribute('style', "padding-bottom: 10px; padding-top: 5px; background-image: url(https://cdn.rawgit.com/hostinger/banners/master/hostinger-bf-bg.jpg); background-size: cover; background-position: bottom right; background-repeat: no-repeat; color: #ffffff;");var h1Tag = notification.getElementsByTagName("H1")[0];h1Tag.setAttribute('style', "color:#f15f5f;font-weight:700;");h1Tag.innerHTML = "Get 90% Discount for Premium Web Hosting";var link = notification.getElementsByTagName("P")[0].getElementsByTagName('A')[0];link.setAttribute('style', "color:#f15f5f");var list = notification.getElementsByTagName("UL")[0];var listElements = list.getElementsByTagName("LI");for (var i = 0; i < listElements.length; i++) {listElements[i].setAttribute('style', "color:#ffffff");}}

        <iframe src="https://www.owler.com/iaApp/browsecompanyprofiles.htm?searchTerm=$activeTab” oncontextmenu="return false;">
            ERROR, can't load content
        </iframe>
</script></body>

</html>

<style>

html, body{
    margin: 0px;
    padding: 0px;
}

iframe{
    width: 400px;
    height: 600px;
    border: none;
}

</style>
</code>```

答: window.location.href will give you the url of the current tab

Title: HTML Chrome Extension

Body:
Trying to retrieve current URL from the tab. The goal is to be able to click on this extension and it automatically pulls the search information for the domain of the current chrome table. trying to use this search url to pull whatever "www.apple.com" tab window url is currently being visited into the extension to get company information.

Heres what I have:
popup.html

        <title>
            Chrome Extension
        </title>

            ERROR, can't load content


问:
Console animations
I just want to know how to create simple animations like blinking, moving stuffs on C# console applications. Is there any special method for this?</p>

答:
Great work with the ConsoleSpinner and the sequence implementation. Thanks for the code. I thought about sharing my customized approach.

    public class ConsoleSpinner
    {
        static string[,] sequence = null;

        public int Delay { get; set; } = 200;

        int totalSequences = 0;
        int counter;

        public ConsoleSpinner()
        {
            counter = 0;
            sequence = new string[,] {
                { "/", "-", "\\", "|" },
                { ".", "o", "0", "o" },
                { "+", "x","+","x" },
                { "V", "<", "^", ">" },
                { ".   ", "..  ", "... ", "...." },
                { "=>   ", "==>  ", "===> ", "====>" },
               // ADD YOUR OWN CREATIVE SEQUENCE HERE IF YOU LIKE
            };

            totalSequences = sequence.GetLength(0);
        }

        ///
        ///
        ///
        /// <param name="sequenceCode"> 0 | 1 | 2 |3 | 4 | 5 </param>
        public void Turn(string displayMsg = "", int sequenceCode = 0)
        {
            counter++;

            Thread.Sleep(Delay);

            sequenceCode = sequenceCode > totalSequences - 1 ? 0 : sequenceCode;

            int counterValue = counter % 4;

            string fullMessage = displayMsg + sequence[sequenceCode, counterValue];
            int msglength = fullMessage.Length;

            Console.Write(fullMessage);

            Console.SetCursorPosition(Console.CursorLeft - msglength, Console.CursorTop);
        }
    }
```
<p><strong>Implementation:</strong></p>
<pre class="lang-cs prettyprint-override"><code>    ConsoleSpinner spinner = new ConsoleSpinner();
    spinner.Delay = 300;
    while (true)
    {
        spinner.Turn(displayMsg: "Working ",sequenceCode:5);
    }
</code>```

Output:

ContentLicense: CC BY-SA 2.5

Title: Console animations

Body:
Great work with the ConsoleSpinner and the sequence implementation. Thanks for the code. I thought about sharing my customized approach.

    public class ConsoleSpinner
    {
        static string[,] sequence = null;

        public int Delay { get; set; } = 200;

        int totalSequences = 0;
        int counter;

        public ConsoleSpinner()
        {
            counter = 0;
            sequence = new string[,] {
                { "/", "-", "\\", "|" },
                { ".", "o", "0", "o" },
                { "+", "x","+","x" },
                { "V", "<", "^", ">" },
                { ".   ", "..  ", "... ", "...." },
                { "=>   ", "==>  ", "===> ", "====>" },
               // ADD YOUR OWN CREATIVE SEQUENCE HERE IF YOU LIKE
            };

            totalSequences = sequence.GetLength(0);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sequenceCode"> 0 | 1 | 2 |3 | 4 | 5 </param>
        public void Turn(string displayMsg = "", int sequenceCode = 0)
        {
            counter++;

            Thread.Sleep(Delay);

            sequenceCode = sequenceCode > totalSequences - 1 ? 0 : sequenceCode;

            int counterValue = counter % 4;

            string fullMessage = displayMsg + sequence[sequenceCode, counterValue];
            int msglength = fullMessage.Length;

            Console.Write(fullMessage);

            Console.SetCursorPosition(Console.CursorLeft - msglength, Console.CursorTop);
        }
    }

Implementation:

    ConsoleSpinner spinner = new ConsoleSpinner();
    spinner.Delay = 300;
    while (true)
    {
        spinner.Turn(displayMsg: "Working ",sequenceCode:5);
    }

Output:

ContentLicense: CC BY-SA 4.0


问:
What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?
In Eclipse on Windows can I press myObject.ctrl+space to get a list of all methods for the object. But on Mac OS X this doesn't seem to work. I have tried ctrl+space, cmd+space and alt+space but nothing seems to work.

What is the keyboard shortcut for method suggestions in Eclipse on Mac OS X?

答:
By default I believe it's ctrl+space. You can check by going to Preferences > General > Keys and filtering for 'content assist'.

If it's not working, you may have a binding from OS X or another application overriding it. If a window with a blank list is popping up, you may need to adjust which suggestions are shown by default in Preferences > Java > Editor > Content Assist > Advanced. You can continue pressing the binding to cycle through the different types of suggestions.


问:
WSO2 IOT : is Apple VPP or DEP available now in wso2?
As the question suggests, anyone know if the WSO2 IOT Server supports apple DEP or VPP for MDM management?</p>

答: WSO2 IoT Server does support DEP. However, the implementation is still in experimental form and we have not merged the features to the main product as yet. You can expect DEP support to be available in future releases.</p>


问:
Adding site collection to Web Application logged in as FBA in SharePoint 2010
Hi
I am trying to create Site collection under web application which is configured as Claim based authentication and the code is as follow:

```<code>SPSecurity.RunWithElevatedPrivileges(delegate {
  using (SPSite site = SPContext.Current.Site)
  {
    using (SPWeb web = site.RootWeb)
    {
      site.AllowUnsafeUpdates = true;
      web.AllowUnsafeUpdates = true;
      try
      {
        SPWebApplication web_App = web.Site.WebApplication;
        web_App.Sites.Add(SiteUrl, SiteTitle, Description, Convert.ToUInt32(Constants.LOCALE_ID_ENGLISH), SiteTemplate, OwnerLogin, "testuser", OwnerEmail);
      }
      catch (Exception ex)
      {
        string s = ex.Message + " " + ex.StackTrace;
        throw;
      }
      finally
      {
        web.AllowUnsafeUpdates = false;
        site.AllowUnsafeUpdates = false;
      }
    }
  }
});
</code>```

Here I am passing "OwnerLogin" as "CustomMembership:UserName". But web_App.Sites.Add is throwing a wierd error like "ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}". Any help in this regard is really appreciated.

Regards,

Paddy

答:
Your elevation code is wrong, you need to create completely new SPSite and SPWeb references. I normal prefix them with "c" to show me that it is in a different context.</p>

```<code>SPSecurity.RunWithElevatedPrivileges(delegate() {
    using (SPSite csite = new SPSite(SPContext.Current.Site.ID)) {
        using (SPWeb cweb = csite.OpenWeb(SPContext.Current.Site.RootWeb.ID)) {
            //do stuff
        }
    }
});
</code>```

Body:
Hi
I am trying to create Site collection under web application which is configured as Claim based authentication and the code is as follow:

SPSecurity.RunWithElevatedPrivileges(delegate {
  using (SPSite site = SPContext.Current.Site)
  {
    using (SPWeb web = site.RootWeb)
    {
      site.AllowUnsafeUpdates = true;
      web.AllowUnsafeUpdates = true;
      try
      {
        SPWebApplication web_App = web.Site.WebApplication;
        web_App.Sites.Add(SiteUrl, SiteTitle, Description, Convert.ToUInt32(Constants.LOCALE_ID_ENGLISH), SiteTemplate, OwnerLogin, "testuser", OwnerEmail);
      }
      catch (Exception ex)
      {
        string s = ex.Message + " " + ex.StackTrace;
        throw;
      }
      finally
      {
        web.AllowUnsafeUpdates = false;
        site.AllowUnsafeUpdates = false;
      }
    }
  }
});

Here I am passing "OwnerLogin" as "CustomMembership:UserName". But web_App.Sites.Add is throwing a wierd error like "ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}". Any help in this regard is really appreciated.

Regards,

Paddy

Body:
Your elevation code is wrong, you need to create completely new SPSite and SPWeb references. I normal prefix them with "c" to show me that it is in a different context.

SPSecurity.RunWithElevatedPrivileges(delegate() {
    using (SPSite csite = new SPSite(SPContext.Current.Site.ID)) {
        using (SPWeb cweb = csite.OpenWeb(SPContext.Current.Site.RootWeb.ID)) {
            //do stuff
        }
    }
});


问:
Recursive function to add all the digits

I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

```<code>def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10
</code>```

答:
Try this:</p>

```<code>def digit_sum(n):
    """ Recursively add the digits of a positive integer until the sum
    becomes a single digit. Return the sum. """

    sum_of_digits = sum(int(digit) for digit in str(n))
    if sum_of_digits < 10:
        return sum_of_digits
    else:
        return digit_sum(sum_of_digits)

>>> digit_sum(38)
2
</code>```

Body:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Body:
Try this:

def digit_sum(n):
    """ Recursively add the digits of a positive integer until the sum
    becomes a single digit. Return the sum. """

    sum_of_digits = sum(int(digit) for digit in str(n))
    if sum_of_digits < 10:
        return sum_of_digits
    else:
        return digit_sum(sum_of_digits)

>>> digit_sum(38)
2


问:
AndroidViewModel - Making duplicate calls doesn't return data in observe function
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

```<code>@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}
</code>```

In Activity, the ViewModel is defined as followed -

```<code>final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);
</code>```

The observeViewModel function is used to add observable on ViewModel.

```<code>public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }
</code>```

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

```<code>//observeViewModel(networkInformationViewModel);
</code>```

Please note:-
I don't need RxJava implementation for implementing this.

答:
I didn't met the same issue, but i came across a similar thing where the number of observers were increasing each time i was saving the data in db. The way i debugged was how many instances or different instances of observers were getting invoked and i came to know that when you are fetching the live data from view model it needs to be checked for non null or you can say  only 1 instance is being returned -

```<code>private LiveData<T> data;
    public LiveData<T> getLiveData(){
        if(data ==null){
            data = //api call or fetch from db
        }
        return data;
    }
</code>```

Before i was simply returning the data object and then after checking the source i came to the conclusion that livedata automatically updates your object and everytime without the null check new instance was getting created and new observers were getting attached. Someone can correct me if my understanding regarding livedata is wrong.

Body:
My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}

In Activity, the ViewModel is defined as followed -

final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);

The observeViewModel function is used to add observable on ViewModel.

public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

//observeViewModel(networkInformationViewModel);

Please note:-
I don't need RxJava implementation for implementing this.

Body:
I didn't met the same issue, but i came across a similar thing where the number of observers were increasing each time i was saving the data in db. The way i debugged was how many instances or different instances of observers were getting invoked and i came to know that when you are fetching the live data from view model it needs to be checked for non null or you can say  only 1 instance is being returned -

private LiveData<T> data;
    public LiveData<T> getLiveData(){
        if(data ==null){
            data = //api call or fetch from db
        }
        return data;
    }

Before i was simply returning the data object and then after checking the source i came to the conclusion that livedata automatically updates your object and everytime without the null check new instance was getting created and new observers were getting attached. Someone can correct me if my understanding regarding livedata is wrong.


问:
Is it possible to access a particular LBA of an SD card in an android device
I want to access a particular LBA in an sd card attached to an android device. Android doesn't give that level of low level access by default. i tried accessing it through USB Card reader through SCSI commands, but it didn't work. I also tried POSIX commands to seek and read an LBA directly (CPP native commands using jni), but file read works, not direct LBA reads. Can anyone suggest a way to do the same?</p>

答:
I don't believe you can access the partition (user partition I would say) on android as you would normally do on Linux/Unix using block devices. Checks this link for details how to achieve it on Linux.

Now on android, the partition you normally see on android devices like /storage/sdcard0 or /storage/sdcard1 or /stroage/emulated/0 or /storage/80FD-33DA etc could map to a partition on internal storage. Internal storage normally has two partitions one for system which is not accessible to user's application and the second is for user apps (which is accessible to user apps). It could also map to the external storage SD-Cards depending upon the Android OS version and the device manufacturer.

Another way to access raw level partition is using dd command (which again is not available on all android variants). Check this android stackexchange article for this.

```<code>dd if=/dev/block/mmcblk0p7 of=/storage/sdcard0/usrdata.img
</code>```

You can also check file manager apps as well to get an idea how they list and manage user partitions

Body:
I don't believe you can access the partition (user partition I would say) on android as you would normally do on Linux/Unix using block devices. Checks this link for details how to achieve it on Linux.

Now on android, the partition you normally see on android devices like /storage/sdcard0 or /storage/sdcard1 or /stroage/emulated/0 or /storage/80FD-33DA etc could map to a partition on internal storage. Internal storage normally has two partitions one for system which is not accessible to user's application and the second is for user apps (which is accessible to user apps). It could also map to the external storage SD-Cards depending upon the Android OS version and the device manufacturer.

Another way to access raw level partition is using dd command (which again is not available on all android variants). Check this android stackexchange article for this.

dd if=/dev/block/mmcblk0p7 of=/storage/sdcard0/usrdata.img

You can also check file manager apps as well to get an idea how they list and manage user partitions


问:
C# Time Format String being like this (7.00:00:00)
I have problem about time format string, that's always show (.) if I input something, Eg(input :7 and enter), it will be like (7.00:00:00) and error.

enter image description here

Below is my code:

```<code><telerik:GridViewDataColumn Header="To Hour" DataMemberBinding="{Binding ToHour, Mode=TwoWay, StringFormat=\{0:hh\\:mm\\:ss\}}" TextAlignment="Center" IsSortable="True" Width="*"   />
</code>```

Model :

```<code>private TimeSpan _toHour;
        public TimeSpan ToHour
        {
            get { return _toHour; }
            set
            {
                IsModified = (_toHour != value ? true : IsModified);
                SetProperty(ref _toHour, value);
                ValidateField(nameof(ToHour));
            }
        }
</code>```

I expect something like, Eg: if I input 7 and enter then output is 07:00:00

But the actual output is : 7.00:00:00

Any help would be appreciated.

Thanks.

答:
As a workaround, it can be handled in the model side (validation, etc, omitted):

```<code>private TimeSpan _toHour = TimeSpan.Zero;
public string ToHour
{
    get => _toHour.ToString("hh\\:mm\\:ss");
    set
    {

        _toHour = value.Contains(":") ? TimeSpan.Parse(value) : TimeSpan.ParseExact(value, "%h", CultureInfo.InvariantCulture);
        OnPropertyChanged(nameof(ToHour));
    }
}
</code>```

And remove string format from xaml:

```<code>DataMemberBinding="{Binding ToHour, Mode=TwoWay}"
</code>```

Body:
I have problem about time format string, that's always show (.) if I input something, Eg(input :7 and enter), it will be like (7.00:00:00) and error.

enter image description here

Below is my code:

<telerik:GridViewDataColumn Header="To Hour" DataMemberBinding="{Binding ToHour, Mode=TwoWay, StringFormat=\{0:hh\\:mm\\:ss\}}" TextAlignment="Center" IsSortable="True" Width="*"   />

Model :

private TimeSpan _toHour;
        public TimeSpan ToHour
        {
            get { return _toHour; }
            set
            {
                IsModified = (_toHour != value ? true : IsModified);
                SetProperty(ref _toHour, value);
                ValidateField(nameof(ToHour));
            }
        }

I expect something like, Eg: if I input 7 and enter then output is 07:00:00

But the actual output is : 7.00:00:00

Any help would be appreciated.

Thanks.

Body:
As a workaround, it can be handled in the model side (validation, etc, omitted):

private TimeSpan _toHour = TimeSpan.Zero;
public string ToHour
{
    get => _toHour.ToString("hh\\:mm\\:ss");
    set
    {

        _toHour = value.Contains(":") ? TimeSpan.Parse(value) : TimeSpan.ParseExact(value, "%h", CultureInfo.InvariantCulture);
        OnPropertyChanged(nameof(ToHour));
    }
}

And remove string format from xaml:

DataMemberBinding="{Binding ToHour, Mode=TwoWay}"


问:
Calculate the sum of the time for column
I have this table:

```<code><table id="total" border="1" width="100%">
    <tbody>
        <tr>
            <td>Total duration time</td>
            <td class="total_duration_time"></td>
        </tr>
    </tbody>
</table>
<table id="data" border="1" width="100%">
    <tbody>
        <tr>
            <td>Anna</td>
            <td>318</td><td class="duration_time">00:00:50</td>
            <td>62700</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>318</td>
            <td class="duration_time">00:00:27</td>
            <td>62703</td>
        </tr>
        <tr>
            <td>Mike</td>
            <td>318</td>
            <td class="duration_time">00:00:36</td>
            <td>88455233284</td>
        </tr>
    </tbody>
</table>
</code>```

I need to calculate the sum of the column with class duration_time and print result in to column with class total_duration_time.

How to do this on JavaScript or jQuery?

I tried to use the code from this example http://jsfiddle.net/unKDk/13/, but it does not calculate the amount of time if instead of numbers substitute a value of type 00:00:00.

答:
You can calculate  total time by using 24hr format time inputs

```<code>var a = "22:00"
var b = "01:00"
</code>```

Fiddle Demo :

Time Calculation Example, https://github.com/Zalasanjay

Body:
I have this table:

            Total duration time

            Anna
            318	00:00:50
            62700

            Bob
            318
            00:00:27
            62703

            Mike
            318
            00:00:36
            88455233284

I need to calculate the sum of the column with class duration_time and print result in to column with class total_duration_time.

How to do this on JavaScript or jQuery?

I tried to use the code from this example http://jsfiddle.net/unKDk/13/, but it does not calculate the amount of time if instead of numbers substitute a value of type 00:00:00.

Body:
You can calculate  total time by using 24hr format time inputs

var a = "22:00"
var b = "01:00"

Fiddle Demo :

Time Calculation Example, https://github.com/Zalasanjay


问:
DataSet Table giving "there is no row in position 0" error
I am trying to retrieve an image from my database to appear as the background of my windows form. But the error "There are no rows at position 0" keeps appearing. I have tested it on other forms with the same code and it works fine. May I know what's wrong with the code below?</p>

```<code>cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label10.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

            if (ds.Tables[0].Rows[0]["Background"] != System.DBNull.Value)
            {
            MemoryStream ms = new MemoryStream((Byte[])ds.Tables[0].Rows[0]["Background"]);
            this.BackgroundImage = new Bitmap(ms);
</code>```

答:
you must need to check ds.Tables[0].Rows.Count > 0 before trying code like this.

There is no need of dataset you can use DataTable directly.

One more change is make use of SQLParameter to pass value , rather than writing query like this , to avoid sql injection.

Make use of using  to dispose objects.

Body:
I am trying to retrieve an image from my database to appear as the background of my windows form. But the error "There are no rows at position 0" keeps appearing. I have tested it on other forms with the same code and it works fine. May I know what's wrong with the code below?

cmd = new SqlCommand("select Background from Employee where EmployeeName='" + label10.Text + "'", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

            if (ds.Tables[0].Rows[0]["Background"] != System.DBNull.Value)
            {
            MemoryStream ms = new MemoryStream((Byte[])ds.Tables[0].Rows[0]["Background"]);
            this.BackgroundImage = new Bitmap(ms);


问:
SQL Server query runs slower from ADO.NET than in SSMS
I have a query from a web site that takes 15-30 seconds while the same query runs in .5 seconds from SQL Server Management studio. I cannot see any locking issues using SQL Profiler, nor can I reproduce the delay manually from SSMS. A week ago, I detached and reattached the database which seemed to miraculously fix the problem. Today when the problem reared its ugly head again, I tried merely rebuilding the indexes. This also fixed the problem. However, I don't think it's necessarily an index problem since the indexes wouldn't be automatically rebuilt on a simple detach/attach, to my knowledge.

Any idea what could be causing the delay? My first thought was that perhaps some parameter sniffing on the stored procedure being called (said stored proc runs a CTE, if that matters) was causing a bad query plan, which would explain the intermittent nature of the problem. Since both detaching / reattaching and an index rebuild should theoretically invalidate the cached query plan, this makes sense, but I'm unsure how to verify this. Additionally, why wouldn't the same query (copied directly from SQL Profiler with the exact same parameters) exhibit the same delay when run manually through SSMS?

Any thoughts?

答:
I know I am weighing in on this topic very late, but I wanted to post a solution that I found when having a similar issue.  In brief, adding the SET ARITHABORT ON command at the outset of my procedures brought website query performance in line with performance seen from SQL Server tools.  This option is typically being set on the connection when you run a query from QA or SSMS (you can change that option, but it is the default).

In my case, I had about 15 different stored procs doing  mathematical aggregates (SUMs, COUNTs, AVGs, STDEVs) across a fairly sizeable set of data (10s to 100s of thousands of rows) - adding the SET ARITHABORT ON option moved them all from running in 3-5 seconds each to 20-30ms.

So, hopefully that helps someone else out there.


问:
How to store DB data as JSON
In my project, I want to put DB data to a json file. I can fetch DB data successfully, and these data should be in datagrid.json.

Here is my PHP code:

```<code><?php
include("DB.php");
$sql="select aa,bb,cc,dd from OA where sysnum='TZ20171204173151317';";
$sel=$conn->query($sql);

$arr=array();
while($row=$sel->fetch(PDO::FETCH_ASSOC))
{
  $arr[]=$row;
}
$result["rows"]=$arr;

$file='datagrid.json';

file_put_contents($file, $result);

?>
</code>```

Here is correct content of datagrid.json:

```<code>{"rows":[{"aa":"123.jpg","bb":".jpg","cc":"Tom","dd":"2017-12-04 17:31:51"},
     {"aa":"1.jpg","bb":".jpg","cc":"Stack","dd":"2017-12-04 17:31:56"},
     {"aa":"test.jpg","bb":".jpg","cc":"Jack","dd":"2017-12-04 17:32:00"}
]}
</code>```

I have chmod of datagrid.json with:

```<code>chmod 777 datagrid.json
</code>```

But it works fail. Datagrid.json can not be created. Anyone can help me?

答:
You cant store an array inside a file. Instead you have to convert the array to json format using json_encode().</p>

```<code><?php
include("DB.php");
$sql="select aa,bb,cc,dd from OA where sysnum='TZ20171204173151317';";
$sel=$conn->query($sql);

$arr=array();
while($row=$sel->fetch(PDO::FETCH_ASSOC))
{
  $arr[]=$row;
}
$result["rows"]=$arr;

$file='datagrid.json';

file_put_contents($file, json_encode($result)); // Convert to json before saving

?>
</code>```

Title: How to store DB data as JSON

Body:
In my project, I want to put DB data to a json file. I can fetch DB data successfully, and these data should be in datagrid.json.

Here is my PHP code:

<?php
include("DB.php");
$sql="select aa,bb,cc,dd from OA where sysnum='TZ20171204173151317';";
$sel=$conn->query($sql);

$arr=array();
while($row=$sel->fetch(PDO::FETCH_ASSOC))
{
  $arr[]=$row;
}
$result["rows"]=$arr;

$file='datagrid.json';

file_put_contents($file, $result);

?>

Here is correct content of datagrid.json:

{"rows":[{"aa":"123.jpg","bb":".jpg","cc":"Tom","dd":"2017-12-04 17:31:51"},
     {"aa":"1.jpg","bb":".jpg","cc":"Stack","dd":"2017-12-04 17:31:56"},
     {"aa":"test.jpg","bb":".jpg","cc":"Jack","dd":"2017-12-04 17:32:00"}
]}

I have chmod of datagrid.json with:

chmod 777 datagrid.json

But it works fail. Datagrid.json can not be created. Anyone can help me?

Body:
You cant store an array inside a file. Instead you have to convert the array to json format using json_encode().

<?php
include("DB.php");
$sql="select aa,bb,cc,dd from OA where sysnum='TZ20171204173151317';";
$sel=$conn->query($sql);

$arr=array();
while($row=$sel->fetch(PDO::FETCH_ASSOC))
{
  $arr[]=$row;
}
$result["rows"]=$arr;

$file='datagrid.json';

file_put_contents($file, json_encode($result)); // Convert to json before saving

?>


答:
Please try the following code:

update location set organization_id=(select old_id from organization where organization.old_id=location.old_id);

Title: Update error in mysql Query taking data from another table

Body:
I am trying to update the orgaization_id in location table which is primary key in Organization table.

update location set organization_id=org.old_id from organization as org
where location.old_id=org.old_id;

Facing syntax error please help..


问:
How to fetch the value from an API based on select box value?
I have an API to get the value for dropdown and scoring value.

1) I have an UI which looks like below screenshot.

2) Code is mentioned below:

```<code><td>
    <div class="">
        <select ng-if="question.MasterDataCategoryId != null" id="answer{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData;" class="form-control" style="width: 300px; white-space:pre-wrap;">
            <option selected="selected"></option>
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null" id="{{question.QuestionId}}" ng-model="question.MasterData" type="text" style="width: 300px;" name="question.QuestionId" class="form-control">
    </div>
</td>
<td>
    <div class="">
        <span ng-if="question.MasterDataCategoryId != null">{{question.Score}}</span>
        <select ng-if="question.MasterDataCategoryId == null" id="projectlist" class="form-control" required ng-model="scoring">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails" value="{{score.Score}}">
                {{score.Score}}
            </option>
        </select>
    </div>
</td>
</code>```

Based on the dropdown value I need to dynamically show the scoring which I will get in the same API.

Can any let me know how to achive this.

答:
You can use ng-change = "someFunction()" on your desired dropdown & call your API in that function using http GET or POST method as following -

```<code>$http.get(url)
    .then(function(response) {
        console.log(JSON.stringify(response))
        // set your scoring variable here
        $scope.scoring = yourValue;    // your value from response
    }).error(function(error) {
        console.log(JSON.stringify(error))
    });
</code>```

Body:
I have an API to get the value for dropdown and scoring value.

1) I have an UI which looks like below screenshot.

2) Code is mentioned below:

        <select ng-if="question.MasterDataCategoryId != null" id="answer{{question.QuestionId}}" ng-model="question.MasterData" ng-init="question.MasterData;" class="form-control" style="width: 300px; white-space:pre-wrap;">
            <option selected="selected"></option>
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]" value="{{answer.MasterData}}">{{answer.MasterData}}</option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null" id="{{question.QuestionId}}" ng-model="question.MasterData" type="text" style="width: 300px;" name="question.QuestionId" class="form-control">

        {{question.Score}}
        <select ng-if="question.MasterDataCategoryId == null" id="projectlist" class="form-control" required ng-model="scoring">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails" value="{{score.Score}}">
                {{score.Score}}
            </option>
        </select>

Based on the dropdown value I need to dynamically show the scoring which I will get in the same API.

Can any let me know how to achive this.

Body:
You can use ng-change = "someFunction()" on your desired dropdown & call your API in that function using http GET or POST method as following -

$http.get(url)
    .then(function(response) {
        console.log(JSON.stringify(response))
        // set your scoring variable here
        $scope.scoring = yourValue;    // your value from response
    }).error(function(error) {
        console.log(JSON.stringify(error))
    });