问:
Using special character ? in sed
I am trying to replace phone numbers of the following format using sed:

+1(123)456-7890

Where + and the following 1 are optional. Other digits are arbitrary, but the format has to be the same (i.e. +1(123)456-7890, 1(321)456-0987, (222)555-9900 should match)

I read in this question that I either need to use extended regular expressions option or escape all occurrences of { } and ? if I want to use them as special characters. Since --regexp-extended is not available in my version of sed, I chose to escape special characters.

This is what I tried so far:

sed 's/+\?1\?([0-9]\{3\})[0-9]\{3\}-[0-9]\{4\}/test/g'

Doesn't match the numbers of the format that I specified.

The closest I could get is this:

sed 's/([0-9]\{3\})[0-9]\{3\}-[0-9]\{4\}/test/g'

This matches (222)555-9900 and like, but obviously doesn't match numbers with +1 or + or 1 in the beginning.

I am a little lost, since I've tried lots of different ways to match 0 or 1 of previous expression and none of them worked.

Just in case it might be helpful: I am using sed that was pre-installed on my Macbook.

答:
You can apply * or \? to group. For example: \(abc\)\? mean "text 'abc' can be present or not".

For your case, solution is:

```<code>sed 's/\(+\?1\)\?([0-9]\{3\})[0-9]\{3\}-[0-9]\{4\}/test/'
</code>```

or

```<code>sed -E 's/(\+?1)?\([0-9]{3}\)[0-9]{3}-[0-9]{4}/test/'
</code>```

BTW, in Macbook you have BSD sed. In linux usually used GNU sed (which also support '-E' flags as alias to '-r'). So better always to use '-E' for portability.

Title: Using special character ? in sed

Body:
You can apply * or \? to group. For example: \(abc\)\? mean "text 'abc' can be present or not".

For your case, solution is:

sed 's/\(+\?1\)\?([0-9]\{3\})[0-9]\{3\}-[0-9]\{4\}/test/'

or

sed -E 's/(\+?1)?\([0-9]{3}\)[0-9]{3}-[0-9]{4}/test/'

BTW, in Macbook you have BSD sed. In linux usually used GNU sed (which also support '-E' flags as alias to '-r'). So better always to use '-E' for portability.


来源: stackexchange

问:
Converting XML to C# object
I need to get the OrderID from these xml data:

```<code><?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>
</code>```

I have tried this one but does not work.

```<code>var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}
</code>```

Please advice.

答:
For such problem, i would always choose using XmlSerializer.
Use this classes:

```<code>    using System;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    namespace classes
    {
        [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
   public class Order
    {
        public int OrderID { get; set; }
        public string OrderStatus { get; set; }
    }

    [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class OrderArray
    {
        public List<Order> Orders { get; set; }
    }

    [XmlRoot(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class GetOrdersResponse
    {
        public string Timestamp { get; set; }
        public string Ack { get; set; }
        public string Version { get; set; }
        public string Build { get; set; }
        public OrderArray OrderArray { get; set; }
    }

    }
</code>```

Then Deserialize to your object:

```<code>XmlSerializer serializer = new XmlSerializer(typeof(GetOrdersResponse ));
using (TextReader reader = new StringReader(xmlResult))
{
    GetOrdersResponse result = (GetOrdersResponse) serializer.Deserialize(reader);
}

int id=result.OrderArray.Orders.First().OrderID; //this will return ID of first object in Orders list.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Converting XML to C# object

Body:
I need to get the OrderID from these xml data:

<?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>

I have tried this one but does not work.

var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}

Please advice.

Body:
For such problem, i would always choose using XmlSerializer.
Use this classes:

    using System;
    using System.Xml.Serialization;
    using System.Collections.Generic;
    namespace classes
    {
        [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
   public class Order
    {
        public int OrderID { get; set; }
        public string OrderStatus { get; set; }
    }

    [XmlType(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class OrderArray
    {
        public List<Order> Orders { get; set; }
    }

    [XmlRoot(Namespace = "urn:ebay:apis:eBLBaseComponents")]
    public class GetOrdersResponse
    {
        public string Timestamp { get; set; }
        public string Ack { get; set; }
        public string Version { get; set; }
        public string Build { get; set; }
        public OrderArray OrderArray { get; set; }
    }

    }

Then Deserialize to your object:

XmlSerializer serializer = new XmlSerializer(typeof(GetOrdersResponse ));
using (TextReader reader = new StringReader(xmlResult))
{
    GetOrdersResponse result = (GetOrdersResponse) serializer.Deserialize(reader);
}

int id=result.OrderArray.Orders.First().OrderID; //this will return ID of first object in Orders list.


问:
Iphone : How to return a image or anything from second view to first view?
please check the picture you will more clear what I want to present

This is the first launch in First View

It's an empty table view

There is a add button on the right bar

If you press the Add button it will push to the Second View

The second is a only 3 rows table view

Tap the first row it will pop up a alert view to let you set a name

Press create ,the text will appear in the first row

<That's the question 1,I don't know how to pass the text to the cell...>

And keep forward ,That's a custom radio button in the row 2 and row 3

Unless You click the radio button first , otherwise you can't call this methord

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

This is last two view
Icon View 1

Icon View 2

There are many buttons in the view,This the second question:
If I press one of this button,it will return to the second view and show the button icon on the tableview row 2 or row 3

Finally,press the Done button(same on the right bar)

It will back to the First View and show what you type the name , and which icon you selected
(Basis on radio button is selected)

That's the last question.

I upload my source code here:Link

You can download it ...

and here is the code about how I push the view...

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row==0) {
        [self nameInputAlertView];
    }
    RadioButtonClass *btn = [radioButtonArray objectAtIndex:[indexPath row]];
    if (btn.selected) {
        //Radio Button is selected ,use that icon
        if (indexPath.row == 1) {
            IconViewOne *iconViewOne = [[IconViewOne alloc]init];
            iconViewOne.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewOne animated:YES];
            [iconViewOne release];
        }
        if (indexPath.row==2) {
            IconViewTwo *iconViewTwo = [[IconViewTwo alloc]init];
            iconViewTwo.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewTwo animated:YES];
            [iconViewTwo release];
        }
    }
}
</code>```

so...Summary all the question...

1.How to write a text via textfield in the alert view to table view cell ?

2.How to selected an icon from last view to second view ?

3.Send all this two elements to First view : Name & Icon

I only know how to pass elements from view 1 to view 2...
Don't know how to return back......

Thanks mate , please help me to figure out this problem.I will very very appreciate ！

BTW:you can take the radio button class to add in your any project

答:
In any case if you dont like using AppDelegate Variables , there is one other method which You can use in case of Navigation Controllers :-

for eg. in "IConViewOne.m"

```<code>UITableViewCell* cell = [[[self.navigationController.viewControllers objectAtIndex:1] tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]] ;
    cell.imageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"marco%d.png",button.tag]];
</code>```

and then in "ViewWillAppear" of SecondView :-

```<code>[self.tableView reloadData];
</code>```

Similarly for passing to RootViewController u can give:-

```<code>self.navigationController.topViewController.tableView
</code>```

OR

```<code>[[self.navigationController.viewControllers objectAtIndex:0]tableView]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
please check the picture you will more clear what I want to present

This is the first launch in First View

It's an empty table view

There is a add button on the right bar

If you press the Add button it will push to the Second View

The second is a only 3 rows table view

Tap the first row it will pop up a alert view to let you set a name

Press create ,the text will appear in the first row

<That's the question 1,I don't know how to pass the text to the cell...>

And keep forward ,That's a custom radio button in the row 2 and row 3

Unless You click the radio button first , otherwise you can't call this methord

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

This is last two view
Icon View 1

Icon View 2

There are many buttons in the view,This the second question:
If I press one of this button,it will return to the second view and show the button icon on the tableview row 2 or row 3

Finally,press the Done button(same on the right bar)

It will back to the First View and show what you type the name , and which icon you selected
(Basis on radio button is selected)

That's the last question.

I upload my source code here:Link

You can download it ...

and here is the code about how I push the view...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row==0) {
        [self nameInputAlertView];
    }
    RadioButtonClass *btn = [radioButtonArray objectAtIndex:[indexPath row]];
    if (btn.selected) {
        //Radio Button is selected ,use that icon
        if (indexPath.row == 1) {
            IconViewOne *iconViewOne = [[IconViewOne alloc]init];
            iconViewOne.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewOne animated:YES];
            [iconViewOne release];
        }
        if (indexPath.row==2) {
            IconViewTwo *iconViewTwo = [[IconViewTwo alloc]init];
            iconViewTwo.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewTwo animated:YES];
            [iconViewTwo release];
        }
    }
}

so...Summary all the question...

1.How to write a text via textfield in the alert view to table view cell ?

2.How to selected an icon from last view to second view ?

3.Send all this two elements to First view : Name & Icon

I only know how to pass elements from view 1 to view 2...
Don't know how to return back......

Thanks mate , please help me to figure out this problem.I will very very appreciate ！

BTW:you can take the radio button class to add in your any project

Body:
In any case if you dont like using AppDelegate Variables , there is one other method which You can use in case of Navigation Controllers :-

for eg. in "IConViewOne.m"

UITableViewCell* cell = [[[self.navigationController.viewControllers objectAtIndex:1] tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]] ;
    cell.imageView.image=[UIImage imageNamed:[NSString stringWithFormat:@"marco%d.png",button.tag]];

and then in "ViewWillAppear" of SecondView :-

[self.tableView reloadData];

Similarly for passing to RootViewController u can give:-

self.navigationController.topViewController.tableView

OR

[[self.navigationController.viewControllers objectAtIndex:0]tableView]


问:
Can not move fragment when click navigation view
When i click item in navigation but not move new frament
I think i wrong in function replace fragment
fragmentTransaction.replace(R.id.ad_linear, fragment, CURRENT_TAG);

Anyone help me fix issue
Thanks

MainActivity.java

```<code>public class MainActivity extends ActionBarActivity implements MaterialTabListener {
    private String TAG = MainActivity.class.getSimpleName();
    MaterialTabHost tabHost;
    ViewPager pager;

    ViewPagerAdapter adapter;
    private String[] tabs =  {"Home","Category","Favourite"};
    Toolbar toolbar;
    String strMessage;
    private AdView mAdView;
    private InterstitialAd mInterstitial;
    private String name, link;
    private ProgressDialog pDialog;

    private NavigationView navigationView;
    private DrawerLayout drawer;
    private View navHeader;
    private ImageView imgNavHeaderBg, imgProfile;
    private TextView txtName, txtWebsite;
    private FloatingActionButton fab;

    // index to identify current nav menu item
    public static int navItemIndex = 0;

    // tags used to attach the fragments
    private static final String TAG_HOME = "home";
    public static String CURRENT_TAG = TAG_HOME;

    // toolbar titles respected to selected nav menu item
    private String[] activityTitles;

    // flag to load home fragment when user presses back key
    private boolean shouldLoadHomeFragOnBackPress = true;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);
            toolbar = (Toolbar) this.findViewById(R.id.toolbar);
            toolbar.setTitle(getString(R.string.app_name));
            this.setSupportActionBar(toolbar);

            tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
            pager = (ViewPager) this.findViewById(R.id.pager );
            adapter = new ViewPagerAdapter(getSupportFragmentManager());
            pager.setAdapter(adapter);

            pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // when user do a swipe the selected tab change
                    tabHost.setSelectedNavigationItem(position);

                }
            });

            for(String tab_name:tabs)
            {
                tabHost.addTab(
                        tabHost.newTab()
                                .setText(tab_name)
                                .setTabListener(MainActivity.this)
                );
            }
            //navigation

        mHandler = new Handler();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);

        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.website);
        imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

        // load nav menu header data
        loadNavHeader();

        // initializing navigation menu
        setUpNavigationView();

        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }

            //end navigation

    }

//navigation

    private void loadNavHeader() {
        // name, website
        txtName.setText("Ravi Tamada");
        txtWebsite.setText("www.androidhive.info");

        // loading header background image
        Glide.with(this).load(urlNavHeaderBg)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgNavHeaderBg);

        // Loading profile image
        Glide.with(this).load(urlProfileImg)
                .crossFade()
                .thumbnail(0.5f)
                .bitmapTransform(new CircleTransform(this))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgProfile);

        // showing dot next to notifications label
        navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
    }

    private void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_photos:
                        navItemIndex = 1;
                        CURRENT_TAG = TAG_PHOTOS;
                        break;
                    case R.id.nav_movies:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_MOVIES;
                        break;
                    case R.id.nav_notifications:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_NOTIFICATIONS;
                        break;
                    case R.id.nav_settings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_SETTINGS;
                        break;
                    case R.id.nav_about_us:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, HomeFragment.class));
                        drawer.closeDrawers();
                        return true;
                    case R.id.nav_privacy_policy:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, HomeFragment.class));
                        drawer.closeDrawers();
                        return true;
                    default:
                        navItemIndex = 0;
                }

                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked()) {
                    menuItem.setChecked(false);
                } else {
                    menuItem.setChecked(true);
                }
                menuItem.setChecked(true);

                loadHomeFragment();

                return true;
            }
        });

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }

    private void selectNavMenu() {
        navigationView.getMenu().getItem(navItemIndex).setChecked(true);
    }
    private void loadHomeFragment() {
        // selecting appropriate nav menu item
        selectNavMenu();

        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawer.closeDrawers();

            // show or hide the fab button

            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments
                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                        android.R.anim.fade_out);
                fragmentTransaction.replace(R.id.ad_linear, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        // show or hide the fab button

        //Closing drawer on item click
        drawer.closeDrawers();

        // refresh toolbar menu
        invalidateOptionsMenu();
    }

    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                HomeFragment homeFragment = new HomeFragment();
                return homeFragment;
            case 1:
                // photos
                PhotosFragment photosFragment = new PhotosFragment();
                return photosFragment;
            case 2:
                // movies fragment
                CategoryFragment moviesFragment = new CategoryFragment();
                return moviesFragment;
            case 3:
                // notifications fragment
                CategoryFragment notificationsFragment = new CategoryFragment();
                return notificationsFragment;

            case 4:
                // settings fragment
                CategoryFragment settingsFragment = new CategoryFragment();
                return settingsFragment;
            default:
                return new HomeFragment();
        }
    }
@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawers();
        return;
    }

    // This code loads home fragment when back key is pressed
    // when user is in other fragment than home
    if (shouldLoadHomeFragOnBackPress) {
        // checking if user is on other navigation menu
        // rather than home
        if (navItemIndex != 0) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            return;
        }
    }

    super.onBackPressed();
}

    //end navigation
    @Override
    public void onTabSelected(MaterialTab tab) {
        // TODO Auto-generated method stub
        pager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(MaterialTab tab) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(MaterialTab tab) {
        // TODO Auto-generated method stub

    }

    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);

        }

        public Fragment getItem(int num) {

            switch (num) {
                case 0:
                    return new HomeFragmentCheck();
                case 1:
                    return new CategoryFragmentCheck();
                case 2:
                    return new FavouriteFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem)
    {
        switch (menuItem.getItemId())
        {
        case R.id.about:
            Intent intab=new Intent(MainActivity.this,AboutActivity.class);
            startActivity(intab);
            break;

            case R.id.update:

                showPU();

                break;

        default:
            return super.onOptionsItemSelected(menuItem);
        }
        return true;

    }

}
</code>```

activity_main.xml

```<code>    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <RelativeLayout
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
<include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/m_tab_clr"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

        <it.neokree.materialtabs.MaterialTabHost
            android:id="@+id/tabHost"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@+id/toolbar"
            app:accentColor="@color/m_tab_select_accent_clr"
            app:primaryColor="@color/m_tab_clr" />

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/ad_linear"
            android:layout_below="@+id/tabHost" />

        <LinearLayout
            android:id="@+id/ad_linear"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

        </LinearLayout>
    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>
</code>```

app_bar_main.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.app.apk.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/AppTheme.AppBarOverlay">
        </android.support.design.widget.AppBarLayout>
        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"></FrameLayout>
<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

    </android.support.design.widget.CoordinatorLayout>
</code>```

答:
```<code>    Fragment fragment = getHomeFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                                android.R.anim.fade_out);
    fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
    fragmentTransaction.commit();
</code>```

Body:
When i click item in navigation but not move new frament
I think i wrong in function replace fragment
fragmentTransaction.replace(R.id.ad_linear, fragment, CURRENT_TAG);

Anyone help me fix issue
Thanks

MainActivity.java

public class MainActivity extends ActionBarActivity implements MaterialTabListener {
    private String TAG = MainActivity.class.getSimpleName();
    MaterialTabHost tabHost;
    ViewPager pager;

    ViewPagerAdapter adapter;
    private String[] tabs =  {"Home","Category","Favourite"};
    Toolbar toolbar;
    String strMessage;
    private AdView mAdView;
    private InterstitialAd mInterstitial;
    private String name, link;
    private ProgressDialog pDialog;

    private NavigationView navigationView;
    private DrawerLayout drawer;
    private View navHeader;
    private ImageView imgNavHeaderBg, imgProfile;
    private TextView txtName, txtWebsite;
    private FloatingActionButton fab;

    // index to identify current nav menu item
    public static int navItemIndex = 0;

    // tags used to attach the fragments
    private static final String TAG_HOME = "home";
    public static String CURRENT_TAG = TAG_HOME;

    // toolbar titles respected to selected nav menu item
    private String[] activityTitles;

    // flag to load home fragment when user presses back key
    private boolean shouldLoadHomeFragOnBackPress = true;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);
            toolbar = (Toolbar) this.findViewById(R.id.toolbar);
            toolbar.setTitle(getString(R.string.app_name));
            this.setSupportActionBar(toolbar);

            tabHost = (MaterialTabHost) this.findViewById(R.id.tabHost);
            pager = (ViewPager) this.findViewById(R.id.pager );
            adapter = new ViewPagerAdapter(getSupportFragmentManager());
            pager.setAdapter(adapter);

            pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // when user do a swipe the selected tab change
                    tabHost.setSelectedNavigationItem(position);

                }
            });

            for(String tab_name:tabs)
            {
                tabHost.addTab(
                        tabHost.newTab()
                                .setText(tab_name)
                                .setTabListener(MainActivity.this)
                );
            }
            //navigation

        mHandler = new Handler();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);

        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.website);
        imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

        // load nav menu header data
        loadNavHeader();

        // initializing navigation menu
        setUpNavigationView();

        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }

            //end navigation

    }

//navigation

    private void loadNavHeader() {
        // name, website
        txtName.setText("Ravi Tamada");
        txtWebsite.setText("www.androidhive.info");

        // loading header background image
        Glide.with(this).load(urlNavHeaderBg)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgNavHeaderBg);

        // Loading profile image
        Glide.with(this).load(urlProfileImg)
                .crossFade()
                .thumbnail(0.5f)
                .bitmapTransform(new CircleTransform(this))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgProfile);

        // showing dot next to notifications label
        navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
    }

    private void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_photos:
                        navItemIndex = 1;
                        CURRENT_TAG = TAG_PHOTOS;
                        break;
                    case R.id.nav_movies:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_MOVIES;
                        break;
                    case R.id.nav_notifications:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_NOTIFICATIONS;
                        break;
                    case R.id.nav_settings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_SETTINGS;
                        break;
                    case R.id.nav_about_us:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, HomeFragment.class));
                        drawer.closeDrawers();
                        return true;
                    case R.id.nav_privacy_policy:
                        // launch new intent instead of loading fragment
                        startActivity(new Intent(MainActivity.this, HomeFragment.class));
                        drawer.closeDrawers();
                        return true;
                    default:
                        navItemIndex = 0;
                }

                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked()) {
                    menuItem.setChecked(false);
                } else {
                    menuItem.setChecked(true);
                }
                menuItem.setChecked(true);

                loadHomeFragment();

                return true;
            }
        });

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }

    private void selectNavMenu() {
        navigationView.getMenu().getItem(navItemIndex).setChecked(true);
    }
    private void loadHomeFragment() {
        // selecting appropriate nav menu item
        selectNavMenu();

        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawer.closeDrawers();

            // show or hide the fab button

            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments
                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                        android.R.anim.fade_out);
                fragmentTransaction.replace(R.id.ad_linear, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        // show or hide the fab button

        //Closing drawer on item click
        drawer.closeDrawers();

        // refresh toolbar menu
        invalidateOptionsMenu();
    }

    private Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                HomeFragment homeFragment = new HomeFragment();
                return homeFragment;
            case 1:
                // photos
                PhotosFragment photosFragment = new PhotosFragment();
                return photosFragment;
            case 2:
                // movies fragment
                CategoryFragment moviesFragment = new CategoryFragment();
                return moviesFragment;
            case 3:
                // notifications fragment
                CategoryFragment notificationsFragment = new CategoryFragment();
                return notificationsFragment;

            case 4:
                // settings fragment
                CategoryFragment settingsFragment = new CategoryFragment();
                return settingsFragment;
            default:
                return new HomeFragment();
        }
    }
@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawers();
        return;
    }

    // This code loads home fragment when back key is pressed
    // when user is in other fragment than home
    if (shouldLoadHomeFragOnBackPress) {
        // checking if user is on other navigation menu
        // rather than home
        if (navItemIndex != 0) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            return;
        }
    }

    super.onBackPressed();
}

    //end navigation
    @Override
    public void onTabSelected(MaterialTab tab) {
        // TODO Auto-generated method stub
        pager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(MaterialTab tab) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(MaterialTab tab) {
        // TODO Auto-generated method stub

    }

    private class ViewPagerAdapter extends FragmentStatePagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);

        }

        public Fragment getItem(int num) {

            switch (num) {
                case 0:
                    return new HomeFragmentCheck();
                case 1:
                    return new CategoryFragmentCheck();
                case 2:
                    return new FavouriteFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home, menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem)
    {
        switch (menuItem.getItemId())
        {
        case R.id.about:
            Intent intab=new Intent(MainActivity.this,AboutActivity.class);
            startActivity(intab);
            break;

            case R.id.update:

                showPU();

                break;

        default:
            return super.onOptionsItemSelected(menuItem);
        }
        return true;

    }

}

activity_main.xml

    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <RelativeLayout
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
<include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/m_tab_clr"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

        <it.neokree.materialtabs.MaterialTabHost
            android:id="@+id/tabHost"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_below="@+id/toolbar"
            app:accentColor="@color/m_tab_select_accent_clr"
            app:primaryColor="@color/m_tab_clr" />

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/ad_linear"
            android:layout_below="@+id/tabHost" />

        <LinearLayout
            android:id="@+id/ad_linear"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

        </LinearLayout>
    </RelativeLayout>

</android.support.v4.widget.DrawerLayout>

app_bar_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.app.apk.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:theme="@style/AppTheme.AppBarOverlay">
        </android.support.design.widget.AppBarLayout>
        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"></FrameLayout>
<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

    </android.support.design.widget.CoordinatorLayout>


问:
Error installing GitHub desktop "Application cannot be started, contact the application vendor."
I've recently upgraded from windows 7 to windows 10 and when installing GitHub desktop, I'm getting the following error:

```<code>"Application cannot be started, contact the application vendor."
</code>```

When I click on details, there is the following error:

```<code>"Unable to install this application because an application with the same identity is already installed."
</code>```

I tried several troubleshoots, such as:

running the .exe file as administrator;

deleting the 2.0 folder from Local/apps/

disabling windows defender

But none of them seems to work. I cant understand what the problem may be, since I had no trouble installing github desktop on windows 7.

答: Simply right click on the installation file and run as admin. It will automatically adjust itself to your system settings and install without error.</p>

Body:
I've recently upgraded from windows 7 to windows 10 and when installing GitHub desktop, I'm getting the following error:

"Application cannot be started, contact the application vendor."

When I click on details, there is the following error:

"Unable to install this application because an application with the same identity is already installed."

I tried several troubleshoots, such as:

running the .exe file as administrator;

deleting the 2.0 folder from Local/apps/

disabling windows defender

But none of them seems to work. I cant understand what the problem may be, since I had no trouble installing github desktop on windows 7.


问:
How to use MBProgressHUD with swift
here is my code , but it showing the progress . is there any error in this code? please give some idea to fix this, or give some link related to this.</p>

```<code>class Approval: UIViewController {

var hud: MBProgressHUD = MBProgressHUD()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchData()
}
   func fetchData(){
      hud.show(true)
      // doing some http request
      dispatch_async(dispatch_get_main_queue()) {
         hud.hide(true)
      }
   }

}
</code>```

答:
step 1 : Download "MBProgressHUD.h" and "MBProgressHUD.m" file and Add both file into your project. it will ask you to Bridging for Objective C files. if you already done bridging then it won't ask.

step 2 : In Bridging File import MBProgressHUD "import MBProgressHUD.h"

step 3 : use below code to show progress hud or hide hud.

for Show

```<code>DispatchQueue.main.async {
    MBProgressHUD.showAdded(to: self.view, animated: true)
}
</code>```

for hide

```<code>DispatchQueue.main.async {
    MBProgressHUD.hide(for: self.view, animated: true)
}
</code>```

Title: How to use MBProgressHUD with swift

Body:
here is my code , but it showing the progress . is there any error in this code? please give some idea to fix this, or give some link related to this.

class Approval: UIViewController {

var hud: MBProgressHUD = MBProgressHUD()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchData()
}
   func fetchData(){
      hud.show(true)
      // doing some http request
      dispatch_async(dispatch_get_main_queue()) {
         hud.hide(true)
      }
   }

}

Body:
step 1 : Download "MBProgressHUD.h" and "MBProgressHUD.m" file and Add both file into your project. it will ask you to Bridging for Objective C files. if you already done bridging then it won't ask.

step 2 : In Bridging File import MBProgressHUD "import MBProgressHUD.h"

step 3 : use below code to show progress hud or hide hud.

for Show

DispatchQueue.main.async {
    MBProgressHUD.showAdded(to: self.view, animated: true)
}

for hide

DispatchQueue.main.async {
    MBProgressHUD.hide(for: self.view, animated: true)
}


问:
Java Comparator Sort Differently
public class StringComparatorTest {

```<code>public static void main(String[] args) {
    String[] a = {"abc9", "abc", "abc123", "ab9"};
    String[] b = {"abc9", "abc", "abc123", "ab9"};
    String[] c = {"abc9", "abc", "abc123", "ab9"};

    System.out.print("a_Origin     : ");
    printArray(a);
    System.out.print("c_Origin     : ");
    printArray(c);

    System.out.print("a_Default    : ");
    Arrays.sort(a);
    printArray(a);

    System.out.print("c_Default    : ");
    Arrays.sort(c);
    printArray(c);

    System.out.print("a_Customized1: ");
    Arrays.sort(a, new StringComparator());
    printArray(a);

    System.out.print("b_Customized1: ");
    Arrays.sort(b, new StringComparator());
    printArray(b);

    System.out.print("c_Customized2: ");
    Arrays.sort(c, new StringComparator2());
    printArray(c);
}

public static void printArray(String[] arr){
    for (String str: arr) {
        System.out.print(str + " ");
    }
    System.out.println();
}
</code>```

}

public class StringComparator implements Comparator {

```<code>@Override
public int compare(String s1, String s2) {
    if(s1.length() == s2.length()){
        if(s1.equals(s2))
            return 0;
        else{
            for(int i = 0; i < s1.length(); i++){
                if(s1.charAt(i) > s2.charAt(i)){
                    return 1;
                }else {
                    return -1;
                }
            }
            return 0;
        }
    }else if(s1.length() < s2.length()){
        return -1;
    }else{
        return 1;
    }
}
</code>```

}

public class StringComparator2 implements Comparator {

```<code>@Override
public int compare(String s1, String s2) {
    if (s1.length() == s2.length()) {
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) > s2.charAt(i)) {
                return 1;
            } else if (s1.charAt(i) < s2.charAt(i)) {
                return -1;
            }
        }
        return 0;
    } else if (s1.length() < s2.length()) {
        return -1;
    } else {
        return 1;
    }
}
</code>```

}

I have to comparators to sort a String objects, it turns out the "StringComparator" has some bugs but I can't figure out.

"StringComparator" works fine at
"Arrays.sort(b, new StringComparator());"
the out put order is as expected.

but when I use Default sort(steps below) and then sort by "StringComparator", the bug shows:

" Arrays.sort(a);
 Arrays.sort(a, new StringComparator());"

the out put orders are different which should be the same.
(Array a and b are same)

Can someone explain a little bit?
Thanks a lot~

答:
This works - compare in StringComparator class -

```<code>public int compare(String s1, String s2) {
        if(s1.length() == s2.length()){
            if(s1.equals(s2))
                return 0;
            else{
                for(int i = 0; i < s1.length(); i++){
                    if(s1.charAt(i) != s2.charAt(i)) {
                        return s1.charAt(i) - s2.charAt(i);
                    }
                }
            }
        }
        return s1.length() - s2.length();
    }
</code>```

The result given for an array which is sorted first with default sort and then custom comparator(a_customized) is same as the on with using the custom comparator (b_customized)

The issue in old code seems to be here -

```<code> if(s1.charAt(i) > s2.charAt(i)){
    return 1;
 }else {
    return -1;
 }
</code>```

if the s1.charAt(i) == s2.charAt(i) then also it was returning -1;

Title: Java Comparator Sort Differently

Body:
public class StringComparatorTest {

public static void main(String[] args) {
    String[] a = {"abc9", "abc", "abc123", "ab9"};
    String[] b = {"abc9", "abc", "abc123", "ab9"};
    String[] c = {"abc9", "abc", "abc123", "ab9"};

    System.out.print("a_Origin     : ");
    printArray(a);
    System.out.print("c_Origin     : ");
    printArray(c);

    System.out.print("a_Default    : ");
    Arrays.sort(a);
    printArray(a);

    System.out.print("c_Default    : ");
    Arrays.sort(c);
    printArray(c);

    System.out.print("a_Customized1: ");
    Arrays.sort(a, new StringComparator());
    printArray(a);

    System.out.print("b_Customized1: ");
    Arrays.sort(b, new StringComparator());
    printArray(b);

    System.out.print("c_Customized2: ");
    Arrays.sort(c, new StringComparator2());
    printArray(c);
}

public static void printArray(String[] arr){
    for (String str: arr) {
        System.out.print(str + " ");
    }
    System.out.println();
}

}

public class StringComparator implements Comparator {

@Override
public int compare(String s1, String s2) {
    if(s1.length() == s2.length()){
        if(s1.equals(s2))
            return 0;
        else{
            for(int i = 0; i < s1.length(); i++){
                if(s1.charAt(i) > s2.charAt(i)){
                    return 1;
                }else {
                    return -1;
                }
            }
            return 0;
        }
    }else if(s1.length() < s2.length()){
        return -1;
    }else{
        return 1;
    }
}

}

public class StringComparator2 implements Comparator {

@Override
public int compare(String s1, String s2) {
    if (s1.length() == s2.length()) {
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) > s2.charAt(i)) {
                return 1;
            } else if (s1.charAt(i) < s2.charAt(i)) {
                return -1;
            }
        }
        return 0;
    } else if (s1.length() < s2.length()) {
        return -1;
    } else {
        return 1;
    }
}

}

I have to comparators to sort a String objects, it turns out the "StringComparator" has some bugs but I can't figure out.

"StringComparator" works fine at
"Arrays.sort(b, new StringComparator());"
the out put order is as expected.

but when I use Default sort(steps below) and then sort by "StringComparator", the bug shows:

" Arrays.sort(a);
 Arrays.sort(a, new StringComparator());"

the out put orders are different which should be the same.
(Array a and b are same)

Can someone explain a little bit?
Thanks a lot~

Body:
This works - compare in StringComparator class -

public int compare(String s1, String s2) {
        if(s1.length() == s2.length()){
            if(s1.equals(s2))
                return 0;
            else{
                for(int i = 0; i < s1.length(); i++){
                    if(s1.charAt(i) != s2.charAt(i)) {
                        return s1.charAt(i) - s2.charAt(i);
                    }
                }
            }
        }
        return s1.length() - s2.length();
    }

The result given for an array which is sorted first with default sort and then custom comparator(a_customized) is same as the on with using the custom comparator (b_customized)

The issue in old code seems to be here -

 if(s1.charAt(i) > s2.charAt(i)){
    return 1;
 }else {
    return -1;
 }

if the s1.charAt(i) == s2.charAt(i) then also it was returning -1;


问:
Very simple Javascript ad placement engine
I have ten different banner ads uploaded on my site. I want to make a Javascript program that will randomly show one each time a page is loaded. How would I do this?</p>

答:
Google is overwhelming with ad rotators. Checkout:

The JavaScript Source: Text Effects: Banner Ad Rotator

A JavaScript Banner Ad Rotator Script


问:
How can I get values from CKEditor and display them in an HTML table?

i have to show  equation from editor to the following table as it is

答:
You can get the content from ckeditor, by the following piece code. You need to place the id associated to your html element in place of <id-for-the-textarea> in the provided code.
CKEDITOR.replace() will replace the textarea having id passed to it earlier with a CKEDITOR functional text box. After that you can get the text by calling CKEDITOR.instances on the id of the html element that CKEDITOR had override.

```<code>var msgEditor = CKEDITOR.replace('<id-for-the-textarea>', {
        height: "150",
        // placeholder:'Type text...',
        //extraPlugins: 'placeholder',
    });
var msg = CKEDITOR.instances.<id-for-the-textarea>.document.getBody().getHtml();
</code>```

In order to get only the equation from the text received, you can use

```<code>msg.replace("solve this mathematical equation", "");
</code>```

Body:
You can get the content from ckeditor, by the following piece code. You need to place the id associated to your html element in place of <id-for-the-textarea> in the provided code.
CKEDITOR.replace() will replace the textarea having id passed to it earlier with a CKEDITOR functional text box. After that you can get the text by calling CKEDITOR.instances on the id of the html element that CKEDITOR had override.

var msgEditor = CKEDITOR.replace('<id-for-the-textarea>', {
        height: "150",
        // placeholder:'Type text...',
        //extraPlugins: 'placeholder',
    });
var msg = CKEDITOR.instances.<id-for-the-textarea>.document.getBody().getHtml();

In order to get only the equation from the text received, you can use

msg.replace("solve this mathematical equation", "");


问:
Java thread is consuming more time when the input increases
I have written a Java program to scrap through huge log files. For parallel processing of files, I am using thread concept. Below is the source code for the same.

```<code>ExecutorService threadPool = Executors.newFixedThreadPool(8);
        for(int i=0; i < files.size(); i++)
        {
            threadPool.execute(new ProcessInThreads(i+"`"+files.get(i),fr) {
                 public void run()
                 {
                    long threadId = Thread.currentThread().getId();
                    Initiate(fr,threadId);

                 }
             });
        }
        threadPool.shutdown();
</code>```

When the files.size()=300, the program completes execution in less than minutes, but when the files.size() increases, the performance degrades. What could be reason?? How to overcome the same.

Here files is an array of the filenames to be processed, populating this array is taking less than 10 seconds.

ProcessInThreads is a class which implements Runnable interface. if the loop runs for 500 files, will 500 instance of ProcessInThreads be created. How can I kill/release the instance after every execution?

答:
You are using a fixed size thread pool, it will only be running 8 threads at a time. If you add more input files, you should expect it to take longer to go through all of them.

That being said, don't expect much better performance by throwing more threads at the problem. It depends on many other factors like the nature of the file read, etc.

Body:
I have written a Java program to scrap through huge log files. For parallel processing of files, I am using thread concept. Below is the source code for the same.

ExecutorService threadPool = Executors.newFixedThreadPool(8);
        for(int i=0; i < files.size(); i++)
        {
            threadPool.execute(new ProcessInThreads(i+"`"+files.get(i),fr) {
                 public void run()
                 {
                    long threadId = Thread.currentThread().getId();
                    Initiate(fr,threadId);

                 }
             });
        }
        threadPool.shutdown();

When the files.size()=300, the program completes execution in less than minutes, but when the files.size() increases, the performance degrades. What could be reason?? How to overcome the same.

Here files is an array of the filenames to be processed, populating this array is taking less than 10 seconds.

ProcessInThreads is a class which implements Runnable interface. if the loop runs for 500 files, will 500 instance of ProcessInThreads be created. How can I kill/release the instance after every execution?


问:
how does a static variable not get reassigned when inside the function
I have a question regarding the answer in this question but I can not comment on it because I have less than 50 rep.

I was wondering in the answer foo() is being called multiple times and the static variable is being assigned the same number of times. So why is it that the static variable is not reassigned to 10 each time?

答:
You've got the shorter answer, but let me expand a bit on that.

Any object, has a storage duration. The storage duration determines the "lifetime" of the object (or variable).

Static storage is one of the storage durations, marked by keyword static. Now, to elaborate on lifetime, let us check the relevant parts of the C11 standard, chapter §6.2.4.

From paragraph 2,

The lifetime of an object is the portion of program execution during which storage is
  guaranteed to be reserved for it. An object exists, has a constant address and retains
  its last-stored value throughout its lifetime. [....]

So, the last stored value is retained throughout the lifetime.

Now, for the objects with static storage duration, paragraph 3,

An object whose identifier is declared without the storage-class specifier
  _Thread_local, and either with external or internal linkage or with the storage-class
  specifier static, has static storage duration. Its lifetime is the entire execution of the
  program and its stored value is initialized only once, prior to program startup.

Now, referring to your question, the statement you saw is the initialization and as per the rule specified, it happens only once (prior to program startup), so the initialization is not repeated over for multiple function calls. The variable retains the last-stored value.


答: When you define a static or global variable it goes in data segment of memory model and it occupies that allocation for the life of the program, of course scope is associated with each variable where it is defined. So when you enter the function again, the variable exists and it also remembers the last content. So ideally you cannot redefine a variable, if you bound it with condition than scope will protect it and hence it is a new variable. </p>

Title: how does a static variable not get reassigned when inside the function

Body:
I have a question regarding the answer in this question but I can not comment on it because I have less than 50 rep.

I was wondering in the answer foo() is being called multiple times and the static variable is being assigned the same number of times. So why is it that the static variable is not reassigned to 10 each time?


问:
Javascript short circuiting in if statement
I am confused about the below if statement code. Not sure what it is exactly doing

```<code>if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}
</code>```

Can someone please help me to understand this?

Is it a short-circuiting in if statement:
i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

答:
Notes :

This short-circuiting is good for the performance, as it allows significant bits of calculations to be skipped.

The AND operator (&&) returns true if both expressions are true, otherwise it returns false.

DEMO

var x = 1;
var y = 5;

if (x > 0 && y < 6) { console.log(x) }; // true

if(x > 1 && y < 6) { console.log(x) }; // false```

As suggested by nnnnnn in his comment, the first this.props.filterURL is checking for a truthy value, not for true specifically. If the property is not defined that is falsy, but if the value is null or 0 or an empty string those are all falsy too.

Body:
I am confused about the below if statement code. Not sure what it is exactly doing

if (this.props.filterURL && nextProps.filterURL !== this.props.filterURL) {}

Can someone please help me to understand this?

Is it a short-circuiting in if statement:
i.e

1- if first this.props.filterURL from left side is false then it will return false. 2- if first this.props.filterURL has a value then it will return true and the second variable nextProps.filterURL will be compared to this.props.filterURL on the right most of the statement?

Body:
Notes :

This short-circuiting is good for the performance, as it allows significant bits of calculations to be skipped.

The AND operator (&&) returns true if both expressions are true, otherwise it returns false.

DEMO

var x = 1;
var y = 5;

if (x > 0 && y < 6) { console.log(x) }; // true

if(x > 1 && y < 6) { console.log(x) }; // false

As suggested by nnnnnn in his comment, the first this.props.filterURL is checking for a truthy value, not for true specifically. If the property is not defined that is falsy, but if the value is null or 0 or an empty string those are all falsy too.


问:
VBA run-time Error 9: subscript out of range
I'm running a vba to extract the url from a column of hyperlinked texts:

```<code>Sub RemoveHyperlinks()
Dim Cell As Range

Dim i As Long
Dim k As Long
k = 1
Set Cell = Workbooks("Company_List.xlms").Sheets("Sheet1").UsedRange

i = 0

Do Until i = Cell.Hyperlinks.Count
If Cell.Hyperlinks.Count > 0 Then
Workbooks("Company_List.xlms").Sheets("Sheet1").Cells(k, 1).Value = Cell.Hyperlinks.Item(1).Address
i = i + 1
k = k + 1
End If

Loop

End Sub
</code>```

And the runtime error 9 occurs at the line:

Set Cell = Workbooks("Company_List.xlms").Sheets("Sheet1").UsedRange

Can anyone help with this? The Workbook name and Sheet name is correct, and my column data starts at A1 with heading title of column.

EDIT (2 Apr 2017):
This piece of code has another error as it generated a list of url that appears to be the first one on the list. The entire list looks the same, but clicking through to each one would bring me to the correct hyperlink. I would like to have the list to have all the correct respective urls, how should I edit this code?

EDIT:
I found the error, it should be
Workbooks("Company_List.xlms").Sheets("Sheet1").Cells(k, 1).Value = Cell.Hyperlinks.Item(k).Address

答:
If Workbooks("Company_List.xlms").Sheets("Sheet1").UsedRange returns subscript out of range then there is either not a workbook named "Company_List.xlms" in Workbooks or there is not a sheet named "Sheet1" in that workbook.

I suspect the first since the name is strange and should be "Company_List.xlsm" instead.

Body:
I'm running a vba to extract the url from a column of hyperlinked texts:

Sub RemoveHyperlinks()
Dim Cell As Range

Dim i As Long
Dim k As Long
k = 1
Set Cell = Workbooks("Company_List.xlms").Sheets("Sheet1").UsedRange

i = 0

Do Until i = Cell.Hyperlinks.Count
If Cell.Hyperlinks.Count > 0 Then
Workbooks("Company_List.xlms").Sheets("Sheet1").Cells(k, 1).Value = Cell.Hyperlinks.Item(1).Address
i = i + 1
k = k + 1
End If

Loop

End Sub

And the runtime error 9 occurs at the line:

Set Cell = Workbooks("Company_List.xlms").Sheets("Sheet1").UsedRange

Can anyone help with this? The Workbook name and Sheet name is correct, and my column data starts at A1 with heading title of column.

EDIT (2 Apr 2017):
This piece of code has another error as it generated a list of url that appears to be the first one on the list. The entire list looks the same, but clicking through to each one would bring me to the correct hyperlink. I would like to have the list to have all the correct respective urls, how should I edit this code?

EDIT:
I found the error, it should be
Workbooks("Company_List.xlms").Sheets("Sheet1").Cells(k, 1).Value = Cell.Hyperlinks.Item(k).Address


问:
How can I add class active when a link clicked and redirect?
My vue component is like this:

<template>

        ...

                Message

                Review

                Resolution

        ...

</template>

```

When the link is clicked, it will call the url, I want to add class active on the clicked link after reloading the page.

But, I'm still confused, How can I do it?

答:
You could add a computed property, say, currentPath:

```<code>computed: {
  currentPath () {
    // grab current url and return the part after `baseUrl `
    // e.g. '/message/inbox' or '/message/review'
    return '/message/inbox'
  }
}
</code>```

And a CSS class for your special style:

```<code>.active-item {
  /* key-value pairs here */
}
</code>```

Then in your template, you could apply the class to the matched item:

```<code><a :href="baseUrl+'/message/inbox'"
   :class="{ 'active-item': currentPath === '/message/inbox'}">
   class="list-group-item">Message</a>
<a :href="baseUrl+'/message/review'"
   :class="{ 'active-item': currentPath === '/message/review'}">
   class="list-group-item">Review</a>
</code>```

Please read the doc on binding HTML classes with object syntax

Body:
My vue component is like this:

<template>

        ...

                Message

                Review

                Resolution

        ...

</template>

When the link is clicked, it will call the url, I want to add class active on the clicked link after reloading the page.

But, I'm still confused, How can I do it?

Body:
You could add a computed property, say, currentPath:

computed: {
  currentPath () {
    // grab current url and return the part after `baseUrl `
    // e.g. '/message/inbox' or '/message/review'
    return '/message/inbox'
  }
}

And a CSS class for your special style:

.active-item {
  /* key-value pairs here */
}

Then in your template, you could apply the class to the matched item:

<a :href="baseUrl+'/message/inbox'"
   :class="{ 'active-item': currentPath === '/message/inbox'}">
   class="list-group-item">Message</a>
<a :href="baseUrl+'/message/review'"
   :class="{ 'active-item': currentPath === '/message/review'}">
   class="list-group-item">Review</a>

Please read the doc on binding HTML classes with object syntax

ContentLicense: CC BY-SA 4.0


问:
conda build R packages to different library location
I'm following the instructions from https://www.continuum.io/content/conda-data-science in order to build a CRAN-available R package (e.g. synthpop).

```<code>conda skeleton cran synthpop
conda build r-synthpop
</code>```

How can I change the default conda build sequence to install to a different library location, as I don't have permission to install to the default one?

```<code>* installing to library ‘/path/to/default/lib’
Error: ERROR: no permission to install to directory ‘/path/to/default/lib’
</code>```

Also, I'm running conda build from within a virtual env.

Raised this as an issue here: https://github.com/ContinuumIO/anaconda-issues/issues/1562

答:
Hi I was faced with this similar problem recently. After some researches, I wrote one passage about it

https://github.com/alfredzj/Documentations/blob/master/anaconda-set-up.md

I don't think changing location is a good idea.

Body:
I'm following the instructions from https://www.continuum.io/content/conda-data-science in order to build a CRAN-available R package (e.g. synthpop).

conda skeleton cran synthpop
conda build r-synthpop

How can I change the default conda build sequence to install to a different library location, as I don't have permission to install to the default one?

* installing to library ‘/path/to/default/lib’
Error: ERROR: no permission to install to directory ‘/path/to/default/lib’

Also, I'm running conda build from within a virtual env.

Raised this as an issue here: https://github.com/ContinuumIO/anaconda-issues/issues/1562


问:
How can I draw bitmap over the text in editfield?
I would like to draw bitmap image over the text that I type in editfield.

How can I do that?

答: You will need to subclass EditField and then override the paint method. In the override, call super.paint before you do anything so that the component can draw the text, and then you can use the Graphics object provided by paint to draw a Bitmap over the contents of the EditField (Graphics.drawBitmap).


问:
Android Java API 21 to Azure MongoDB
Am trying to put a document on my MongoDB located in Azure. The problem I am facing is that I can't connect to the service. Azure provides the connector string so it should be working.

I am getting this errors

```<code>03-29 15:47:24.265 3578-3578/name.bagi.levente.pedometer W/org.bson.ObjectId: Failed to get process identifier from JMX, using random number instead
        java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
    Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory"
</code>```

and

```<code>FATAL EXCEPTION: main                                                                           Process: name.bagi.levente.pedometer, PID: 3578                                                                           java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.CodeSource java.security.ProtectionDomain.getCodeSource()' on a null object reference
</code>```

I am using this code to connect

```<code>//Line below causes exception
MongoClient mongoClient = new MongoClient(new MongoClientURI("AzureProvidedString?ssl=true&sslInvalidHostNameAllowed=true"));
        BasicDBObject document = new BasicDBObject();
        document.put("id",2);
        document.put("location", 3);
        document.put("steps", 4);
        mongoClient.getDatabase("FitnessData").getCollection("FitnessCollection").insertOne(Document.parse(document.toJson()));
</code>```

My dependencies

```<code>dependencies{
        compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
        // https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
        compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.4.2'

    }
</code>```

I tried using Mongo driver 3.2.2 and am getting a different error. Other solutions here seem to be the same and are working.

答:
It sounds like you want to access MongoDB on Azure from Android using Mongo Driver for Java. There was a similar SO thread mongodb 3.x driver Android compatibility which got a same issue with yours. The issue reason is the offical driver mongo-java-driver which is incompatible on Android. A solution is using the third-party driver porting for Android https://github.com/matfur92/mongo-java-driver.

However, directly access MongoDB on Android is not a good choice, even for sending data. Per my experience, the best practice is use REST webservice for sending & storing data on MongoDB, please refer to the MongoDB reference HTTP Interface to get fully featured RESTful Web Services powered by MongoDB on Azure WebApps, or just create Azure Mobile App to receive data from Android.

Title: Android Java API 21 to Azure MongoDB

Body:
Am trying to put a document on my MongoDB located in Azure. The problem I am facing is that I can't connect to the service. Azure provides the connector string so it should be working.

I am getting this errors

03-29 15:47:24.265 3578-3578/name.bagi.levente.pedometer W/org.bson.ObjectId: Failed to get process identifier from JMX, using random number instead
        java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
    Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory"

and

FATAL EXCEPTION: main                                                                           Process: name.bagi.levente.pedometer, PID: 3578                                                                           java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.CodeSource java.security.ProtectionDomain.getCodeSource()' on a null object reference

I am using this code to connect

//Line below causes exception
MongoClient mongoClient = new MongoClient(new MongoClientURI("AzureProvidedString?ssl=true&sslInvalidHostNameAllowed=true"));
        BasicDBObject document = new BasicDBObject();
        document.put("id",2);
        document.put("location", 3);
        document.put("steps", 4);
        mongoClient.getDatabase("FitnessData").getCollection("FitnessCollection").insertOne(Document.parse(document.toJson()));

My dependencies

dependencies{
        compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
        // https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
        compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.4.2'

    }

I tried using Mongo driver 3.2.2 and am getting a different error. Other solutions here seem to be the same and are working.


问:
Anaconda on Windows 10: iPython and Spyder fail to start in Python3 environment
I'm using Windows 10 and I have Anaconda with Python 2 installed, so my root environment is Python 2. I created an additional Python 3 environment and among other packages installed iPython and Spyder into it. I used the Anaconda Navigator to install the packages.

I can activate and deactivate the environment using Windows CMD just fine. After activating the Python 3 environment in the CMD the ipython command typed into the same CMD starts up Python 3.6.1.

The Anaconda Startmenu folder does contain shortcuts to iPython and Spyder both for Python 2 and Python 3 now. I can use those to start both for Python 2 as before, but the Python 3 versions won't start. And there is no error message or crash or anything.

When clicking on the Python 3 iPython shortcut a command prompt pops up for a split second and immediatly closes again. Spyder does not even open a command prompt, it does absolutely nothing, I presume it's because iPython fails. Checking the task manager shows that there is no Python running in the background at all, so it really does not start.

Now I know that iPython 3 itself is not broken because I can start it from within CMD after switching environments, nonetheless I deinstalled and reinstalled them both, no change.

I then went into the shortcut to get the exact command it was executing to write a small batch file with a pause command to see if anything gets displayed when iPython fails. Doing a right-click on the shortcut and executing "open file location" leads me to python.exe in the Python 3 environment base folder, and executing that works fine of course.

So now I'm stumped since I have no leads to solve or even analyze the problem properly, over the entire course of action not a single error message ever appeared anywhere.

Any hints and suggestions are appreciated.

EDIT:

The target of the Python 3 shortcut in the properties looks like this:

C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\envs\Python3\python.exe C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\cwp.py C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\envs\Python3 "C:/Users/My.Name/AppData/Loca

The working shortcut to Python 2 looks pretty much the same:

C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\python.exe C:\Users\My.Name\AppData\Local\Continuum\Anaconda2\cwp.py C:\Users\My.Name\AppData\Local\Continuum\Anaconda2 "C:/Users/My.Name/AppData/Local/Continuum/Anaconda2/pyth

答:
I found the problem.

As it turns out the module menuinst wasn't automatically installed into the new environment so I had to manually install it. Now everything works.


问:
Notice: Undefined index: when trying to submit form with a null array
Good day, could anybody be willing to explain this notice everytime I submit the form. This is my code below:

```<code><form action="" method="post" name="f">
<TABLE id="dataTable" border="1">
<thead>
        <tr>
            <td></td>
            <td>Product Name</td>
            <td>Model</td>
            <td>Description</td>
        </tr>
    </thead>
<tbody>

</tbody>
</TABLE>
<br>

<input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >

<input type="submit" name="submit" value="Submit">

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
</code>```

```<code><?php

if($_POST['submit']) {

    $dbC = new imsFunction();

    if ($_POST['item'] == null) {
        echo 'No Data';
    } else {
        foreach ($_POST['item'] as $key => $value) {

            $item = $_POST["item"][$key];
            $price = $_POST["price"][$key];
            $qty = $_POST["qty"][$key];

                $sql = $dbC->qryExec('Insert Into tbl_test (item,price,quant) Values (?, ?, ?)', [$item, $price, $qty]);
                //$sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");
            }
        }
    }
}
</code>```

?>

This is the javascript code to add the data to the table rows.

```<code>function addRow(tableID) {

    var enteredItem = $("#item").val();
    var enteredPrice = $("#price").val();
    var enteredQty= $("#qty").val();

    if (!enteredItem) {
        alert("Please entere item name!");
    } else {
        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = "<input type='text' name='item[]' value='"+enteredItem+"' readonly />";

        var cell3 = row.insertCell(2);
        cell3.innerHTML = "<input type='text'  name='price[]' value='"+enteredPrice+"' readonly />";

        var cell4 = row.insertCell(3);
        cell4.innerHTML = "<input type='text'  name='qty[]' value='"+enteredQty+"' readonly />";

        document.getElementById('item').value='';
    }
}
</code>```

The input was name like 'item[]'. what I want to do is to catch error if the user submit button without adding data first. But what happen is, it gives out a Notice that Undefined index: item in the foreach loop.

答:
There are some mistakes on input fields name

```<code><input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >
</code>```

They are all named : ProductNme that's why these lines won't work

```<code>$item = $_POST["item"][$key];
        $price = $_POST["price"][$key];
        $qty = $_POST["qty"][$key];
</code>```

These indexes(item,price,qty) do not exist in $_POST array sent to the server.
Hence the undefined index message.
Good luck

Body:
Good day, could anybody be willing to explain this notice everytime I submit the form. This is my code below:

<form action="" method="post" name="f">

            Product Name
            Model
            Description

<input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >

<input type="submit" name="submit" value="Submit">

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

<?php

if($_POST['submit']) {

    $dbC = new imsFunction();

    if ($_POST['item'] == null) {
        echo 'No Data';
    } else {
        foreach ($_POST['item'] as $key => $value) {

            $item = $_POST["item"][$key];
            $price = $_POST["price"][$key];
            $qty = $_POST["qty"][$key];

                $sql = $dbC->qryExec('Insert Into tbl_test (item,price,quant) Values (?, ?, ?)', [$item, $price, $qty]);
                //$sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");
            }
        }
    }
}

?>

This is the javascript code to add the data to the table rows.

function addRow(tableID) {

    var enteredItem = $("#item").val();
    var enteredPrice = $("#price").val();
    var enteredQty= $("#qty").val();

    if (!enteredItem) {
        alert("Please entere item name!");
    } else {
        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = "<input type='text' name='item[]' value='"+enteredItem+"' readonly />";

        var cell3 = row.insertCell(2);
        cell3.innerHTML = "<input type='text'  name='price[]' value='"+enteredPrice+"' readonly />";

        var cell4 = row.insertCell(3);
        cell4.innerHTML = "<input type='text'  name='qty[]' value='"+enteredQty+"' readonly />";

        document.getElementById('item').value='';
    }
}

The input was name like 'item[]'. what I want to do is to catch error if the user submit button without adding data first. But what happen is, it gives out a Notice that Undefined index: item in the foreach loop.

Body:
There are some mistakes on input fields name

<input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >

They are all named : ProductNme that's why these lines won't work

$item = $_POST["item"][$key];
        $price = $_POST["price"][$key];
        $qty = $_POST["qty"][$key];

These indexes(item,price,qty) do not exist in $_POST array sent to the server.
Hence the undefined index message.
Good luck


问:
How to use proxies to download files
I'm downloading a website with heaps of GPL-licensed free content, however my computer exceeds the daily download limit of 20 files (out of some 10,000!)

Is there a proxy service I can use (via PHP) to continue accessing such content?

答:
Technically, shouldn't a proxy only get you an extra 20 files per day? I hope you have a lot of proxies lined up.

Another option would be to use Tor, which could potentially spread your requests amongst hundreds of end points.

Personally, I'd approach the site owner first. If the files truly are GPL and the host is following the spririt of GPL and not just trying to maximize advertising revenue, they shouldn't have too much of an issue giving you the lot.

Title: How to use proxies to download files


问:
Removing duplicate entries in sequence in postgres table
We have a table of scientific data that's sampled twice a day across about 10,000-12,000 sensors across the country. Each sensor pings some data to us that is put into this table.

A simplified version is below - sensor_rt_data:

```<code>id | BIGINT PK
sensor-name | STRING
location-id | INT FK
sensor-value | NUMERIC(0,2)
last-updated | TIMESTAMP_WITH_TIMEZONE
</code>```

Unfortunately, there's duplicated samples throughout the day that I'm trying to remove. Eg.

Simplified for (location-id last column):

```<code>2017-03-30 06:30 | 49.00 | 1
2017-03-30 06:30 | 37.00 | 2
2017-03-30 10:30 | 51.00 | 1
2017-03-30 10:30 | 35.00 | 2
2017-03-30 15:30 | 51.00 | 1
2017-03-30 15:30 | 35.00 | 2
2017-03-30 18:30 | 51.00 | 1
2017-03-30 20:30 | 42.00 | 1
</code>```

Trying to cull the three 51s to just show 1; I can remove duplicates with distinct but I'm not sure how I go about removing only duplicates in series so it looks like this:

```<code>2017-03-30 06:30 | 49.00 | 1
2017-03-30 06:30 | 37.00 | 2
2017-03-30 18:30 | 51.00 | 1
2017-03-30 15:30 | 35.00 | 2
2017-03-30 20:30 | 42.00 | 1
</code>```

I also had a look and play with Deleting Duplicates on the wiki but my query didn't seem to delete the series data.

Before you suggest it, we can't ignore the duplicates at the source (that would be lovely, I'm totally sensing that!) due to some legal kerfuffle that I'm not privvy to.

Would SQL be able to handle that sort of deduping, or would I have to move that data to another table? We've had this running for 6 months and the table size is getting big and most of it is unnecessary ping data.

EDIT:
For clarification, this is a big table of many records, I was trying to remove all duplicates that duplicate the previous "latest" (but only checking certain fields - locationid, sensor-value and last updated) if that makes sense.

If this was done outside of SQL, I could load each row  (ordered by date ASC) and store the "latest" reading in an array for each location-id, if the retrieved row matches the same sensor-value as the last one for that location-id, I'd discard it.

At the end, I should have data that doesn't duplicate the sensor-value across time and only stores changes in the sensor values (which are what's relevant).

EDIT

Thanks to the answer below, I've got it working, however...

So after some tweaking of the query, i've got it going on our dataset. However, I'm noticing that these sensor readings are down to just two records...

```<code>2017-02-28 00:00:00 144
2017-02-27 00:00:00 139
2017-02-26 00:00:00 139
.. 20 more at 139
2017-02-14 00:00:00 129
...10 more at 129
</code>```

turns into:

```<code>2017-02-28 00:00:00 144
2017-02-14 00:00:00 129
</code>```

I'm expecting the 139 to make an appearance there? The example works fine from the accepted answer tho.

答:
Something like:

```<code>delete from sensordata s
using (
  select id,
         sensor_value = lead(sensor_value) over w as same_value_as_next
  from sensordata
  window w as (partition by location_id order by last_updated)
) x
where x.id = s.id
  and x.same_value_as_next
;
</code>```

However as this is going over all rows, this is not going to be very efficient, but I can't think of a better way right now.

Online example: http://rextester.com/SGPOB26281

Body:
We have a table of scientific data that's sampled twice a day across about 10,000-12,000 sensors across the country. Each sensor pings some data to us that is put into this table.

A simplified version is below - sensor_rt_data:

id | BIGINT PK
sensor-name | STRING
location-id | INT FK
sensor-value | NUMERIC(0,2)
last-updated | TIMESTAMP_WITH_TIMEZONE

Unfortunately, there's duplicated samples throughout the day that I'm trying to remove. Eg.

Simplified for (location-id last column):

2017-03-30 06:30 | 49.00 | 1
2017-03-30 06:30 | 37.00 | 2
2017-03-30 10:30 | 51.00 | 1
2017-03-30 10:30 | 35.00 | 2
2017-03-30 15:30 | 51.00 | 1
2017-03-30 15:30 | 35.00 | 2
2017-03-30 18:30 | 51.00 | 1
2017-03-30 20:30 | 42.00 | 1

Trying to cull the three 51s to just show 1; I can remove duplicates with distinct but I'm not sure how I go about removing only duplicates in series so it looks like this:

2017-03-30 06:30 | 49.00 | 1
2017-03-30 06:30 | 37.00 | 2
2017-03-30 18:30 | 51.00 | 1
2017-03-30 15:30 | 35.00 | 2
2017-03-30 20:30 | 42.00 | 1

I also had a look and play with Deleting Duplicates on the wiki but my query didn't seem to delete the series data.

Before you suggest it, we can't ignore the duplicates at the source (that would be lovely, I'm totally sensing that!) due to some legal kerfuffle that I'm not privvy to.

Would SQL be able to handle that sort of deduping, or would I have to move that data to another table? We've had this running for 6 months and the table size is getting big and most of it is unnecessary ping data.

EDIT:
For clarification, this is a big table of many records, I was trying to remove all duplicates that duplicate the previous "latest" (but only checking certain fields - locationid, sensor-value and last updated) if that makes sense.

If this was done outside of SQL, I could load each row  (ordered by date ASC) and store the "latest" reading in an array for each location-id, if the retrieved row matches the same sensor-value as the last one for that location-id, I'd discard it.

At the end, I should have data that doesn't duplicate the sensor-value across time and only stores changes in the sensor values (which are what's relevant).

EDIT

Thanks to the answer below, I've got it working, however...

So after some tweaking of the query, i've got it going on our dataset. However, I'm noticing that these sensor readings are down to just two records...

2017-02-28 00:00:00 144
2017-02-27 00:00:00 139
2017-02-26 00:00:00 139
.. 20 more at 139
2017-02-14 00:00:00 129
...10 more at 129

turns into:

2017-02-28 00:00:00 144
2017-02-14 00:00:00 129

I'm expecting the 139 to make an appearance there? The example works fine from the accepted answer tho.

Body:
Something like:

delete from sensordata s
using (
  select id,
         sensor_value = lead(sensor_value) over w as same_value_as_next
  from sensordata
  window w as (partition by location_id order by last_updated)
) x
where x.id = s.id
  and x.same_value_as_next
;

However as this is going over all rows, this is not going to be very efficient, but I can't think of a better way right now.

Online example: http://rextester.com/SGPOB26281