问:
Searching Two Columns in a Data Frame in R
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

```<code>Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321
</code>```

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

答:
If I understood it correctly, please check if this is the output you are expecting.

```<code>ind<-function(t,df){
    ind<-t
    while(t>1){
       t=t-1
        if((df$Times[t]!=df$Times[ind]) && (!is.na(df$Midquote[t]))){
            return(t)
        }
    }
}
sapply((nrow(data):1),FUN = ind,data)

#[[1]]
#[1] 5

#[[2]]
#[1] 5

#[[3]]
#[1] 5

#[[4]]
#[1] 4

#[[5]]
#[1] 4

#[[6]]
#[1] 3

#[[7]]
#[1] 2

#[[8]]
#[1] 1

#[[9]]
#NULL
</code>```

The output series corresponds to the associated index for your data.frame starting from the last row.

Explanation: ind takes the value of row number as the current row, while t takes value starting from ind-1 to 1. df takes the entire data.frame as input and then while loop is used to check if time and midquote value of  df$Times[t] and df$Midquote[t] satisfy the required conditions. If  yes they return the index else the loop continues until it reaches the first row.

Without using sapply for a particular current row:

```<code> ind(9,df)
 [1] 5
</code>```

Body:
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

Body:
If I understood it correctly, please check if this is the output you are expecting.

ind<-function(t,df){
    ind<-t
    while(t>1){
       t=t-1
        if((df$Times[t]!=df$Times[ind]) && (!is.na(df$Midquote[t]))){
            return(t)
        }
    }
}
sapply((nrow(data):1),FUN = ind,data)

#[[1]]
#[1] 5

#[[2]]
#[1] 5

#[[3]]
#[1] 5

#[[4]]
#[1] 4

#[[5]]
#[1] 4

#[[6]]
#[1] 3

#[[7]]
#[1] 2

#[[8]]
#[1] 1

#[[9]]
#NULL

The output series corresponds to the associated index for your data.frame starting from the last row.

Explanation: ind takes the value of row number as the current row, while t takes value starting from ind-1 to 1. df takes the entire data.frame as input and then while loop is used to check if time and midquote value of  df$Times[t] and df$Midquote[t] satisfy the required conditions. If  yes they return the index else the loop continues until it reaches the first row.

Without using sapply for a particular current row:

 ind(9,df)
 [1] 5


来源: stackexchange

问:
Xcode 9 : Module compiled with Swift 3.1 cannot be imported in Swift 4.0
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

```<code>@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0
</code>```

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

答:
It works for me.

1.Clean your project in Xcode 8

2.Build or run your project in Xcode 9

ContentLicense: CC BY-SA 3.0

Body:
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !


问:
Solutions for testing entire features of an app
EDIT: to clarify - I am asking for advice on both unit testing and user interface testing.

Currently, I don't use TDD. While I am developing an application I am constantly testing what I am working on. Testing iteration could be anything from minor function changes to entire models. I try not to code too much before I test. I like instant feedback.

Of course, with experience I can see potential problems or bugs occurring as I'm coding.

BUT, after an application is complete I will usually go through the entire app on the frontend and ensure all functions are working as expected. This means literally everything. Every add/edit/delete, sort, filter, even broken links and such.

This can take a lot of time sometimes but it does ensure my work hardly ever contains bugs after deployment.

However, I'm looking for a more standard solution. What do experienced developers do? Assume for a moment I am a single developer and so do not have a testing department etc

Do you hire beta testers (no good if app is sensitive to public use)?

Is it viable to build a series of 'general' unit tests which can for example test ALL sorting, filter functions. One for testing ALL add/edit/delete functions.

Love to hear your feedback. Will be changing the way I develop based on suggestions.

答:
Unit-testing for models and helpers, of course.

But you can do unit-testing on "page-requests", as well. See, for example:

Content with Style - Unit testing controllers with Zend Framework

That's a step towards integration testing. But for issues of layout and visual aesthetics, you're pretty much stuck with walking-through each request with your browser.

ContentLicense: CC BY-SA 2.5


问:
Launchimage and Appicon aren't added to assets.xcassets in Xcode 8.3.3
I deleted my images.xcassets file and when I click new -> add asset catalog I get a new blue folder but nothing inside including the launchimage and appicons.

Any advice would be great.

Thx.

答: You can add it manually, like following figure(click the "+" button):


问:
Convert multiple lists to dataframe python
I want to put list in dataframe, my code is,

```<code>webpage_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]

    for i in webpage_urls:
        wiki2 = i
        page= urllib.request.urlopen(wiki2)

        soup = BeautifulSoup(page)

        # fetching organisations

        data3 = soup.find_all('li', class_="nav-item active")

        lobbying1 = []
        for element in data3:
            lobbying1.append(element.span.get_text())
        print(lobbying1)

        df = pd.DataFrame({'Organisation':lobbying1})
</code>```

My above code is giving output as:

```<code>['Reserve Bank of Aus... (24)', 'Business Support an... (24)']
['Department of Finance (16)', 'Business Support an... (16)']
['Department of Agric... (13)', 'Business Support an... (13)']...so on
</code>```

Which is multiple lists, not a nested one and I am getting data frame as follows only:

```<code>   Organisation
0  Australian Charitie... (1)
1  Business Support an... (1)
</code>```

I want output as two columns first element of list in column in column 1 and second element of list in column 2, and I want all entries:

```<code>Organisation            Groups
Australian Cha...      Business Support and...
</code>```

Help me out in this.

答:
Your list lobbying1 is a list of lists. So you can get a two columns dataframe by simply calling pd.Dataframe as follows:

```<code>lobbying1 = [['Reserve Bank of Aus... (24)', 'Business Support an... (24)'],
['Department of Finance (16)', 'Business Support an... (16)'],
['Department of Agric... (13)', 'Business Support an... (13)']]
df = pd.DataFrame(main_list, columns=['Organization','Groups'])
</code>```

You get this as output

```<code>>>> df.head()
                  Organization                       Groups
0  Reserve Bank of Aus... (24)  Business Support an... (24)
1   Department of Finance (16)  Business Support an... (16)
2  Department of Agric... (13)  Business Support an... (13)
>>>
</code>```

Body:
I want to put list in dataframe, my code is,

webpage_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]

    for i in webpage_urls:
        wiki2 = i
        page= urllib.request.urlopen(wiki2)

        soup = BeautifulSoup(page)

        # fetching organisations

        data3 = soup.find_all('li', class_="nav-item active")

        lobbying1 = []
        for element in data3:
            lobbying1.append(element.span.get_text())
        print(lobbying1)

        df = pd.DataFrame({'Organisation':lobbying1})

My above code is giving output as:

['Reserve Bank of Aus... (24)', 'Business Support an... (24)']
['Department of Finance (16)', 'Business Support an... (16)']
['Department of Agric... (13)', 'Business Support an... (13)']...so on

Which is multiple lists, not a nested one and I am getting data frame as follows only:

   Organisation
0  Australian Charitie... (1)
1  Business Support an... (1)

I want output as two columns first element of list in column in column 1 and second element of list in column 2, and I want all entries:

Organisation            Groups
Australian Cha...      Business Support and...

Help me out in this.

Body:
Your list lobbying1 is a list of lists. So you can get a two columns dataframe by simply calling pd.Dataframe as follows:

lobbying1 = [['Reserve Bank of Aus... (24)', 'Business Support an... (24)'],
['Department of Finance (16)', 'Business Support an... (16)'],
['Department of Agric... (13)', 'Business Support an... (13)']]
df = pd.DataFrame(main_list, columns=['Organization','Groups'])

You get this as output

>>> df.head()
                  Organization                       Groups
0  Reserve Bank of Aus... (24)  Business Support an... (24)
1   Department of Finance (16)  Business Support an... (16)
2  Department of Agric... (13)  Business Support an... (13)
>>>


问:
Glide: How to stop glide from loading images from cache instead load from server each time
I tried everything possible but couldn't try to figure out how to update images to glide whenever my json is updated

MY android app initally loads images from json using glide for firsttime after that it only load images from cache.It doesnot load images that are updated on server till i delete the app and reinstall it

I tried using diskCacheStrategy(DiskCacheStrategy.NONE) and .skipMemoryCache(true) but nothing happened

```<code>Glide.with(mContext).load(image.getMedium())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(holder.thumbnail);
</code>```

This is my code GalleryAdapter.java

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.List;

import com.bumptech.glide.signature.StringSignature;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.model.Image;

/**
 * Created by Sagunesh on 31/03/16.
 */

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private List<Image> images;
    private Context mContext;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView thumbnail;

        public MyViewHolder(View view) {
            super(view);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        }
    }

    public GalleryAdapter(Context context, List<Image> images) {
        mContext = context;
        this.images = images;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.gallery_thumbnail, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Image image = images.get(position);

        Glide.with(mContext).load(image.getMedium())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return images.size();
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private GalleryAdapter.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }
}
</code>```

Here is the code of MainActivity.java

```<code>import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.adapter.GalleryAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdView;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.ads.AdRequest;

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

import java.util.ArrayList;

import com.dailysolutions.sn.app.AppController;
import com.dailysolutions.sn.model.Image;
import com.google.android.gms.ads.InterstitialAd;

import java.util.ArrayList;

public class MainActivity extends BaseActivity {
    private DrawerLayout drawerLayout;
    private Toolbar toolbar;

    private String TAG = MainActivity.class.getSimpleName();
    private static final String endpoint = "https://www.freesabkuch.com/api_mehndi/glide.json";
    private ArrayList<Image> images;
    private ProgressDialog pDialog;
    private GalleryAdapter mAdapter;
    private RecyclerView recyclerView;
    private AdView mAdView;
    InterstitialAd interstitial;

    // Our created menu to use
    private Menu mymenu;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initNavigationDrawer();
        checkConnectivity();

        //advertisement
        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);

        // Prepare the Interstitial Ad
        interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
        interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));

        interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
        interstitial.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // Call displayInterstitial() function
                displayInterstitial();
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        pDialog = new ProgressDialog(this);
        images = new ArrayList<>();
        mAdapter = new GalleryAdapter(getApplicationContext(), images);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("images", images);
                bundle.putInt("position", position);

                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
                newFragment.setArguments(bundle);
                newFragment.show(ft, "slideshow");
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        fetchImages();

    }

    public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }
    @Override
    public void onResume() {
        // Start or resume the game.
        super.onResume();
        displayInterstitial();
    }
    @Override
    public void onStart() {
        super.onStart();
        displayInterstitial();
    }
    private void fetchImages() {

        pDialog.setMessage("Downloading....");
        pDialog.show();

        JsonArrayRequest req = new JsonArrayRequest(endpoint,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();

                        images.clear();
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject object = response.getJSONObject(i);
                                Image image = new Image();
                                image.setName(object.getString("name"));

                                JSONObject url = object.getJSONObject("url");
                                image.setSmall(url.getString("small"));
                                image.setMedium(url.getString("medium"));
                                image.setLarge(url.getString("large"));
                                image.setTimestamp(object.getString("timestamp"));

                                images.add(image);

                            } catch (JSONException e) {
                                Log.e(TAG, "Json parsing error: " + e.getMessage());
                            }
                        }

                        mAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                pDialog.hide();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req);
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    public void initNavigationDrawer() {

        NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                int id = menuItem.getItemId();

                switch (id){
                    case R.id.home:
                        Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.share:
                        Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        try {
                            Intent i = new Intent(Intent.ACTION_SEND);
                            i.setType("text/plain");
                            i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
                            String sAux = "\nLet me recommend you this application\n\n";
                            sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                            i.putExtra(Intent.EXTRA_TEXT, sAux);
                            startActivity(Intent.createChooser(i, "choose one"));
                        } catch(Exception e) {
                            //e.toString();
                        }
                    case R.id.trash:
                        Toast.makeText(getApplicationContext(),"Drawer Closed",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.logout:
                       exit();

                }
                return true;
            }
        });
        View header = navigationView.getHeaderView(0);
        TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
        tv_email.setText("Daily Solutions");
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer);

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){

            @Override
            public void onDrawerClosed(View v){
                super.onDrawerClosed(v);
            }

            @Override
            public void onDrawerOpened(View v) {
                super.onDrawerOpened(v);
            }
        };
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
    }
    private void checkConnectivity(){
        if(ConnectionHelper.isConnectedOrConnecting(getApplicationContext())) {
            hideErrorsBar(true);

        }else {
            //hideErrorsBar(false);
            Intent Intent = new Intent(MainActivity.this,NoInternet.class);
            startActivity(Intent);
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Add our menu
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // We should save our menu so we can use it to reset our updater.
        mymenu = menu;

        //
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_refresh:
                // Do animation start
                LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
                Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
                rotation.setRepeatCount(Animation.INFINITE);
                iv.startAnimation(rotation);
                item.setActionView(iv);
                new UpdateTask(this).execute();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void resetUpdating()
    {
        // Get our refresh item from the menu
        MenuItem m = mymenu.findItem(R.id.action_refresh);
        if(m.getActionView()!=null)
        {
            // Remove the animation.
            m.getActionView().clearAnimation();
            m.setActionView(null);
        }
    }

}
</code>```

答:
Well everyone thanks a lot for help :)

I resolved this problem by disabling cache of volley library that was causing the issue but anyway thanks for help :)

```<code>//disabling caching for url
        AppController.getInstance().getRequestQueue().getCache().remove(url);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried everything possible but couldn't try to figure out how to update images to glide whenever my json is updated

MY android app initally loads images from json using glide for firsttime after that it only load images from cache.It doesnot load images that are updated on server till i delete the app and reinstall it

I tried using diskCacheStrategy(DiskCacheStrategy.NONE) and .skipMemoryCache(true) but nothing happened

Glide.with(mContext).load(image.getMedium())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(holder.thumbnail);

This is my code GalleryAdapter.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.List;

import com.bumptech.glide.signature.StringSignature;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.model.Image;

/**
 * Created by Sagunesh on 31/03/16.
 */

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private List<Image> images;
    private Context mContext;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView thumbnail;

        public MyViewHolder(View view) {
            super(view);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        }
    }

    public GalleryAdapter(Context context, List<Image> images) {
        mContext = context;
        this.images = images;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.gallery_thumbnail, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Image image = images.get(position);

        Glide.with(mContext).load(image.getMedium())
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return images.size();
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private GalleryAdapter.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }
}

Here is the code of MainActivity.java

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.adapter.GalleryAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdView;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.ads.AdRequest;

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

import java.util.ArrayList;

import com.dailysolutions.sn.app.AppController;
import com.dailysolutions.sn.model.Image;
import com.google.android.gms.ads.InterstitialAd;

import java.util.ArrayList;

public class MainActivity extends BaseActivity {
    private DrawerLayout drawerLayout;
    private Toolbar toolbar;

    private String TAG = MainActivity.class.getSimpleName();
    private static final String endpoint = "https://www.freesabkuch.com/api_mehndi/glide.json";
    private ArrayList<Image> images;
    private ProgressDialog pDialog;
    private GalleryAdapter mAdapter;
    private RecyclerView recyclerView;
    private AdView mAdView;
    InterstitialAd interstitial;

    // Our created menu to use
    private Menu mymenu;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initNavigationDrawer();
        checkConnectivity();

        //advertisement
        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);

        // Prepare the Interstitial Ad
        interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
        interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));

        interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
        interstitial.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // Call displayInterstitial() function
                displayInterstitial();
            }
        });

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        pDialog = new ProgressDialog(this);
        images = new ArrayList<>();
        mAdapter = new GalleryAdapter(getApplicationContext(), images);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("images", images);
                bundle.putInt("position", position);

                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
                newFragment.setArguments(bundle);
                newFragment.show(ft, "slideshow");
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));

        fetchImages();

    }

    public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }
    @Override
    public void onResume() {
        // Start or resume the game.
        super.onResume();
        displayInterstitial();
    }
    @Override
    public void onStart() {
        super.onStart();
        displayInterstitial();
    }
    private void fetchImages() {

        pDialog.setMessage("Downloading....");
        pDialog.show();

        JsonArrayRequest req = new JsonArrayRequest(endpoint,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();

                        images.clear();
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject object = response.getJSONObject(i);
                                Image image = new Image();
                                image.setName(object.getString("name"));

                                JSONObject url = object.getJSONObject("url");
                                image.setSmall(url.getString("small"));
                                image.setMedium(url.getString("medium"));
                                image.setLarge(url.getString("large"));
                                image.setTimestamp(object.getString("timestamp"));

                                images.add(image);

                            } catch (JSONException e) {
                                Log.e(TAG, "Json parsing error: " + e.getMessage());
                            }
                        }

                        mAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                pDialog.hide();
            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(req);
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    public void initNavigationDrawer() {

        NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                int id = menuItem.getItemId();

                switch (id){
                    case R.id.home:
                        Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.share:
                        Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        try {
                            Intent i = new Intent(Intent.ACTION_SEND);
                            i.setType("text/plain");
                            i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
                            String sAux = "\nLet me recommend you this application\n\n";
                            sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                            i.putExtra(Intent.EXTRA_TEXT, sAux);
                            startActivity(Intent.createChooser(i, "choose one"));
                        } catch(Exception e) {
                            //e.toString();
                        }
                    case R.id.trash:
                        Toast.makeText(getApplicationContext(),"Drawer Closed",Toast.LENGTH_SHORT).show();
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.logout:
                       exit();

                }
                return true;
            }
        });
        View header = navigationView.getHeaderView(0);
        TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
        tv_email.setText("Daily Solutions");
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer);

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){

            @Override
            public void onDrawerClosed(View v){
                super.onDrawerClosed(v);
            }

            @Override
            public void onDrawerOpened(View v) {
                super.onDrawerOpened(v);
            }
        };
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
    }
    private void checkConnectivity(){
        if(ConnectionHelper.isConnectedOrConnecting(getApplicationContext())) {
            hideErrorsBar(true);

        }else {
            //hideErrorsBar(false);
            Intent Intent = new Intent(MainActivity.this,NoInternet.class);
            startActivity(Intent);
            finish();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Add our menu
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // We should save our menu so we can use it to reset our updater.
        mymenu = menu;

        //
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_refresh:
                // Do animation start
                LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
                Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
                rotation.setRepeatCount(Animation.INFINITE);
                iv.startAnimation(rotation);
                item.setActionView(iv);
                new UpdateTask(this).execute();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void resetUpdating()
    {
        // Get our refresh item from the menu
        MenuItem m = mymenu.findItem(R.id.action_refresh);
        if(m.getActionView()!=null)
        {
            // Remove the animation.
            m.getActionView().clearAnimation();
            m.setActionView(null);
        }
    }

}

Body:
Well everyone thanks a lot for help :)

I resolved this problem by disabling cache of volley library that was causing the issue but anyway thanks for help :)

//disabling caching for url
        AppController.getInstance().getRequestQueue().getCache().remove(url);


问:
windows batch command to copy files from a list of folders to a destination without traversing through the subfolders
I need to recursively go through a list of windows directories and copy the txt files in these directories to a destination.I am using the below code:

```<code>@echo off

set TESTDIRS=RFP,New Audit
set TD=C:\Users\Audit

for %%d in (%TESTDIRS%) do call :process_testdir %%d
goto :eof

:process_testdir
set CTD=%TD%\%1
echo CTD: %CTD%
    REM Echos the expected path

for /R %CTD% %%f in (*.txt) do (echo %%f
 copy "%%f" "C:\Users\Audit\ImportantDocs)
    REM Echos as expected

goto :eof
</code>```

Issue that i am facing:This batch script traverses across all the subfolders present within the parent folder and copies the txt files into the destination,which is not what i want.If i specify a folder name,i would want the text files only in that particular folder to be copied to the destination and not the files present in its subfolders.

Eg:The folder named "RFP" contains 3 text files and also a subfolder named "July" which contains 5 test files.I would want my batch script to copy only the 3 files present in the "RFP" folder to the destination and not the 5 files present in the subfolder "July"

Any help ??

答:
change

```<code>for /R %CTD% %%f in (*.txt) do (echo %%f
</code>```

to

```<code>for %%f in ("%CTD%\*.txt") do (echo %%f
</code>```

the /r is recursive. Your directorynames appear to include spaces, so you'd need to "enclose directorynames including spaces in quotes" and remove he quotes in the subroutine by using %~1 which removes the enclosing quotes.

Body:
I need to recursively go through a list of windows directories and copy the txt files in these directories to a destination.I am using the below code:

@echo off

set TESTDIRS=RFP,New Audit
set TD=C:\Users\Audit

for %%d in (%TESTDIRS%) do call :process_testdir %%d
goto :eof

:process_testdir
set CTD=%TD%\%1
echo CTD: %CTD%
    REM Echos the expected path

for /R %CTD% %%f in (*.txt) do (echo %%f
 copy "%%f" "C:\Users\Audit\ImportantDocs)
    REM Echos as expected

goto :eof

Issue that i am facing:This batch script traverses across all the subfolders present within the parent folder and copies the txt files into the destination,which is not what i want.If i specify a folder name,i would want the text files only in that particular folder to be copied to the destination and not the files present in its subfolders.

Eg:The folder named "RFP" contains 3 text files and also a subfolder named "July" which contains 5 test files.I would want my batch script to copy only the 3 files present in the "RFP" folder to the destination and not the 5 files present in the subfolder "July"

Any help ??

Body:
change

for /R %CTD% %%f in (*.txt) do (echo %%f

to

for %%f in ("%CTD%\*.txt") do (echo %%f

the /r is recursive. Your directorynames appear to include spaces, so you'd need to "enclose directorynames including spaces in quotes" and remove he quotes in the subroutine by using %~1 which removes the enclosing quotes.


问:
HTTP WCF Service, JSON date formatting issue returning IEnumerable<class>
I have a Restful WCF Http Service that returns JSON and works great, except the DateTime doesn't format correctly:

e.g. "AdjudDate": "/Date(1349409600000-0400)/"

After looking around I found an old post here but I could not get that code to work. It was last updated in 2011. Is there maybe a more current version or implementation?
JSON.NET Serializer for WCF REST Services

Here's my code that returns an IEnumerable.

//All JSON values are good except for the dates:

```<code>private IEnumerable<Customer> ProcessWcfPost(Customer searchmodel)
{
    return _repository.GetCustomers(searchModel);
}
</code>```

edit
I've also of course tried changing the return type to string instead of IEnumerable as:

```<code>private string ProcessWcfPost(Customer searchmodel)
    {
        var result = _repository.GetCustomers(searchModel);
        return Newtonsoft.Json.JsonConvert.SerializeObject(result);
    }
</code>```

But my JSON is not quite right:
[{\"ClaimProcessId\":1599986,\"ClmHdrId\":1011,\"ClmLineId\":1011,\"ClmAdjId\":1011,\"ReceivedDtSur\":\"2012-12-05T00:00:00\",\"AdjudicationDtSur\":\"2011-10-05T00:00:00\"(on and on)...

答:
I was facing the same problem and I could find a solution that might help anybody.
This solution is based on DateTimeKind.Utc which will return date without -0400, ex:

```<code>Public Function test() As Date

Dim DateFormatted As New DateTime(2017, 07, 04, 8, 18, 42, DateTimeKind.Utc)
return DateFormatted

End Function
</code>```

Body:
I have a Restful WCF Http Service that returns JSON and works great, except the DateTime doesn't format correctly:

e.g. "AdjudDate": "/Date(1349409600000-0400)/"

After looking around I found an old post here but I could not get that code to work. It was last updated in 2011. Is there maybe a more current version or implementation?
JSON.NET Serializer for WCF REST Services

Here's my code that returns an IEnumerable.

//All JSON values are good except for the dates:

private IEnumerable<Customer> ProcessWcfPost(Customer searchmodel)
{
    return _repository.GetCustomers(searchModel);
}

edit
I've also of course tried changing the return type to string instead of IEnumerable as:

private string ProcessWcfPost(Customer searchmodel)
    {
        var result = _repository.GetCustomers(searchModel);
        return Newtonsoft.Json.JsonConvert.SerializeObject(result);
    }

But my JSON is not quite right:
[{\"ClaimProcessId\":1599986,\"ClmHdrId\":1011,\"ClmLineId\":1011,\"ClmAdjId\":1011,\"ReceivedDtSur\":\"2012-12-05T00:00:00\",\"AdjudicationDtSur\":\"2011-10-05T00:00:00\"(on and on)...

Body:
I was facing the same problem and I could find a solution that might help anybody.
This solution is based on DateTimeKind.Utc which will return date without -0400, ex:

Public Function test() As Date

Dim DateFormatted As New DateTime(2017, 07, 04, 8, 18, 42, DateTimeKind.Utc)
return DateFormatted

End Function


问:
Convert SVG semi-circle arc to full-circle arc using Path
I'm trying to convert this semi-circle arc into a full circle, or at least an almost full circle with small disconnected notch at the bottom.

I've tried changing the 180 to 360.

I have also tried changing the 0, 0, 1 ,parameters to change the rotation of the arc, but that seems to have a rotation / flipping effect, rather than elongating the arc.

This code is in AngularJS, but should not detract from math involved to solve this.

This example is modified from from Pluralsight's Scalable Dynamic Graphs & Charts Using AngularJS and SVG Course.

Plunker Link

gauge.component.js

```<code>angular.module('app.gauge', []);
angular.module('app.gauge')
  .component('gauge', {
    require: {
      parent: '^appMain'
    },
    bindings: {
      centerX: '=',
      centerY: '=',
      radius: '<',
      maxValue: '<',
      gradientInterval: '<',
      currentValue: '<',
      gradientsOffset: '<'
    },
    controller: GaugeCtrl,
    controllerAs: 'gauge',
    templateUrl: 'gauge.html',
    bindToController: true
  });

function GaugeCtrl(d3, $scope) {
  var gauge = this;
  // preset defaults
  gauge.specs = {
    centerX: 0, // pass in 300
    centerY: 0, // pass in 300
    radius: 0, // pass in 200
    maxValue: 0, // pass in 180
    gradientInterval: 0,
    currentValue: 0, // 45 passed in
    gradients: [],
    gradientsOffset: 0, // 10
    maxValueCoordinates: null
  };

  // pass in values from component passed-in values
  function initPassedInValues() {
    // grab all props from controller
    var keys = Object.keys(gauge);
    // if ctrl key is in gauge.specs object, copy over to specs
    keys.forEach(function(key,idx){
      if (gauge.specs.hasOwnProperty(key)) {
        gauge.specs[key] = gauge[key];
      }
    });
  }

  // passedin padding
  gauge.$onInit = function() {
    initPassedInValues(); // process passed-in values from component
    initGauge();
    initGradients();
  }

  gauge.$postLink = function() {

  }

  // function defs
  var getCoordinatesForAngle = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 180.0) * Math.PI / 180.0);
    return {
      x: parseInt(centerX + (radius * Math.cos(angleInRadians))),
      y: parseInt(centerY + (radius * Math.sin(angleInRadians)))
    };
  };

  // calc background and value arc
    // radius as param - diff for circle vs. text path
  var getArcPathForAngle = function(startingAngle, endingAngle, radius){
    var startingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        startingAngle);

    var endingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        endingAngle);

    return ["M", startingPt.x, startingPt.y, "A", radius, radius, 0, 0, 1, endingPt.x, endingPt.y].join(' ');
  };

  // textPath ticks
  function initGradients() {
    // use < instead of <= so doesn't show last value, taken care of with fixLastGradientTextValue fn
    for (var value = 0, offset = 0; value < gauge.specs.maxValue; value += gauge.specs.gradientInterval, offset += 100/18) {
      gauge.specs.gradients.push({value: value, offset: offset});
    }
  }

  function initGauge() {
    // draw background
    gauge.background = getArcPathForAngle(0, gauge.specs.maxValue, gauge.specs.radius);
    // draw gauge value
    gauge.value = getArcPathForAngle(0, gauge.specs.currentValue, gauge.specs.radius);
    // draw gradient tick values
    gauge.gradients = getArcPathForAngle(0, gauge.specs.maxValue, gauge.specs.radius + gauge.specs.gradientsOffset);
    // fix last text value and rotate
    gauge.specs.maxValueCoordinates = getCoordinatesForAngle(
      gauge.specs.centerX,
      gauge.specs.centerY,
      gauge.specs.radius + gauge.specs.gradientsOffset,
      gauge.specs.maxValue);
  }

  // additional watcher for currentValue
  $scope.$watch('gauge.specs.currentValue', function(oldValue, newValue) {
    initGauge();
  }, true);
}
</code>```

gauge.html

```<code><div class="svg-container gauge">
  <!-- gauge -->
  <svg class="svg-scalable" viewBox="0 0 600 400" preserveAspectRation="xMidYMid meet">

    <g>
      <!-- background -->
      <path id="gaugeBackground" ng-attr-d="{{ gauge.background }}" stroke-width="10" stroke="black" fill="none"/>

      <!-- gauge value -->
      <path ng-attr-d="{{ gauge.value }}" stroke-width="10" stroke="#2a9fbc" fill="none"/>

      <!-- invisible arc for textPath to follow, slightly larger -->
      <path id="gradients" ng-attr-d="{{ gauge.gradients }}" stroke width="0" fill="none" />

      <!-- gradient ticks -->
      <text ng-repeat="gradient in gauge.specs.gradients" dx="0" dy="0" text-anchor="middle" style="font: bold large arial">
        <textPath xlink:href="#gradients" startOffset="{{ gradient.offset }}%">
          {{ gradient.value }}
        </textPath>
      </text>

      <!-- Fix for last tick-->
      <text dx="{{ gauge.specs.maxValueCoordinates.x }}" dy="{{ gauge.specs.maxValueCoordinates.y }}" text-anchor="middle" style="font: bold large arial" transform="rotate(90, {{ gauge.specs.maxValueCoordinates.x}}, {{ gauge.specs.maxValueCoordinates.y }} )">
       {{ gauge.specs.maxValue }}
      </text>

      <text dx="50%" dy="50%" text-anchor="middle"
    alignment-baseline="hanging" style="font-size: 7rem">
        {{ gauge.specs.currentValue }}
      </text>
    </g>
  </svg>
</div>
</code>```

app-main.html -- passed in defaults

```<code>...
<!-- Gauge component -->
<gauge center-x="300"
  center-y="300"
  radius="200"
  max-value="180"
  gradient-interval="10"
  current-value="45"
  gradients-offset="10">
</gauge>
...
</code>```

答:
Okay, I relented, and made the modifications for you :)

The original gauge has the "sweep angle" and the max gauge value both hardwired to 180.  It breaks if you try and change the max-value attribute.

My version fixes that and introduces a new attribute gauge-sweep that sets the angle that the gauge covers (up to 360 degrees).  You can also set the max-value independently (eg. 100).

The main changes to the code are in the following three functions:

```<code>  var getCoordinatesForAngle = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 90 - gauge.specs.gaugeSweep/2) * Math.PI / 180.0);
    return {
      x: parseInt(centerX + (radius * Math.cos(angleInRadians))),
      y: parseInt(centerY + (radius * Math.sin(angleInRadians)))
    };
  };
</code>```

This needed to be modified from having the start angle of the gauge being on the left (west). We now vary it based on the gaugeSweep value.

```<code>  // calc background and value arc
  // radius as param - diff for circle vs. text path
  // Divided into three arcs to ensure accuracy over the largest possible range (360deg)
  var getArcPathForAngle = function(startingAngle, endingAngle, radius, maxAngle) {
    var startingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        startingAngle);
    var midPt1 = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        (startingAngle + endingAngle)/3);
    var midPt2 = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        (startingAngle + endingAngle)*2/3);
    var endingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        endingAngle);

    return ["M", startingPt.x, startingPt.y,
            "A", radius, radius, 0, 0, 1, midPt1.x, midPt1.y,
            "A", radius, radius, 0, 0, 1, midPt2.x, midPt2.y,
            "A", radius, radius, 0, 0, 1, endingPt.x, endingPt.y].join(' ');
  };
</code>```

Path arc (A) commands have a tendency to get a little inaccurate if they cover 180 or more degrees. To avoid that, we now use three arcs for the gauge so that we can safely cover any sweep up to 360 degrees.

```<code>  // textPath ticks
  function initGradients() {
    // use < instead of <= so doesn't show last value, taken care of with fixLastGradientTextValue fn
    var offsetStep = (gauge.specs.gradientInterval * 100) / gauge.specs.maxValue;
    for (var value = 0, offset = 0; value < gauge.specs.maxValue; value += gauge.specs.gradientInterval, offset += offsetStep) {
      gauge.specs.gradients.push({value: value, offset: offset});
    }
  }
</code>```

This function calculates the tick positions of the gauge.  It was hardwired to expect a maxValue of 180 degrees. It needed to be fixed.

There were also minor changes to app-main.html and gauge.html.

My updated plunkr is here

Body:
I'm trying to convert this semi-circle arc into a full circle, or at least an almost full circle with small disconnected notch at the bottom.

I've tried changing the 180 to 360.

I have also tried changing the 0, 0, 1 ,parameters to change the rotation of the arc, but that seems to have a rotation / flipping effect, rather than elongating the arc.

This code is in AngularJS, but should not detract from math involved to solve this.

This example is modified from from Pluralsight's Scalable Dynamic Graphs & Charts Using AngularJS and SVG Course.

Plunker Link

gauge.component.js

angular.module('app.gauge', []);
angular.module('app.gauge')
  .component('gauge', {
    require: {
      parent: '^appMain'
    },
    bindings: {
      centerX: '=',
      centerY: '=',
      radius: '<',
      maxValue: '<',
      gradientInterval: '<',
      currentValue: '<',
      gradientsOffset: '<'
    },
    controller: GaugeCtrl,
    controllerAs: 'gauge',
    templateUrl: 'gauge.html',
    bindToController: true
  });

function GaugeCtrl(d3, $scope) {
  var gauge = this;
  // preset defaults
  gauge.specs = {
    centerX: 0, // pass in 300
    centerY: 0, // pass in 300
    radius: 0, // pass in 200
    maxValue: 0, // pass in 180
    gradientInterval: 0,
    currentValue: 0, // 45 passed in
    gradients: [],
    gradientsOffset: 0, // 10
    maxValueCoordinates: null
  };

  // pass in values from component passed-in values
  function initPassedInValues() {
    // grab all props from controller
    var keys = Object.keys(gauge);
    // if ctrl key is in gauge.specs object, copy over to specs
    keys.forEach(function(key,idx){
      if (gauge.specs.hasOwnProperty(key)) {
        gauge.specs[key] = gauge[key];
      }
    });
  }

  // passedin padding
  gauge.$onInit = function() {
    initPassedInValues(); // process passed-in values from component
    initGauge();
    initGradients();
  }

  gauge.$postLink = function() {

  }

  // function defs
  var getCoordinatesForAngle = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 180.0) * Math.PI / 180.0);
    return {
      x: parseInt(centerX + (radius * Math.cos(angleInRadians))),
      y: parseInt(centerY + (radius * Math.sin(angleInRadians)))
    };
  };

  // calc background and value arc
    // radius as param - diff for circle vs. text path
  var getArcPathForAngle = function(startingAngle, endingAngle, radius){
    var startingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        startingAngle);

    var endingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        endingAngle);

    return ["M", startingPt.x, startingPt.y, "A", radius, radius, 0, 0, 1, endingPt.x, endingPt.y].join(' ');
  };

  // textPath ticks
  function initGradients() {
    // use < instead of <= so doesn't show last value, taken care of with fixLastGradientTextValue fn
    for (var value = 0, offset = 0; value < gauge.specs.maxValue; value += gauge.specs.gradientInterval, offset += 100/18) {
      gauge.specs.gradients.push({value: value, offset: offset});
    }
  }

  function initGauge() {
    // draw background
    gauge.background = getArcPathForAngle(0, gauge.specs.maxValue, gauge.specs.radius);
    // draw gauge value
    gauge.value = getArcPathForAngle(0, gauge.specs.currentValue, gauge.specs.radius);
    // draw gradient tick values
    gauge.gradients = getArcPathForAngle(0, gauge.specs.maxValue, gauge.specs.radius + gauge.specs.gradientsOffset);
    // fix last text value and rotate
    gauge.specs.maxValueCoordinates = getCoordinatesForAngle(
      gauge.specs.centerX,
      gauge.specs.centerY,
      gauge.specs.radius + gauge.specs.gradientsOffset,
      gauge.specs.maxValue);
  }

  // additional watcher for currentValue
  $scope.$watch('gauge.specs.currentValue', function(oldValue, newValue) {
    initGauge();
  }, true);
}

gauge.html

  <svg class="svg-scalable" viewBox="0 0 600 400" preserveAspectRation="xMidYMid meet">

    <g>

      <path id="gaugeBackground" ng-attr-d="{{ gauge.background }}" stroke-width="10" stroke="black" fill="none"/>

      <path ng-attr-d="{{ gauge.value }}" stroke-width="10" stroke="#2a9fbc" fill="none"/>

      <path id="gradients" ng-attr-d="{{ gauge.gradients }}" stroke width="0" fill="none" />

      <text ng-repeat="gradient in gauge.specs.gradients" dx="0" dy="0" text-anchor="middle" style="font: bold large arial">
        <textPath xlink:href="#gradients" startOffset="{{ gradient.offset }}%">
          {{ gradient.value }}
        </textPath>
      </text>

      <text dx="{{ gauge.specs.maxValueCoordinates.x }}" dy="{{ gauge.specs.maxValueCoordinates.y }}" text-anchor="middle" style="font: bold large arial" transform="rotate(90, {{ gauge.specs.maxValueCoordinates.x}}, {{ gauge.specs.maxValueCoordinates.y }} )">
       {{ gauge.specs.maxValue }}
      </text>

      <text dx="50%" dy="50%" text-anchor="middle"
    alignment-baseline="hanging" style="font-size: 7rem">
        {{ gauge.specs.currentValue }}
      </text>
    </g>
  </svg>

app-main.html -- passed in defaults

...

<gauge center-x="300"
  center-y="300"
  radius="200"
  max-value="180"
  gradient-interval="10"
  current-value="45"
  gradients-offset="10">
</gauge>
...

Body:
Okay, I relented, and made the modifications for you :)

The original gauge has the "sweep angle" and the max gauge value both hardwired to 180.  It breaks if you try and change the max-value attribute.

My version fixes that and introduces a new attribute gauge-sweep that sets the angle that the gauge covers (up to 360 degrees).  You can also set the max-value independently (eg. 100).

The main changes to the code are in the following three functions:

  var getCoordinatesForAngle = function(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = ((angleInDegrees - 90 - gauge.specs.gaugeSweep/2) * Math.PI / 180.0);
    return {
      x: parseInt(centerX + (radius * Math.cos(angleInRadians))),
      y: parseInt(centerY + (radius * Math.sin(angleInRadians)))
    };
  };

This needed to be modified from having the start angle of the gauge being on the left (west). We now vary it based on the gaugeSweep value.

  // calc background and value arc
  // radius as param - diff for circle vs. text path
  // Divided into three arcs to ensure accuracy over the largest possible range (360deg)
  var getArcPathForAngle = function(startingAngle, endingAngle, radius, maxAngle) {
    var startingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        startingAngle);
    var midPt1 = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        (startingAngle + endingAngle)/3);
    var midPt2 = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        (startingAngle + endingAngle)*2/3);
    var endingPt = getCoordinatesForAngle(
        gauge.specs.centerX,
        gauge.specs.centerY,
        radius,
        endingAngle);

    return ["M", startingPt.x, startingPt.y,
            "A", radius, radius, 0, 0, 1, midPt1.x, midPt1.y,
            "A", radius, radius, 0, 0, 1, midPt2.x, midPt2.y,
            "A", radius, radius, 0, 0, 1, endingPt.x, endingPt.y].join(' ');
  };

Path arc (A) commands have a tendency to get a little inaccurate if they cover 180 or more degrees. To avoid that, we now use three arcs for the gauge so that we can safely cover any sweep up to 360 degrees.

  // textPath ticks
  function initGradients() {
    // use < instead of <= so doesn't show last value, taken care of with fixLastGradientTextValue fn
    var offsetStep = (gauge.specs.gradientInterval * 100) / gauge.specs.maxValue;
    for (var value = 0, offset = 0; value < gauge.specs.maxValue; value += gauge.specs.gradientInterval, offset += offsetStep) {
      gauge.specs.gradients.push({value: value, offset: offset});
    }
  }

This function calculates the tick positions of the gauge.  It was hardwired to expect a maxValue of 180 degrees. It needed to be fixed.

There were also minor changes to app-main.html and gauge.html.

My updated plunkr is here


问:
phpMyAdmin error 1932 - table doesn't exist in engine
windows 7 - xampp

I have a database with 14 tables. I worked this days with all of them without problems untill this morning.

All tables are ok except table posts. When I click on it's name (left menu in phpMyAdmin) I got a message:

#1932... posts doesnt exist in engine

On stackoverflow there are six posts with simmilar title, but there is no solution for me.

For example this is about a system table phpmyadmin.pma and on ubuntu. I'm on windows and table posts is a user table.

Any help?

答:
I got it working with some changes in xampp/phpmyadmin/config.inc.php:

Add a $i=1 after /* server parameters */

```<code>/* Server parameters */

$i = 1
</code>```

AND fix tablespaces of phpMyAdmin as written in https://stackoverflow.com/a/11506495/2364405

Body:
I got it working with some changes in xampp/phpmyadmin/config.inc.php:

Add a $i=1 after /* server parameters */

/* Server parameters */

$i = 1

AND fix tablespaces of phpMyAdmin as written in https://stackoverflow.com/a/11506495/2364405


问:
input date must be not be greater than current date in bootstrap datepicker [dd-M-yyyy] format
my input textbox

```<code><input  type="text" id="dateOfDiagnosisTextbox" class="form-control" />
</code>```

This is my jquery

```<code>$('#dateOfDiagnosisTextbox').datepicker({
            format: "dd-M-yyyy",
            autoclose: true,
            todayHighlight: true
        });
</code>```

Date of textbox should be a valid date format (dd-M-yyyy) and must be not be greater than current date otherwise system should display appropriate error message.

答:
Here you go with jsfiddle https://jsfiddle.net/or3jabbv/</p>

```<code> $( function() {
    $( "#datepicker" ).datepicker({ maxDate: "now" });
 } );
</code>```

Body:
my input textbox

<input  type="text" id="dateOfDiagnosisTextbox" class="form-control" />

This is my jquery

$('#dateOfDiagnosisTextbox').datepicker({
            format: "dd-M-yyyy",
            autoclose: true,
            todayHighlight: true
        });

Date of textbox should be a valid date format (dd-M-yyyy) and must be not be greater than current date otherwise system should display appropriate error message.

Body:
Here you go with jsfiddle https://jsfiddle.net/or3jabbv/

 $( function() {
    $( "#datepicker" ).datepicker({ maxDate: "now" });
 } );


问:
Keras save checkpoints
I am following this blog and I am having trouble to implement saving checkpoints as it's used in linked blog. At line 23 it used:

filepath="weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5".

So I tried to tweak the code a little bit to be more dynamic:

filepath = '{0}/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5'.format(directory).

Where I want to store all checkpoints of given architecture in 1 directory, e.g.: ./architecture1/checkpoints/

But I get the following error: KeyError: 'epoch'. What am I doing wrong here?

P.S.: filepath = "./checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5" works, but it saves all checkpoints in 1 directory which I don't want.

答:
The problem is that you are using format on a format eligible string but supply only one of the keys - and that causes an error.

What you are doing is

```<code>"{0} some text here {epoch:02d}".format("text")
</code>```

and that is causing an error, because it looks for the second key and can't find it.

If you want your code to be dynamic, what I would do is:

```<code>"{0}".format(directory) + "/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5"
</code>```

Title: Keras save checkpoints

Body:
The problem is that you are using format on a format eligible string but supply only one of the keys - and that causes an error.

What you are doing is

"{0} some text here {epoch:02d}".format("text")

and that is causing an error, because it looks for the second key and can't find it.

If you want your code to be dynamic, what I would do is:

"{0}".format(directory) + "/checkpoints/checkpoint-{epoch:02d}-{val_loss:.2f}.hdf5"


答:
```<code>$('#dateOfDiagnosisTextbox').datepicker({
     format: "dd-M-yyyy",
     autoclose: true,
     todayHighlight: true,
     endDate: new Date()
});
</code>```

Title: input date must be not be greater than current date in bootstrap datepicker [dd-M-yyyy] format


问:
Align vertical text next to the image
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

```<code><h1>This is Sparta!</h1>
<div class="container">
<div class="row">
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
  <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
</div>
</div>
</code>```

CSS:

```<code>.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}
</code>```

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

答:
This method will work with any length of text (so long as it's a single line).

```<code>.services__text {
    position:absolute;
    transform: rotate(-90deg) translate(-100%);
    transform-origin: left top;
    width:100%;
    left:-8px;
    text-align:right;
}
</code>```

translate(-100%) moves the elements new position -100% of its width to its left (down).

width:100%; gives your title room to expand. This the elements height.

text-align:right; pushes the text to the top of the image

position:absolute; & left:-8px; pushes the text to the outside of the image (possibly overlapping other elements)

Title: Align vertical text next to the image

Body:
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

This is Sparta!

Title Text Here

Title Text Here

Title Text Here

CSS:

.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

Body:
This method will work with any length of text (so long as it's a single line).

.services__text {
    position:absolute;
    transform: rotate(-90deg) translate(-100%);
    transform-origin: left top;
    width:100%;
    left:-8px;
    text-align:right;
}

translate(-100%) moves the elements new position -100% of its width to its left (down).

width:100%; gives your title room to expand. This the elements height.

text-align:right; pushes the text to the top of the image

position:absolute; & left:-8px; pushes the text to the outside of the image (possibly overlapping other elements)


问:
How do you make a star rating as a visualisation
I have a simple dataframe.

```<code>name    Rating
George     2
Henry      4
</code>```

In either python or R, I want to make a star rating visualization like in Amazon.

```<code>name     Rating
George     **
Henry      ****
</code>```

答:
Python:

```<code>df.assign(Rating=df['Rating'].apply(lambda x: x * '*'))
</code>```

Output:

```<code>     name Rating
0  George     **
1   Henry   ****
</code>```

Body:
I have a simple dataframe.

name    Rating
George     2
Henry      4

In either python or R, I want to make a star rating visualization like in Amazon.

name     Rating
George     **
Henry      ****

Body:
Python:

df.assign(Rating=df['Rating'].apply(lambda x: x * '*'))

Output:

     name Rating
0  George     **
1   Henry   ****


问:
Permission denied for access to folder on Python3.6 with Flask
EDIT: Ignore this question entirely. It was a filesystem problem.

Whenever I try to open the posts folder, I get an error:

```<code>Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\vikas\Projects\blg\main.py", line 19, in index
    return render_template("index.html", newest_post=find_recent_post())
  File "C:\Users\vikas\Projects\blg\main.py", line 12, in find_recent_post
    with open(str(find_recent_post_name())) as post:
PermissionError: [Errno 13] Permission denied: 'posts/'
</code>```

My main.py file:

```<code>from flask import Flask
from flask import render_template

app = Flask(__name__)

def find_recent_post_name():
    import glob
    posts = glob.glob("posts/")
    return posts[len(posts) - 1]

def find_recent_post():
    with open(str(find_recent_post_name())) as post:
        newest_post = post.readlines()
    return newest_post

@app.route("/")
def index():
    return render_template("index.html", newest_post=find_recent_post())

if __name__ == '__main__':
    app.run(debug=True)
</code>```

My Python version is v3.6.1 and Flask v1.12.0

EDIT: Debugging code and using PowerShell seems to work.

答:
It is not a problem with flask. you can either change the permissions on the folder /posts/ or  you can run flask as a user who has read access.

```<code>$ chmod 755 <folder names>
</code>```

to give access to the user who run's flask app, or you could use:

```<code>$ sudo python main.py
</code>```

to run as admin or run flask as a user who already has access. and note that you should add the same settings while on deployment. so workers for uwsgi or gunicron or however you run your app on deployment should run with same credentials.

note that your user should have both read or 4 access to read the file content's, and have execute or 1 access to be able to cd into it.

Body:
EDIT: Ignore this question entirely. It was a filesystem problem.

Whenever I try to open the posts folder, I get an error:

Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36-32\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python36-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\vikas\Projects\blg\main.py", line 19, in index
    return render_template("index.html", newest_post=find_recent_post())
  File "C:\Users\vikas\Projects\blg\main.py", line 12, in find_recent_post
    with open(str(find_recent_post_name())) as post:
PermissionError: [Errno 13] Permission denied: 'posts/'

My main.py file:

from flask import Flask
from flask import render_template

app = Flask(__name__)

def find_recent_post_name():
    import glob
    posts = glob.glob("posts/")
    return posts[len(posts) - 1]

def find_recent_post():
    with open(str(find_recent_post_name())) as post:
        newest_post = post.readlines()
    return newest_post

@app.route("/")
def index():
    return render_template("index.html", newest_post=find_recent_post())

if __name__ == '__main__':
    app.run(debug=True)

My Python version is v3.6.1 and Flask v1.12.0

EDIT: Debugging code and using PowerShell seems to work.

Body:
It is not a problem with flask. you can either change the permissions on the folder /posts/ or  you can run flask as a user who has read access.

$ chmod 755 <folder names>

to give access to the user who run's flask app, or you could use:

$ sudo python main.py

to run as admin or run flask as a user who already has access. and note that you should add the same settings while on deployment. so workers for uwsgi or gunicron or however you run your app on deployment should run with same credentials.

note that your user should have both read or 4 access to read the file content's, and have execute or 1 access to be able to cd into it.


问:
Cookies On Mobile Phone
can I use a cookie or session object in my mobile website to control login from a PHP page? </p>

答:
Yes.

Mobile phones use web browsers which generally support cookies (unless the phone is really old), so a cookie based login shouldn't be a problem.

Title: Cookies On Mobile Phone


问:
Javascript Calculation issue when there is a Space during calculating input value

function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td class="normal">
    <div align="right">SGST @ 9% :</div>
  </td>
  <td nowrap class="normal">
    <div align="right">
      <div id="divCheckbox1" style="display: none;">
        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>
      </div>
      <button type="button" id="modal1" onclick="divideBy()"></button>
      <span id="answer"></span>
      <span style="display:inline-block; width: 5;"></span>
  </td>
  <tr>
    <td class="normal">
      <div align="right">CGST @ 9% :</div>
    </td>
    <td nowrap class="normal">
      <div align="right">
        <div id="divCheckbox" style="display: none;">
          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>
        </div>
        <button type="button" id="modal" onclick="divideBy()"></button>
        <span id=answer1></span>
        <span style="display:inline-block; width: 5;"></span>
    </td></code>```

答:
Just remove white spaces from input before processing anything.

   function divideBy() {
              var w = document.getElementById("first").value;
                var temp1='';
                for(var i=0; i < w.length; i++){ //Remove white spaces
                    if(w.charAt(i)!==' ')
                        temp1+=w.charAt(i);
                }

              var x = document.getElementById("second").value;
                var temp2='';
                for(var i=0; i < x.length; i++){ //Remove white spaces
                    if(x.charAt(i)!==' ')
                        temp2+=x.charAt(i);
                }

                w=parseFloat(temp1);
                x=parseFloat(temp2);

              var y = w / x;
              y = y.toFixed(2);
              var z = y;
              document.getElementById("answer").innerHTML = z;
              var a = document.getElementById("first1").value;
              var b = document.getElementById("second1").value;
              var c = a / b;
              var d = c;
              d = d.toFixed(2);
              var e = d
              document.getElementById("answer1").innerHTML = e;
              document.getElementById('modal').style.visibility = 'hidden';
              document.getElementById('modal1').style.visibility = 'hidden';
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  </code>```

Body:
function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}

SGST @ 9% :

        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>

      <button type="button" id="modal1" onclick="divideBy()"></button>

CGST @ 9% :

          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>

        <button type="button" id="modal" onclick="divideBy()"></button>


问:
Clear padding in column product info Bootstrap 3
I have site and using Bootstrap 3. I have problem with my product grid. I need to remove padding from my product list.
www.shop11.kg
Sorry my English.
Thanks

```<code><div class="tab-content">
<!-- Start gridview products -->
<div id="grid-view" class="tab-pane fade in active" role="tabpanel">
    <div class="row">
        <!-- Start Single profuct -->
        <div class="col-md-3 col-sm-4 col-lg-3 col-xs-12">
            <div class="single-product">
                <div class="product-thumb">
                    <a href="/product/1264">
                        <img class="front-img" src="/public/images/noimage/noimage_262.jpeg" alt="img">
                    </a>
                </div>
                <div class="product-info">
                    <div class="pro-title">
                        <h4>
                            <a href="/product/1264" title="ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг ">
                                ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг
                            </a>
                        </h4>
                    </div>
                    <div class="pro-price-ratting">
                        <div class="price-box">
                            <span class="price">1580 сом</span>
                        </div>
                    </div>
                    <div class="product-action">
                        <a href="javascript:void(0);" class="pro-btn add-to-cart">Купить</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- End Single profuct -->
    </div>
</div>
<!-- End gridview products -->
</code>```

答:
You can use display:flex and flex-flow:row wrap in your row class so all the items will be wrapped properly i.e

```<code>.row{
  margin-right: -15px;
  margin-left: -15px;
  display: flex;
  flex-flow: row wrap;
 }
</code>```

Body:
I have site and using Bootstrap 3. I have problem with my product grid. I need to remove padding from my product list.
www.shop11.kg
Sorry my English.
Thanks

                                ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг

                            1580 сом

                        Купить

Body:
You can use display:flex and flex-flow:row wrap in your row class so all the items will be wrapped properly i.e

.row{
  margin-right: -15px;
  margin-left: -15px;
  display: flex;
  flex-flow: row wrap;
 }


问:
security concerns with Perl /e modifier
Let's say that I have a Perl script which contains a substitution command which takes replacement string as a positional parameter and uses /e modifier:

```<code>perl -pe 's/abc/$ARGV[0]/ge;'
</code>```

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function? I mean something similar: perl -pe 's/abc//;unlink ("/tmp/file");'.

答:
Unlike /ee, there's no inherent risk to /e as it doesn't invoke the Perl parser. It simply causes code in the source file to be evaluated, just like how map BLOCK LIST and for (LIST) BLOCK evaluate their BLOCK.

Note that

```<code>s{$foo}{$bar}g
</code>```

is simply short for

```<code>s{$foo}{ qq{$bar} }eg
</code>```

So if you're ok with

```<code>perl -pe's/abc/$ARGV[0]/g'
</code>```

then you're ok with

```<code>perl -pe's/abc/"$ARGV[0]"/eg'
</code>```

and the virtually identical

```<code>perl -pe's/abc/$ARGV[0]/eg'
</code>```

Title: security concerns with Perl /e modifier

Body:
Let's say that I have a Perl script which contains a substitution command which takes replacement string as a positional parameter and uses /e modifier:

perl -pe 's/abc/$ARGV[0]/ge;'

Are there any security concerns with this approach? I mean is it possible to give such positional parameter value which causes perl to execute an unwanted function? I mean something similar: perl -pe 's/abc//;unlink ("/tmp/file");'.

Body:
Unlike /ee, there's no inherent risk to /e as it doesn't invoke the Perl parser. It simply causes code in the source file to be evaluated, just like how map BLOCK LIST and for (LIST) BLOCK evaluate their BLOCK.

Note that

s{$foo}{$bar}g

is simply short for

s{$foo}{ qq{$bar} }eg

So if you're ok with

perl -pe's/abc/$ARGV[0]/g'

then you're ok with

perl -pe's/abc/"$ARGV[0]"/eg'

and the virtually identical

perl -pe's/abc/$ARGV[0]/eg'


问:
count number of rows for a timestamp
I am working on the dataset

https://pastebin.com/PEFUspiU

I have to group it and count how many requests are there for a particular period of time and then it will be easy to draw me a chart time vs the number of requests.

for an example

```<code>**timestamp - number of request**

21-06-2016 09:00:00 - 2

21-06-2016 10:00:00 - 1

21-06-2016 11:00:00 - 5
</code>```

how can I get this count?

Thanks

P.S I tried use data['timestamp'].value_counts() but got errors:

```<code>import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6

dateparse = lambda dates: pd.datetime.strptime(dates, '%d-%m-%Y %H:%M:%S')
data = pd.read_csv('/home/amfirnas/Desktop/localhost_access_log.2016-06-21.csv',
                   parse_dates=['timestamp'], index_col='timestamp',date_parser=dateparse)

print data.head(25)

# print data['time'].value_counts()

# print data.groupby(['time']).groups.keys()

ts = data['timestamp'].value_counts()

# plt.plot(ts)
# plt.show()
</code>```

Title: count number of rows for a timestamp

Body:
I am working on the dataset

https://pastebin.com/PEFUspiU

I have to group it and count how many requests are there for a particular period of time and then it will be easy to draw me a chart time vs the number of requests.

for an example

**timestamp - number of request**

21-06-2016 09:00:00 - 2

21-06-2016 10:00:00 - 1

21-06-2016 11:00:00 - 5

how can I get this count?

Thanks

P.S I tried use data['timestamp'].value_counts() but got errors:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6

dateparse = lambda dates: pd.datetime.strptime(dates, '%d-%m-%Y %H:%M:%S')
data = pd.read_csv('/home/amfirnas/Desktop/localhost_access_log.2016-06-21.csv',
                   parse_dates=['timestamp'], index_col='timestamp',date_parser=dateparse)

print data.head(25)

# print data['time'].value_counts()

# print data.groupby(['time']).groups.keys()

ts = data['timestamp'].value_counts()

# plt.plot(ts)
# plt.show()

Body:
Reading File:

 df = pd.read_csv('/home/local/sayali/Downloads/dataset-server_logs.csv')

[In]:df

              host            timestamp  status   byte
0  192.168.102.100  21-06-2016 09:54:44     200  17811
1  192.168.102.100  21-06-2016 09:54:44     200  21630
2  192.168.100.160  21-06-2016 10:08:08     404   1098
3  192.168.100.160  21-06-2016 11:20:44     200  17811
4  192.168.100.160  21-06-2016 11:20:44     200  21630
5  192.168.102.100  21-06-2016 11:54:44     200  17811
6  192.168.102.100  21-06-2016 11:54:44     200  21630
7  192.168.102.100  21-06-2016 11:54:44     200  21630

ts = pd.DataFrame(df['timestamp'].value_counts()))

ts
Out[15]:
                     timestamp
2016-06-21 11:54:44          3
2016-06-21 09:54:44          2
2016-06-21 11:20:44          2
2016-06-21 10:08:08          1

#Convert index to datetime format using pd.to_datetime()
ts.index = pd.to_datetime(ts.index)

# PLOT
plt.title('Number of Requests based on timestamp')
plt.xlabel('Timestamp')
plt.ylabel('Total number of Requests')
#Change xticks orientation to vertical
plt.xticks(rotation='vertical')
plt.plot(ts)


问:
False positive results in email validation on mailgun
We are doing some rather rigorous front end testing in our opt in List.

When users actually subscribed to our email list we are thinking of running email validation  (  https://documentation.mailgun.com/api-email-validation.html#email-validation ) before we even save it to the database.

Does anyone know whether this built in email validation Will result in false positive?(In other words is it possible that the function will  flag agood address as bad?)

Secondly, if we do have a false positive Address in our database: does mail gun in fact check it before trying to send it anyway. Will it get to the destination?

答: You can use MailboxValidator for a second opinion. The demo page is free and you can also sign up for the free API plan if you like.</p>