问:
How to correctly implement "hamburger" to back button functionality when using Fragments
How to move to a new fragment and automatically have the "hamburger" menu change to a <- button which brings the user back to the previous menu?

This seems to be an arcane art, no matter how many stackoverflow questions I read and things I try the "hamburger" menu always just opens the drawer. I am getting confused with certain posts using backstacklisteners to change icons, others using the onoptionselected and others directly attaching a click listener.

Activity

```<code>    public class MainActivity extends AppCompatActivity {

        private ActionBarDrawerToggle drawerToggle;
        private ActionBar actionBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setToolbar();
            // show first fragment here
        }

        private void setToolbar() {
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBar = getSupportActionBar();

            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
                drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
                drawerToggle.setDrawerIndicatorEnabled(true);
                drawerToggle.syncState();
            }
        }

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mnuSettings:
                showSettingsFragment();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showSettingsFragment() {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.fragHolder, new SettingsFragment())
                .addToBackStack(null)
                .commit();
    }
}
</code>```

Activity Layout

```<code><?xml version="1.0" encoding="utf-8"?>

<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"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true">

    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                 android:id="@+id/toolbar"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:background="@color/primary"
                 android:minHeight="?attr/actionBarSize"
                 app:popupTheme="@style/Theme.AppCompat.Light"
                 app:theme="@style/Theme.AppCompat">

            </android.support.v7.widget.Toolbar>

            <FrameLayout
                 android:id="@+id/pnlSearch"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_margin="8dp">

                <EditText
                     android:id="@+id/txtSearch"
                     android:layout_width="match_parent"
                     android:layout_height="44dp"
                     android:background="#FAFAFA"
                     android:gravity="center"
                     android:hint="@string/search_hint"
                     android:imeOptions="flagNoExtractUi|actionDone"
                     android:inputType="textNoSuggestions"
                     android:maxLines="1"
                     android:textSize="16sp"/>

                <ImageView
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="start|center_vertical"
                     android:layout_marginLeft="15dp"
                     android:layout_marginStart="15dp"
                     android:alpha="0.2"
                     android:contentDescription="@string/magnifying_glass_icon"
                     android:src="@drawable/ic_search_black_24dp"/>

                <Button
                     android:id="@+id/btnClear"
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="end|center_vertical"
                     android:layout_marginEnd="15dp"
                     android:layout_marginRight="15dp"
                     android:alpha="0.5"
                     android:background="@drawable/ic_clear_black_24dp"
                     android:visibility="gone"/>

            </FrameLayout>

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

        <FrameLayout
             android:id="@+id/fragHolder"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

    </LinearLayout>

    <android.support.design.widget.NavigationView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:headerLayout="@layout/nav_header"
         app:menu="@menu/toolbar_menu"/>

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

SettingsFragment:

```<code>public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        setToolbarTitle();
    }

    private void setToolbarTitle() {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.settings);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
</code>```

What I am looking for is the standard way to acheive this and not to start adding click/backstack listeners without understanding how its really meant to be done.

答:
You should animate the hamburger

call method like

For Animate hamburger to back arrow

below should call before wherever you call add or replace fragment

```<code>animateBurgerToArrow(mDrawerLayout, 1, 0);
</code>```

in your Activity

From your comment:

onOptionsItemSelected is never called from the fragment

Solution!! : return false in activity's onOptionsItemSelected onclick of Home

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             return false;
        case R.id.mnuSettings:
            animateBurgerToArrow(mDrawerLayout, 1, 0);
            showSettingsFragment();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
</code>```

Animate back arrow to hamburger

below should call before wherever you call popBackStack

```<code>animateBurgerToArrow(mDrawerLayout, 0, 1);
</code>```

in your SettingsFragment

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            animateBurgerToArrow(mDrawerLayout, 0, 1);
            getFragmentManager().popBackStack();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
</code>```

Method

```<code>private void animateBurgerToArrow(final View drawerView,int start,int end){
    ValueAnimator anim = ValueAnimator.ofFloat(start,end);
    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            float slideOffset = (Float) valueAnimator.getAnimatedValue();
            mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
        }
    });
    anim.setInterpolator(new DecelerateInterpolator());
    // You can change this duration to more closely match that of the default animation.
    anim.setDuration(500);
    anim.start();
}
</code>```

Body:
How to move to a new fragment and automatically have the "hamburger" menu change to a <- button which brings the user back to the previous menu?

This seems to be an arcane art, no matter how many stackoverflow questions I read and things I try the "hamburger" menu always just opens the drawer. I am getting confused with certain posts using backstacklisteners to change icons, others using the onoptionselected and others directly attaching a click listener.

Activity

    public class MainActivity extends AppCompatActivity {

        private ActionBarDrawerToggle drawerToggle;
        private ActionBar actionBar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setToolbar();
            // show first fragment here
        }

        private void setToolbar() {
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            actionBar = getSupportActionBar();

            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
                drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.open, R.string.close);
                drawerToggle.setDrawerIndicatorEnabled(true);
                drawerToggle.syncState();
            }
        }

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mnuSettings:
                showSettingsFragment();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void showSettingsFragment() {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.fragHolder, new SettingsFragment())
                .addToBackStack(null)
                .commit();
    }
}

Activity Layout

<?xml version="1.0" encoding="utf-8"?>

<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"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent"
                                        android:fitsSystemWindows="true">

    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                 android:id="@+id/toolbar"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:background="@color/primary"
                 android:minHeight="?attr/actionBarSize"
                 app:popupTheme="@style/Theme.AppCompat.Light"
                 app:theme="@style/Theme.AppCompat">

            </android.support.v7.widget.Toolbar>

            <FrameLayout
                 android:id="@+id/pnlSearch"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_margin="8dp">

                <EditText
                     android:id="@+id/txtSearch"
                     android:layout_width="match_parent"
                     android:layout_height="44dp"
                     android:background="#FAFAFA"
                     android:gravity="center"
                     android:hint="@string/search_hint"
                     android:imeOptions="flagNoExtractUi|actionDone"
                     android:inputType="textNoSuggestions"
                     android:maxLines="1"
                     android:textSize="16sp"/>

                <ImageView
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="start|center_vertical"
                     android:layout_marginLeft="15dp"
                     android:layout_marginStart="15dp"
                     android:alpha="0.2"
                     android:contentDescription="@string/magnifying_glass_icon"
                     android:src="@drawable/ic_search_black_24dp"/>

                <Button
                     android:id="@+id/btnClear"
                     android:layout_width="24dp"
                     android:layout_height="24dp"
                     android:layout_gravity="end|center_vertical"
                     android:layout_marginEnd="15dp"
                     android:layout_marginRight="15dp"
                     android:alpha="0.5"
                     android:background="@drawable/ic_clear_black_24dp"
                     android:visibility="gone"/>

            </FrameLayout>

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

        <FrameLayout
             android:id="@+id/fragHolder"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

    </LinearLayout>

    <android.support.design.widget.NavigationView
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         app:headerLayout="@layout/nav_header"
         app:menu="@menu/toolbar_menu"/>

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

SettingsFragment:

public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        setToolbarTitle();
    }

    private void setToolbarTitle() {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.settings);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

What I am looking for is the standard way to acheive this and not to start adding click/backstack listeners without understanding how its really meant to be done.

Body:
You should animate the hamburger

call method like

For Animate hamburger to back arrow

below should call before wherever you call add or replace fragment

animateBurgerToArrow(mDrawerLayout, 1, 0);

in your Activity

From your comment:

onOptionsItemSelected is never called from the fragment

Solution!! : return false in activity's onOptionsItemSelected onclick of Home

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             return false;
        case R.id.mnuSettings:
            animateBurgerToArrow(mDrawerLayout, 1, 0);
            showSettingsFragment();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Animate back arrow to hamburger

below should call before wherever you call popBackStack

animateBurgerToArrow(mDrawerLayout, 0, 1);

in your SettingsFragment

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            animateBurgerToArrow(mDrawerLayout, 0, 1);
            getFragmentManager().popBackStack();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }

Method

private void animateBurgerToArrow(final View drawerView,int start,int end){
    ValueAnimator anim = ValueAnimator.ofFloat(start,end);
    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            float slideOffset = (Float) valueAnimator.getAnimatedValue();
            mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
        }
    });
    anim.setInterpolator(new DecelerateInterpolator());
    // You can change this duration to more closely match that of the default animation.
    anim.setDuration(500);
    anim.start();
}


来源: stackexchange

问:
If statemts, only if the subject is of a certian class
For an assignment have to turn words into the dog lantin version of them, thats not the problem though, they love to find the conditions for our code to fail, so i think they will attempt to trip us up by having different class types in the auto code. My problem is i want to apply my function to a sentence, I can do it for an indivdual word, but I dont know how to have it apply for every word in the sentece. So i have one function here

```<code>def dog_latinify_word(word):
    """Takes a word and returns the dog latin version of the word"""
    first_letter = word[0]
    first_letter.lower()
    vowels = ('a','e','i','o','u','1','2','3','4','5',
          '6','7','8','9','0')
    dogify_vowel = word + 'woof'
    dogify_constant = word[1:] + word[0] + "oof"
    if word.startswith(vowels):
        result = dogify_vowel
    elif first_letter != vowels:
        result = dogify_constant
        return result
</code>```

but i dont know how to have this function work on every item in a list, because i need to have each word be "dog latinified"

So I have another function to take the sentence that then splits it so each word is its own item in a list, but when I go to call on this function, it only works for class str, and not list. So in my rambling ways can someone point me in the direction of having this function apply into every item in a list, rather than just a string

my code for the secondary function

```<code>def dog_latinify_sentence(sentence):
    """translate a sentence into dog latin"""
    str_split = sentence.split(' ')
    dogify_sentence = dog_latinify_word(str_split)
    return dogify_sentence
</code>```

sorry for the rambling im very tired

答:
You can fix this by just adding a for loop over the list object like this.

```<code>def dog_latinify_sentence(sentence):
    """translate a sentence into dog latin"""
    str_split = sentence.split(' ')
    dogify_sentence = ""
    for s in str_split:
            dogify_sentence += dog_latinify_word(s)
    return dogify_sentence
</code>```

Above code removes spaces between words. In case you want to preserve spaces,

```<code>dogify_sentence = " ".join([dog_latinify_word(s) for s in str_split])
</code>```

It just gets results from dog_latinify_word() and stitch them back!

ContentLicense: CC BY-SA 3.0

Body:
For an assignment have to turn words into the dog lantin version of them, thats not the problem though, they love to find the conditions for our code to fail, so i think they will attempt to trip us up by having different class types in the auto code. My problem is i want to apply my function to a sentence, I can do it for an indivdual word, but I dont know how to have it apply for every word in the sentece. So i have one function here

def dog_latinify_word(word):
    """Takes a word and returns the dog latin version of the word"""
    first_letter = word[0]
    first_letter.lower()
    vowels = ('a','e','i','o','u','1','2','3','4','5',
          '6','7','8','9','0')
    dogify_vowel = word + 'woof'
    dogify_constant = word[1:] + word[0] + "oof"
    if word.startswith(vowels):
        result = dogify_vowel
    elif first_letter != vowels:
        result = dogify_constant
        return result

but i dont know how to have this function work on every item in a list, because i need to have each word be "dog latinified"

So I have another function to take the sentence that then splits it so each word is its own item in a list, but when I go to call on this function, it only works for class str, and not list. So in my rambling ways can someone point me in the direction of having this function apply into every item in a list, rather than just a string

my code for the secondary function

def dog_latinify_sentence(sentence):
    """translate a sentence into dog latin"""
    str_split = sentence.split(' ')
    dogify_sentence = dog_latinify_word(str_split)
    return dogify_sentence

sorry for the rambling im very tired

Body:
You can fix this by just adding a for loop over the list object like this.

def dog_latinify_sentence(sentence):
    """translate a sentence into dog latin"""
    str_split = sentence.split(' ')
    dogify_sentence = ""
    for s in str_split:
            dogify_sentence += dog_latinify_word(s)
    return dogify_sentence

Above code removes spaces between words. In case you want to preserve spaces,

dogify_sentence = " ".join([dog_latinify_word(s) for s in str_split])

It just gets results from dog_latinify_word() and stitch them back!


问:
Karaf Cellar distributed architecture
I am developing an IoT application (it controls EnOcean devices). I have N servers controlling the devices and one management application, which manages and configures the devices associated with each server.

The servers are basically identical, but hold different device data. Their basic functionality is configured in Maven: I don't expect to reconfigure from Karaf's command line.

Is this an appropriate application for Karaf Cellar?  I can see that Cellar would help with the configuration of the N servers, but can I include the management app in the same cluster? Or is the Cellar philosophy more that the management function should also be replicated across all N servers?

答:
Karaf Cellar usually does a full replication for all nodes within one group. So what you could do is, create two different types of groups. One group containing your N servers, while the other group has only one "Management" node with it.
For communication across group boundaries, use the Cellar Distributed OSGi. That way you can have specific services located in one group as providing services while the consumer can be in the other one.

In future please ask at the karaf users mailinglist, as it has much more people answering :-)

Title: Karaf Cellar distributed architecture


问:
Php days error when calculating -1 month
I surprised when i getting the issue in PHP date calculation.

```<code>$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need
</code>```

but in

```<code>$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct
</code>```

please help me in this how could i resolve this issue.

答:
Why not to take advantage of DateTime relative formats and simply use:</p>

```<code>$date = new DateTime('first day of last month');
echo $date->format('Y-m-d');
</code>```

Body:
I surprised when i getting the issue in PHP date calculation.

$add = '- 30 days';
echo date('Y-m-01', strtotime($add)); // result is 2017-02-01 which is correct as need

but in

$add = '-1 month';
echo date('Y-m-01', strtotime($add)); // result is 2017-03-01 which is in correct

please help me in this how could i resolve this issue.

Body:
Why not to take advantage of DateTime relative formats and simply use:

$date = new DateTime('first day of last month');
echo $date->format('Y-m-d');


问:
I want to show the whole c program on screen in android
I wanted to show the whole c program on screen which should be visible to user.

I used textView but i am getting errors as the code contains special symbols.

for example:

```<code> android:text=" #include <stdio.h>
 int main()
{
int x, y, temp;

printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n",x,y);

temp = x;
x = y;
y = temp;

printf("After Swapping\nx = %d\ny = %d\n",x,y);

return 0;
 }" />
</code>```

I also want that the user should be able to scroll the code as the codes may be larger than the example.I am a noob so please suggest me any alternate for the textView to display the code.

答:
EDIT: THIS WORKS BUT READS ONLY A SINGLE LINE OF THE TEXT IN THE TXT FILE

String line;
TextView view;

```<code>@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addingprogrammultipletimes);

    AssetManager am = getAssets();
    try {
        InputStream is = am.open("add.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine();
        view = (TextView) findViewById(R.id.textView);
        view.setText(line);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

Body:
I wanted to show the whole c program on screen which should be visible to user.

I used textView but i am getting errors as the code contains special symbols.

for example:

 android:text=" #include <stdio.h>
 int main()
{
int x, y, temp;

printf("Enter the value of x and y\n");
scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n",x,y);

temp = x;
x = y;
y = temp;

printf("After Swapping\nx = %d\ny = %d\n",x,y);

return 0;
 }" />

I also want that the user should be able to scroll the code as the codes may be larger than the example.I am a noob so please suggest me any alternate for the textView to display the code.

Body:
EDIT: THIS WORKS BUT READS ONLY A SINGLE LINE OF THE TEXT IN THE TXT FILE

String line;
TextView view;

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

    AssetManager am = getAssets();
    try {
        InputStream is = am.open("add.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine();
        view = (TextView) findViewById(R.id.textView);
        view.setText(line);
    } catch (Exception e) {
        e.printStackTrace();
    }

}


问:
Visual C++ Sending message across thread
I am writting a small server application which has ServerSocket object waiting for and create connection socket.
Each connection has a SocketListener and a SocketSender for transfering data.

Each SocketListener is a separate thread. When a connection is disconnect by client, SocketListener send a message to ServerSocket notify that it is closing, so that ServerSocket can clear the handle for that connection from a list.

However, don't know why the message is not received by SocketListener thread. I have tried to narrow down the message filter, but no luck. Could someone help me with this.

```<code>DWORD ServerSocket::m_ThreadFunc() {
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed\n");
    return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT_STR, &hints, &result);
if (iResult != 0) {
    printf("getaddrinfo failed\n");
    WSACleanup();
    return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
    printf("socket failed\n");
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    printf("bind failed\n");
    freeaddrinfo(result);
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
    printf("listen failed\n");
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

// allow listener thread to report back its state
MSG msg;
ZeroMemory(&msg, sizeof(MSG));

//force create message queue
PeekMessage(&msg, NULL, WM_USER, WM_USER + 100, PM_NOREMOVE);

printf("Listing for clients on port %s \n", DEFAULT_PORT_STR);
while (listening) {
    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket != INVALID_SOCKET) {
        printf("Client connected\n");

        sender = new SocketSender(ClientSocket);

        listener = new SocketListener(ClientSocket, this->m_threadId);
        printf("Listener created\n");

        listener->setSender(sender);
        listener->startThread();

        printf("Listener started\n");

        listenerList.push_back(listener);
        senderList.push_back(sender);

        printf("Listener list size: %d \n", listenerList.size());

        printf("Listener pushed to list\n");

        //delete socket data if listener close itself due to connection lost or disconnect.

    }
    else {
        int error = WSAGetLastError();
        printf("accept failed\n");
        switch (error) {
        case 10093:
            listening = false;
            try {
                closesocket(ListenSocket);
            }
            catch (...) {}
            return 1;
        }
    }

    printf("Check message queue for thread message\n");
    //check thread message queue
    //GetMessage(&msg, NULL, 0, 0); //this blocks untill a message is get.

    PeekMessage(&msg, NULL, WM_USER, WM_USER + 100, PM_REMOVE);

    if (msg.message == WM_USER + 1)
    {
        //ProcessCustomMessage(msg);
        m_deleteListener((SocketListener*)msg.wParam);
        printf("Recieved message from ThreadID: %d \n", msg.wParam);
    }
    printf("Recieved message from ThreadID: %d \n", msg.message);

    printf("Server socket complete 1 loop\n");
}

return 0;
</code>```

}

```<code>DWORD SocketListener::m_ThreadFunc() {
listening = true;

rapidxml::xml_document<> doc;

printf("Start thread with ID: %d \n", this->m_threadId);
printf("Parent Thread ID: %d \n", this->_iParentID);

while (listening) {
    int iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);
        recvbuf[iResult - 1] = 0; // null terminate the string according to the length

        // The message spec indicates the XML will end in a "new line"
        // character which can be either a newline or caraiage feed
        // Search for either and replace with a NULL to terminate
        if (recvbuf[iResult - 2] == '\n' || recvbuf[iResult - 2] == '\r')
            recvbuf[iResult - 2] = 0;

        try {
            doc.parse<0>(&recvbuf[0]);
            HandleXMLMessage(&doc);
        }

        catch (...) {}

    }
    else {
        printf("Thread %d is being closed, sending signal to parent (%d)\n", this->m_threadId, this->_iParentID);

        if (PostThreadMessage(this->_iParentID, WM_APP + 1, NULL, NULL) == 0)
        {
            printf("Client cant send Message before closing the conn ! \n");
            printf("Last error %d", GetLastError());
        }
        else {
            printf("Client sent Closing Message successfully \n");
        }

        closesocket(ClientSocket);
        return 1;
    }
}

printf("Server terminate connection\n");

printf("Thread %d is closed, sending signal to parent (%d)\n", this->m_threadId,this->_iParentID);

PostThreadMessage(this->_iParentID, WM_USER + 1, (WPARAM)this->m_threadId, NULL);

return 0;
</code>```

}

Thank you very much.

答:
accept function is a blocking call, so it looks like after accepting first connection your loop gets stuck at

```<code>ClientSocket = accept(ListenSocket, NULL, NULL);
</code>```

And does not check thread message queue until the next connection is made.

You also need to check the return result of PeekMessage to know whether message was actually peeked otherwise msg variable will contain garbage.

Body:
I am writting a small server application which has ServerSocket object waiting for and create connection socket.
Each connection has a SocketListener and a SocketSender for transfering data.

Each SocketListener is a separate thread. When a connection is disconnect by client, SocketListener send a message to ServerSocket notify that it is closing, so that ServerSocket can clear the handle for that connection from a list.

However, don't know why the message is not received by SocketListener thread. I have tried to narrow down the message filter, but no luck. Could someone help me with this.

DWORD ServerSocket::m_ThreadFunc() {
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
    printf("WSAStartup failed\n");
    return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT_STR, &hints, &result);
if (iResult != 0) {
    printf("getaddrinfo failed\n");
    WSACleanup();
    return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
    printf("socket failed\n");
    freeaddrinfo(result);
    WSACleanup();
    return 1;
}

// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
    printf("bind failed\n");
    freeaddrinfo(result);
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
    printf("listen failed\n");
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

// allow listener thread to report back its state
MSG msg;
ZeroMemory(&msg, sizeof(MSG));

//force create message queue
PeekMessage(&msg, NULL, WM_USER, WM_USER + 100, PM_NOREMOVE);

printf("Listing for clients on port %s \n", DEFAULT_PORT_STR);
while (listening) {
    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket != INVALID_SOCKET) {
        printf("Client connected\n");

        sender = new SocketSender(ClientSocket);

        listener = new SocketListener(ClientSocket, this->m_threadId);
        printf("Listener created\n");

        listener->setSender(sender);
        listener->startThread();

        printf("Listener started\n");

        listenerList.push_back(listener);
        senderList.push_back(sender);

        printf("Listener list size: %d \n", listenerList.size());

        printf("Listener pushed to list\n");

        //delete socket data if listener close itself due to connection lost or disconnect.

    }
    else {
        int error = WSAGetLastError();
        printf("accept failed\n");
        switch (error) {
        case 10093:
            listening = false;
            try {
                closesocket(ListenSocket);
            }
            catch (...) {}
            return 1;
        }
    }

    printf("Check message queue for thread message\n");
    //check thread message queue
    //GetMessage(&msg, NULL, 0, 0); //this blocks untill a message is get.

    PeekMessage(&msg, NULL, WM_USER, WM_USER + 100, PM_REMOVE);

    if (msg.message == WM_USER + 1)
    {
        //ProcessCustomMessage(msg);
        m_deleteListener((SocketListener*)msg.wParam);
        printf("Recieved message from ThreadID: %d \n", msg.wParam);
    }
    printf("Recieved message from ThreadID: %d \n", msg.message);

    printf("Server socket complete 1 loop\n");
}

return 0;

}

DWORD SocketListener::m_ThreadFunc() {
listening = true;

rapidxml::xml_document<> doc;

printf("Start thread with ID: %d \n", this->m_threadId);
printf("Parent Thread ID: %d \n", this->_iParentID);

while (listening) {
    int iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);
        recvbuf[iResult - 1] = 0; // null terminate the string according to the length

        // The message spec indicates the XML will end in a "new line"
        // character which can be either a newline or caraiage feed
        // Search for either and replace with a NULL to terminate
        if (recvbuf[iResult - 2] == '\n' || recvbuf[iResult - 2] == '\r')
            recvbuf[iResult - 2] = 0;

        try {
            doc.parse<0>(&recvbuf[0]);
            HandleXMLMessage(&doc);
        }

        catch (...) {}

    }
    else {
        printf("Thread %d is being closed, sending signal to parent (%d)\n", this->m_threadId, this->_iParentID);

        if (PostThreadMessage(this->_iParentID, WM_APP + 1, NULL, NULL) == 0)
        {
            printf("Client cant send Message before closing the conn ! \n");
            printf("Last error %d", GetLastError());
        }
        else {
            printf("Client sent Closing Message successfully \n");
        }

        closesocket(ClientSocket);
        return 1;
    }
}

printf("Server terminate connection\n");

printf("Thread %d is closed, sending signal to parent (%d)\n", this->m_threadId,this->_iParentID);

PostThreadMessage(this->_iParentID, WM_USER + 1, (WPARAM)this->m_threadId, NULL);

return 0;

}

Thank you very much.

Body:
accept function is a blocking call, so it looks like after accepting first connection your loop gets stuck at

ClientSocket = accept(ListenSocket, NULL, NULL);

And does not check thread message queue until the next connection is made.

You also need to check the return result of PeekMessage to know whether message was actually peeked otherwise msg variable will contain garbage.


问:
PowerShell script ffmpeg
Being the good Windows systems admin that I am, I'm finally getting around to learning PowerShell. With that being said, I have no idea what I'm doing (surprise, surprise).

I thought that it would be a good learning experience for me to play around with PowerShell at home, far away from my production environment. Recently, I've begun using FFMPEG to convert all of my .mkv files to .mp4 so I could have better playback support to my PlayStation 3 via Plex, and thought that this would be a good learning experience.

The command I've been running is as follows:

```<code>ffmpeg -i OldVideoName.mkv -vcodec copy -acodec ac3 OldVideoName.mp4
</code>```

What I want is have a PowerShell script that will run once, scanning a folder and all sub-folders for .mkv files (Get-ChildItem ".*.mkv"), transcode them to .mp4 via the above command, and place them in the same location as the .mkv with the same naming scheme.

Example of running the script with D:\Videos as the target directory:

D:\Videos\home_dvr\movies\video1.mkv --> D:\Videos\home_dvr\video1.mp4
D:\Videos\home_dvr\tv\video2.mkv --> D:\Videos\home_dvr\tv\video2.mp4

As you can guess, I can't figure it out for the life of me. Here's the latest attempt before giving up.

```<code>    $oldvid = Get-ChildItem .\*.mkv -Recurse
    $newvid = $oldvid.Name.split(‘.’)[0]; ForEach-Object {
            .\ffmpeg.exe -i $oldvid -y -vcodec copy -acodec ac3 $newvid".mp4”
    }
</code>```

Any help would be appreciated!

答:
It seems as if with the current version of powershell the behaviour has changed a bit. The Answer suggested by Keith Hill doesn't work anymore, it needs to have the .FullName removed in order to work with PS 5.1 (Build 14393).
So the current answer would be:

```<code>$oldvids = Get-ChildItem -Filter "*.mkv" -Recurse
foreach ($oldvid in $oldvids) {
    $newvid = [io.path]::ChangeExtension($oldvid, '.mp4')
    .\ffmpeg.exe -i $oldvid-y -map 0 -c:v copy -c:a ac3 $newvid
}
</code>```

Also -c:v -c:a are now preferred over -vcodec and -acodec.
If you want to keep all your tracks instead of just one audio and one video track the -map 0 flag is needed.

Title: PowerShell script ffmpeg

Body:
Being the good Windows systems admin that I am, I'm finally getting around to learning PowerShell. With that being said, I have no idea what I'm doing (surprise, surprise).

I thought that it would be a good learning experience for me to play around with PowerShell at home, far away from my production environment. Recently, I've begun using FFMPEG to convert all of my .mkv files to .mp4 so I could have better playback support to my PlayStation 3 via Plex, and thought that this would be a good learning experience.

The command I've been running is as follows:

ffmpeg -i OldVideoName.mkv -vcodec copy -acodec ac3 OldVideoName.mp4

What I want is have a PowerShell script that will run once, scanning a folder and all sub-folders for .mkv files (Get-ChildItem ".*.mkv"), transcode them to .mp4 via the above command, and place them in the same location as the .mkv with the same naming scheme.

Example of running the script with D:\Videos as the target directory:

D:\Videos\home_dvr\movies\video1.mkv --> D:\Videos\home_dvr\video1.mp4
D:\Videos\home_dvr\tv\video2.mkv --> D:\Videos\home_dvr\tv\video2.mp4

As you can guess, I can't figure it out for the life of me. Here's the latest attempt before giving up.

    $oldvid = Get-ChildItem .\*.mkv -Recurse
    $newvid = $oldvid.Name.split(‘.’)[0]; ForEach-Object {
            .\ffmpeg.exe -i $oldvid -y -vcodec copy -acodec ac3 $newvid".mp4”
    }

Any help would be appreciated!

Body:
It seems as if with the current version of powershell the behaviour has changed a bit. The Answer suggested by Keith Hill doesn't work anymore, it needs to have the .FullName removed in order to work with PS 5.1 (Build 14393).
So the current answer would be:

$oldvids = Get-ChildItem -Filter "*.mkv" -Recurse
foreach ($oldvid in $oldvids) {
    $newvid = [io.path]::ChangeExtension($oldvid, '.mp4')
    .\ffmpeg.exe -i $oldvid-y -map 0 -c:v copy -c:a ac3 $newvid
}

Also -c:v -c:a are now preferred over -vcodec and -acodec.
If you want to keep all your tracks instead of just one audio and one video track the -map 0 flag is needed.


问:
Free program to grep unicode text files in Windows?
I have a collection of unicode text files (exported from regedit) and I'd like to pull out all the lines with a certain text on them.

I've tried Grep for Windows and findstr but both can't seem to handle the unicode encoding.  My results are empty, but when I use the -v option (show non-matching lines), the output shows a NUL between each character.

Are there any free options to perform a simple grep on Unicode files in Windows?

答: If you have notepad++, you can use "Find in Files..." option to search unicode files. </p>

ContentLicense: CC BY-SA 2.5


问:
Using the Gson library to parse unknown data dynamically
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

```<code>{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}
</code>```

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

答:
From Gson Documentation </p>

```<code> Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType);
</code>```

Body:
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

Body:
From Gson Documentation

 Type mapType = new TypeToken<Map<Integer, Result> >() {}.getType(); // define generic type
Map<Integer, Result> result= gson.fromJson(new InputStreamReader(source), mapType);


问:
Transform JSX to JS using babel
I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.

```<code>npm install --save-dev babel-plugin-transform-react-jsx
</code>```

Created a file called .babelrc in the application root directory.

```<code>{
   "plugins": ["transform-react-jsx"]
}
</code>```

My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens.
Can any one point out what I'm doing wrong ?

答:
if you are only using babel to transform jsx to js, this is what you need :

installation

install babel-cli as global (optional) sudo npm install -g babel-cli

install babel-preset-es2015 (optional. if your code using es6 standard) npm install babel-preset-es2015

install babel-preset-react (required)

configuration

in your root of project, add this file .babelrc and write this to it

```<code>{
  "presets": ["es2015", "react"]
}
</code>```

or

```<code>{
  "presets": ["react"]
}
</code>```

run

```<code>babel source_dir -d target_dir
</code>```

Title: Transform JSX to JS using babel

Body:
I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.

npm install --save-dev babel-plugin-transform-react-jsx

Created a file called .babelrc in the application root directory.

{
   "plugins": ["transform-react-jsx"]
}

My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens.
Can any one point out what I'm doing wrong ?

Body:
if you are only using babel to transform jsx to js, this is what you need :

installation

install babel-cli as global (optional) sudo npm install -g babel-cli

install babel-preset-es2015 (optional. if your code using es6 standard) npm install babel-preset-es2015

install babel-preset-react (required)

configuration

in your root of project, add this file .babelrc and write this to it

{
  "presets": ["es2015", "react"]
}

or

{
  "presets": ["react"]
}

run

babel source_dir -d target_dir

ContentLicense: CC BY-SA 4.0


问:
How to group factors by product and display if a product has more than one factor-pair?
Using a predefined array of numbers, how can I use PHP to generate a multi-dimensional array which groups all factor-pairs by their product?

Input array:

```<code>$array = array(1,2,3,4,5,6,7,8);
</code>```

I want to display all factor-pairs for each product group that have more than one factor-pair.

In a case where there are no product groups that have more than one factor-pair, No pairs Found should be displayed.

Given the above input, this is my expected result:

```<code>1 6 and 2 3  // product group = 6
1 8 and 2 4  // product group = 8
2 6 and 3 4  // product group = 12
3 8 and 4 6  // product group = 24
</code>```

*note as the input array increases in size, the output will display more than two factor-pairs per group.

This is my code from C++:

```<code> void findPairs(int arr[], int n)
{
    bool found = false;
    unordered_map<int, pair < int, int > > H;
    for (int i=0; i<n; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            // If product of pair is not in hash table,
            // then store it
            int prod = arr[i]*arr[j];
            if (H.find(prod) == H.end())
                H[prod] = make_pair(i,j);

            // If product of pair is also available in
            // then print current and previous pair
            else
            {
                pair<int,int> pp = H[prod];
                cout << arr[pp.first] << " " << arr[pp.second]
                     << " and " << arr[i]<<" "<<arr[j]<<endl;
                found = true;
            }
        }
    }
    // If no pair find then print not found
    if (found == false)
        cout << "No pairs Found" << endl;
}
</code>```

答:
The simplest solution will work fine with a small array like your example but will use a lot of memory for bigger inputs. Basically, first calculate all products by using a nested loop. For every product, create a list of inputs that generate the product. Mind you that there might be more than 2 ways to get a certain result, so you might get an output like 1 12 and 2 6 and 3 4 for bigger lists.

For an input of size N, you need to store ((N -1) * N) / 2 tuples in memory, so that's something to keep in mind.

```<code>$input = [1, 2, 3, 4, 5, 6, 7, 8];

$products = [];

foreach ($input as $index1 => $value1) {
    // Assuming you only want unique combinations, only combine this value with the other values coming after it
    for ($index2 = $index1 + 1; $index2 < count($input); $index2++) {
        $value2 = $input[$index2];
        $product = $value1 * $value2;

        // Make sure there is an entry in the $products array for adding this input to
        if (!isset($products[$product])) {
            $products[$product] = [];
        }

        // Add this input (formatted) to the list of possible inputs resulting in this product
        $products[$product][] = sprintf('%d %d', $value1, $value2);
    }
}

// Print all inputs resulting in the same products, if there are more than 1 way to produce the same output
foreach ($products as $inputs) {
    if (count($inputs) > 1) {
        echo implode(' and ', $inputs), PHP_EOL;
    }
}
</code>```

Will output

```<code>1 6 and 2 3
1 8 and 2 4
2 6 and 3 4
3 8 and 4 6
</code>```

Body:
Using a predefined array of numbers, how can I use PHP to generate a multi-dimensional array which groups all factor-pairs by their product?

Input array:

$array = array(1,2,3,4,5,6,7,8);

I want to display all factor-pairs for each product group that have more than one factor-pair.

In a case where there are no product groups that have more than one factor-pair, No pairs Found should be displayed.

Given the above input, this is my expected result:

1 6 and 2 3  // product group = 6
1 8 and 2 4  // product group = 8
2 6 and 3 4  // product group = 12
3 8 and 4 6  // product group = 24

*note as the input array increases in size, the output will display more than two factor-pairs per group.

This is my code from C++:

 void findPairs(int arr[], int n)
{
    bool found = false;
    unordered_map<int, pair < int, int > > H;
    for (int i=0; i<n; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            // If product of pair is not in hash table,
            // then store it
            int prod = arr[i]*arr[j];
            if (H.find(prod) == H.end())
                H[prod] = make_pair(i,j);

            // If product of pair is also available in
            // then print current and previous pair
            else
            {
                pair<int,int> pp = H[prod];
                cout << arr[pp.first] << " " << arr[pp.second]
                     << " and " << arr[i]<<" "<<arr[j]<<endl;
                found = true;
            }
        }
    }
    // If no pair find then print not found
    if (found == false)
        cout << "No pairs Found" << endl;
}

Body:
The simplest solution will work fine with a small array like your example but will use a lot of memory for bigger inputs. Basically, first calculate all products by using a nested loop. For every product, create a list of inputs that generate the product. Mind you that there might be more than 2 ways to get a certain result, so you might get an output like 1 12 and 2 6 and 3 4 for bigger lists.

For an input of size N, you need to store ((N -1) * N) / 2 tuples in memory, so that's something to keep in mind.

$input = [1, 2, 3, 4, 5, 6, 7, 8];

$products = [];

foreach ($input as $index1 => $value1) {
    // Assuming you only want unique combinations, only combine this value with the other values coming after it
    for ($index2 = $index1 + 1; $index2 < count($input); $index2++) {
        $value2 = $input[$index2];
        $product = $value1 * $value2;

        // Make sure there is an entry in the $products array for adding this input to
        if (!isset($products[$product])) {
            $products[$product] = [];
        }

        // Add this input (formatted) to the list of possible inputs resulting in this product
        $products[$product][] = sprintf('%d %d', $value1, $value2);
    }
}

// Print all inputs resulting in the same products, if there are more than 1 way to produce the same output
foreach ($products as $inputs) {
    if (count($inputs) > 1) {
        echo implode(' and ', $inputs), PHP_EOL;
    }
}

Will output

1 6 and 2 3
1 8 and 2 4
2 6 and 3 4
3 8 and 4 6


问:
How to send a notification from php to android app on a specific time (schedule time)?
notification on schedule time

i'm trying to send a notification from php to android app. In php i create a notification and send it to app that is working perfectly.

Now i want to send the notification on specific time. but i have no idea how to do that. this notification is send threw jar file (basically it is pick up from database and send to the GSM). But really i have no idea what to do in it.

Someone help on this issue ?

答:
You have to use Cron tasks for execution php script at specific time.

Read: How to set Cron

UPD

You can try to use php Event::addTimer but I`m not sure it will work good if you have a lot of events.


问:
Spring mongo data repository findAll() return empty?
I'm a newbie in Spring Framework. I'm trying to create a small REST API by using Spring Rest with MongoDB.
And when I create the repository to get data from MongoDb, the findAll() function always return an empty list. Here is my repository:

```<code>   @RepositoryRestResource(collectionResourceRel = "meal", path = "meal")
   public interface MealRepository extends MongoRepository<Meal, Integer> {

       @Override
       public List<Meal> findAll();

       @Override
       public Meal findOne(Integer id);
   }
</code>```

And Controller:

```<code>@RestController
public class MealApiController {

    @Autowired
    MealRepository mMealRepository;

    @RequestMapping(value = "/meal/detail", method = RequestMethod.GET)
    public @ResponseBody Meal mealDetailGet(@RequestParam(value = "id", required = true) Integer id) {
        Meal meal = mMealRepository.findOne(id);
        return meal;
    }

    @RequestMapping(value = "/meal/all", method = RequestMethod.GET)
    public @ResponseBody List<Meal> getAllMeal() {
        return mMealRepository.findAll();
    }

    @RequestMapping(value = "/meal/list", method = RequestMethod.GET)
    public @ResponseBody List<Meal> mealListGet(@RequestParam(value = "menu_id", required = true) Integer menuId) {
        List<Meal> response = mMealRepository.findByMenuId(menuId);
        return response;
    }

}
</code>```

Meal model:

```<code>@Document(collection = "meal_items")
public class Meal {

    @Id
    @JsonProperty("_id")
    private int id;

    @JsonProperty("menu_id")
    private int menuId;

    @JsonProperty("name")
    private String name = null;

    @JsonProperty("image")
    private List<String> image = new ArrayList<String>();

    @JsonProperty("material")
    private List<String> material = new ArrayList<String>();

    @JsonProperty("guide")
    private List<String> guide = new ArrayList<String>();

    public Meal id(int id) {
        this.id = id;
        return this;
    }

    /**
     * Unique identifier representing a specific Meal.
     *
     * @return id
     **/
    public int getId() {
        return id;
    }

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

    public Meal menuId(int menuId) {
        this.menuId = menuId;
        return this;
    }

    /**
     * Unique identifier representing a specific Menu containing the meal.
     *
     * @return menuId
     **/
    public int getMenuId() {
        return menuId;
    }

    public void setMenuId(int menuId) {
        this.menuId = menuId;
    }

    public Meal name(String name) {
        this.name = name;
        return this;
    }

    /**
     * Display name of meal.
     *
     * @return name
     **/
    public String getName() {
        return name;
    }

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

    public Meal image(List<String> image) {
        this.image = image;
        return this;
    }

    public Meal addImageItem(String imageItem) {
        this.image.add(imageItem);
        return this;
    }

    /**
     * Image URL representing the meal.
     *
     * @return image
     **/
    public List<String> getImage() {
        return image;
    }

    public void setImage(List<String> image) {
        this.image = image;
    }

    public Meal material(List<String> material) {
        this.material = material;
        return this;
    }

    public Meal addMaterialItem(String materialItem) {
        this.material.add(materialItem);
        return this;
    }

    /**
     * List material used to cook the meal.
     *
     * @return material
     **/
    public List<String> getMaterial() {
        return material;
    }

    public void setMaterial(List<String> material) {
        this.material = material;
    }

    public Meal guide(List<String> guide) {
        this.guide = guide;
        return this;
    }

    public Meal addGuideItem(String guideItem) {
        this.guide.add(guideItem);
        return this;
    }

    /**
     * Steps cooking the meal.
     *
     * @return guide
     **/
    public List<String> getGuide() {
        return guide;
    }

    public void setGuide(List<String> guide) {
        this.guide = guide;
    }

    @Override
    public boolean equals(java.lang.Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Meal meal = (Meal) o;
        return Objects.equals(this.id, meal.id) && Objects.equals(this.menuId, meal.menuId)
                && Objects.equals(this.name, meal.name) && Objects.equals(this.image, meal.image)
                && Objects.equals(this.material, meal.material) && Objects.equals(this.guide, meal.guide);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, menuId, name, image, material, guide);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("class Meal {\n");

        sb.append("    id: ").append(toIndentedString(id)).append("\n");
        sb.append("    menuId: ").append(toIndentedString(menuId)).append("\n");
        sb.append("    name: ").append(toIndentedString(name)).append("\n");
        sb.append("    image: ").append(toIndentedString(image)).append("\n");
        sb.append("    material: ").append(toIndentedString(material)).append("\n");
        sb.append("    guide: ").append(toIndentedString(guide)).append("\n");
        sb.append("}");
        return sb.toString();
    }

    /**
     * Convert the given object to string with each line indented by 4 spaces
     * (except the first line).
     */
    private String toIndentedString(java.lang.Object o) {
        if (o == null) {
            return "null";
        }
        return o.toString().replace("\n", "\n    ");
    }
}
</code>```

答:
A couple of things.

Firstly, this behaviour is not reproducible. It works fine.

Secondly, you don't need a separate controller(@RestController) class to expose your REST endpoints(unless needed for specific reasons). When you use spring-data-rest(@RepositoryRestResource), spring exposes endpoints for you, including endpoints for custom querymethods like findByMenuId.

In your example, just delete the controller class and restart the application. And try to hit http://host:port/meal from the browser, it will display all the possible options as links, which is self-explanatory.

Body:
I'm a newbie in Spring Framework. I'm trying to create a small REST API by using Spring Rest with MongoDB.
And when I create the repository to get data from MongoDb, the findAll() function always return an empty list. Here is my repository:

   @RepositoryRestResource(collectionResourceRel = "meal", path = "meal")
   public interface MealRepository extends MongoRepository<Meal, Integer> {

       @Override
       public List<Meal> findAll();

       @Override
       public Meal findOne(Integer id);
   }

And Controller:

@RestController
public class MealApiController {

    @Autowired
    MealRepository mMealRepository;

    @RequestMapping(value = "/meal/detail", method = RequestMethod.GET)
    public @ResponseBody Meal mealDetailGet(@RequestParam(value = "id", required = true) Integer id) {
        Meal meal = mMealRepository.findOne(id);
        return meal;
    }

    @RequestMapping(value = "/meal/all", method = RequestMethod.GET)
    public @ResponseBody List<Meal> getAllMeal() {
        return mMealRepository.findAll();
    }

    @RequestMapping(value = "/meal/list", method = RequestMethod.GET)
    public @ResponseBody List<Meal> mealListGet(@RequestParam(value = "menu_id", required = true) Integer menuId) {
        List<Meal> response = mMealRepository.findByMenuId(menuId);
        return response;
    }

}

Meal model:

@Document(collection = "meal_items")
public class Meal {

    @Id
    @JsonProperty("_id")
    private int id;

    @JsonProperty("menu_id")
    private int menuId;

    @JsonProperty("name")
    private String name = null;

    @JsonProperty("image")
    private List<String> image = new ArrayList<String>();

    @JsonProperty("material")
    private List<String> material = new ArrayList<String>();

    @JsonProperty("guide")
    private List<String> guide = new ArrayList<String>();

    public Meal id(int id) {
        this.id = id;
        return this;
    }

    /**
     * Unique identifier representing a specific Meal.
     *
     * @return id
     **/
    public int getId() {
        return id;
    }

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

    public Meal menuId(int menuId) {
        this.menuId = menuId;
        return this;
    }

    /**
     * Unique identifier representing a specific Menu containing the meal.
     *
     * @return menuId
     **/
    public int getMenuId() {
        return menuId;
    }

    public void setMenuId(int menuId) {
        this.menuId = menuId;
    }

    public Meal name(String name) {
        this.name = name;
        return this;
    }

    /**
     * Display name of meal.
     *
     * @return name
     **/
    public String getName() {
        return name;
    }

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

    public Meal image(List<String> image) {
        this.image = image;
        return this;
    }

    public Meal addImageItem(String imageItem) {
        this.image.add(imageItem);
        return this;
    }

    /**
     * Image URL representing the meal.
     *
     * @return image
     **/
    public List<String> getImage() {
        return image;
    }

    public void setImage(List<String> image) {
        this.image = image;
    }

    public Meal material(List<String> material) {
        this.material = material;
        return this;
    }

    public Meal addMaterialItem(String materialItem) {
        this.material.add(materialItem);
        return this;
    }

    /**
     * List material used to cook the meal.
     *
     * @return material
     **/
    public List<String> getMaterial() {
        return material;
    }

    public void setMaterial(List<String> material) {
        this.material = material;
    }

    public Meal guide(List<String> guide) {
        this.guide = guide;
        return this;
    }

    public Meal addGuideItem(String guideItem) {
        this.guide.add(guideItem);
        return this;
    }

    /**
     * Steps cooking the meal.
     *
     * @return guide
     **/
    public List<String> getGuide() {
        return guide;
    }

    public void setGuide(List<String> guide) {
        this.guide = guide;
    }

    @Override
    public boolean equals(java.lang.Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Meal meal = (Meal) o;
        return Objects.equals(this.id, meal.id) && Objects.equals(this.menuId, meal.menuId)
                && Objects.equals(this.name, meal.name) && Objects.equals(this.image, meal.image)
                && Objects.equals(this.material, meal.material) && Objects.equals(this.guide, meal.guide);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, menuId, name, image, material, guide);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("class Meal {\n");

        sb.append("    id: ").append(toIndentedString(id)).append("\n");
        sb.append("    menuId: ").append(toIndentedString(menuId)).append("\n");
        sb.append("    name: ").append(toIndentedString(name)).append("\n");
        sb.append("    image: ").append(toIndentedString(image)).append("\n");
        sb.append("    material: ").append(toIndentedString(material)).append("\n");
        sb.append("    guide: ").append(toIndentedString(guide)).append("\n");
        sb.append("}");
        return sb.toString();
    }

    /**
     * Convert the given object to string with each line indented by 4 spaces
     * (except the first line).
     */
    private String toIndentedString(java.lang.Object o) {
        if (o == null) {
            return "null";
        }
        return o.toString().replace("\n", "\n    ");
    }
}


问:
prevent media scan, set permission or lock the folder and file in android
In my app, me downloading different image and saving inside sdcard under a folder. That file is later used in my app.

What i need is, make this folder only visible to my app. I mean the images should not be available in Android Gallery and other.

Me also saving the sqllite file inside this folder. I also want to restrict any other access  to this sqllite file.

Is there anyway to set permission like anything for folder and file, so that it can only available to my app?
Is there anyway to lock a folder or a file to some specific app?

Thanks in advance.

答:
Finlay i found the answer for this

I done it without setting permission, but we can Hide out files from the Media Scanner

Include an empty file named .nomedia in your external files directory (note the dot prefix in the filename). This will prevent Android's media scanner from reading your media files and including them in apps like Gallery or Music.


问:
Ansible: use both lists and their contents as variable values
I have key - value pairs association in the form of:

```<code>- mykey1:
    myvalues1: ['a', 'b', 'c']
- mykey2:
    myvalues2: ['d', 'e']
- mykey3:
    myvalues3: ['f']
</code>```

I know that using the with_dict construct I can iterate over both keys and  values (which are lists).
My question is how can I have a loop that iterates over the list's (values) elements?

The output i would like to be able to achieve is:

```<code>a', 'b', 'c', 'd', 'e', 'f'
</code>```

The problem is that I need to maintain the above associations.
Is there a way to avoid duplicating list declarations?

答:
I'm not quite sure if it is possible with dynamic keys. But assuming the following vars file without the 1,2 and 3:

```<code>rootitem:
  - mykey:
      myvalues: ['a', 'b', 'c']
  - mykey:
      myvalues: ['d', 'e']
  - mykey:
      myvalues: ['f']
</code>```

It is possible using "with_subelements" with the following example:

```<code>- name: iterate over list
  debug:
    msg: "the current item is{{ item.0 }} and all subitems are {{ item.1 }}"
  with_subelements:
    - "{{ rootitem }}"
    - mykey.myvalues
</code>```

This results in 6 iterations one for each of "a,b,c,d,e,f".

Body:
I have key - value pairs association in the form of:

- mykey1:
    myvalues1: ['a', 'b', 'c']
- mykey2:
    myvalues2: ['d', 'e']
- mykey3:
    myvalues3: ['f']

I know that using the with_dict construct I can iterate over both keys and  values (which are lists).
My question is how can I have a loop that iterates over the list's (values) elements?

The output i would like to be able to achieve is:

a', 'b', 'c', 'd', 'e', 'f'

The problem is that I need to maintain the above associations.
Is there a way to avoid duplicating list declarations?

Body:
I'm not quite sure if it is possible with dynamic keys. But assuming the following vars file without the 1,2 and 3:

rootitem:
  - mykey:
      myvalues: ['a', 'b', 'c']
  - mykey:
      myvalues: ['d', 'e']
  - mykey:
      myvalues: ['f']

It is possible using "with_subelements" with the following example:

- name: iterate over list
  debug:
    msg: "the current item is{{ item.0 }} and all subitems are {{ item.1 }}"
  with_subelements:
    - "{{ rootitem }}"
    - mykey.myvalues

This results in 6 iterations one for each of "a,b,c,d,e,f".


问:
How to attach Mpdf output as email attachment with Codeigniter?
In my controller generating pdf layout and then attaching it as Pdf and with a custom filename. Here is the code

```<code>$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content):
$this->email->send();
</code>```

How to attach the file with email.

答:
Try below code

```<code>$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content, 'attachment', $filename, 'application/pdf');
$this->email->send();
</code>```

For more please check Codeigniter Email Class documentation

Body:
In my controller generating pdf layout and then attaching it as Pdf and with a custom filename. Here is the code

$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content):
$this->email->send();

How to attach the file with email.

Body:
Try below code

$this->load->library('mpdf');
$mpdf = new Mpdf('L', 'A4', 0, 'Trebuchet MS', 6, 6, 9, 9, 3, 3, 'L');
ob_start();
echo $this->generateFoodReport($inspectionId);
$html = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML(utf8_encode($html));
$content = chunk_split(base64_encode($mpdf->Output('', 'S')));
$filename = "inspection-report.pdf";

$this->load->library('email');
$this->email->set_mailtype("html");
$this->email->set_newline("\r\n");
$this->email->from($fromMail, $fromName);
$this->email->to($mailTo);
$this->email->subject($subject);
$this->email->attach($content, 'attachment', $filename, 'application/pdf');
$this->email->send();

For more please check Codeigniter Email Class documentation


问:
Page getting stuck on updating image
I have a problem with my web page which stops updating my image automatically. The page consists of a key pad. When a 4 digit code is entered the code is sent to alarm.php by ajax script. Alarm.php updated a Db and returns some values for alarmSet and alarm Triggered (0,0 alarm off, 1,0 alarm set, 1,1 alarm triggered). My index page then displays an icon depending on the returned values to show the state of the alarm. The page also has an auto update to check to Db and update the icons if the alarm state changes. All this works great. The console is showing the returned values and the image that is to be displayed and the page response as expected.
But if I leave the page for about 5 min the images stop updating. I can still enter a code, the Db is still updated and the console is still showing returned value eg 0,0 greenAlarm.jpg but the green icon is not displayed. It seems the page has locked on the display side. If I refresh the page all is ok again. I cant see what is causing this. Hope this make sense.

index JS script below which is in the Header part of the page

```
</div>
</div>
</p>

<p>I also have gauges on the page the this is auto updated which works but not sure if this is locking up at the same time. I expect it is. This script is below and at the bottom of the main page</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script>
  setInterval(function(){
   $.ajax({
    url:"data.php",
    dataType:"json",
    success: function(data){
    g1.refresh(data.Gwater);
    g2.refresh(data.Gsolar);
    g3.refresh(data.Grayburn);
    }
   });
  }, 3000)
  var g1 = new JustGage({
  id: "Gwater",
  value: 0,
  min: 0,
  max: 75,
  label: "Hot Water",
  labelFontColor: "#00B1FF",
  valueFontColor: "#00B1FF",
  pointer:1
   });
    var g2 = new JustGage({
  id: "Gsolar",
  value: 0,
  min: 0,
  max: 100,
  label: "Solar Temp",
  labelFontColor: "#00B1FF",
  valueFontColor: "#00B1FF",
  pointer:1
   });
   var g3 = new JustGage({
  id: "Grayburn",
  value: 0,
  min: 0,
  max: 100,
  label: "Rayburn Temp",
  labelFontColor: "#00B1FF",
  valueFontColor: "#00B1FF",
  pointer:1
   });
</script></code>```

I can upload all the code if needed.

Any help would be great thank you

答:
Got it working. It was the server getting overloaded with all the request and the page not updating. Below is the new code with a 10 second interval. I have taken the gauges out as this caused more problems. Tried using setTimeOut but could not get it to work properly. Anyway below code now works. Will have to design my own gauges now.

```

Title: Page getting stuck on updating image

Body:
I have a problem with my web page which stops updating my image automatically. The page consists of a key pad. When a 4 digit code is entered the code is sent to alarm.php by ajax script. Alarm.php updated a Db and returns some values for alarmSet and alarm Triggered (0,0 alarm off, 1,0 alarm set, 1,1 alarm triggered). My index page then displays an icon depending on the returned values to show the state of the alarm. The page also has an auto update to check to Db and update the icons if the alarm state changes. All this works great. The console is showing the returned values and the image that is to be displayed and the page response as expected.
But if I leave the page for about 5 min the images stop updating. I can still enter a code, the Db is still updated and the console is still showing returned value eg 0,0 greenAlarm.jpg but the green icon is not displayed. It seems the page has locked on the display side. If I refresh the page all is ok again. I cant see what is causing this. Hope this make sense.

index JS script below which is in the Header part of the page

I also have gauges on the page the this is auto updated which works but not sure if this is locking up at the same time. I expect it is. This script is below and at the bottom of the main page

I can upload all the code if needed.

Any help would be great thank you

Body:
Got it working. It was the server getting overloaded with all the request and the page not updating. Below is the new code with a 10 second interval. I have taken the gauges out as this caused more problems. Tried using setTimeOut but could not get it to work properly. Anyway below code now works. Will have to design my own gauges now.

<script>
 var gaugeData = function(){
  var response = 0;
   $.ajax({
   url:"data.php",
   dataType:"json",
   success: function(data){
    response = (data);
    console.log(response);
    if (response.id == 1){
    display(response);// send the data outside this function to be worked with
    } else{
     setTimeout (gaugeData, 5000);
    }
    }
   });
  }
  function display(data){
  console.log(data.AlarmSet);
  var thisImg = 0;
  if (data.AlarmSet == 0){
   thisImg = "greenAlarm.jpg"; // alarm off
  }
  if (data.AlarmSet == 1){
   thisImg = "blueAlarm.jpg"; // alarm on
  }
  $("#image").attr("src", thisImg);
  $("#Gwater").html(data.Gwater + '&deg;C');
  $("#Gsolar").html(data.Gsolar + '&deg;C');
  $("#Grayburn").html(data.Grayburn + '&deg;C');
  }
  setInterval (gaugeData, 10000);
</script>


问:
Not able to load data into hive table
While loading data into Hive tables, i'm Getting following error:

```<code>"Loading data to table test.temp1
Moved: 'hdfs://mdckd.kk.hyy.com:8020/apps/hive/warehouse/test.db/temp1/000000_0' to trash at: hdfs://mdckd.kk.hyy.com:8020/user/lams/.Trash/Current
Table test.temp1 stats: [numFiles=1014, numRows=0, totalSize=50113, rawDataSize=0]"
</code>```

Looks like my data is going to trash but i don't understand why. Please help. Following is my table definition and the query i am using:

```<code>      CREATE TABLE `temp1`(
      `col1` int,
      `col2` int,
      `col3` int,
      `col4` int,
      `col5` int,
      `col6` int,
      `col7` int,
      `col8` int,
      `col9` int,
      `col10` int)
      ROW FORMAT SERDE
       'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
       STORED AS INPUTFORMAT
       'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
        OUTPUTFORMAT
       'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
       LOCATION
       'hdfs://mdckd.kk.hyy.com:8020/apps/hive/warehouse/test.db/temp1'
       TBLPROPERTIES (
       'COLUMN_STATS_ACCURATE'='true',
       'numFiles'='548',
       'numRows'='547',
       'rawDataSize'='131280',
       'totalSize'='483505',
       'transient_lastDdlTime'='1490261019')

    INSERT OVERWRITE TABLE temp1
    select * from
     (
       select * from tab1
       union all
       select * from tab2
       union all
       select * from tab3
       union all
       select * from tab4
       union all
       select * from tab5
    )p;
</code>```

答:
The data that is already in your table is going to trash, because this exactly what OVERWRITE means.

If you want to append and not truncate, use INSERT INTO TABLE (or INSERT INTO in newer versions).

P.s.

You don't need the outer query.

```<code>insert into table temp1

            select * from tab1
union all   select * from tab2
union all   select * from tab3
union all   select * from tab4
union all   select * from tab5
;
</code>```

Title: Not able to load data into hive table

Body:
While loading data into Hive tables, i'm Getting following error:

"Loading data to table test.temp1
Moved: 'hdfs://mdckd.kk.hyy.com:8020/apps/hive/warehouse/test.db/temp1/000000_0' to trash at: hdfs://mdckd.kk.hyy.com:8020/user/lams/.Trash/Current
Table test.temp1 stats: [numFiles=1014, numRows=0, totalSize=50113, rawDataSize=0]"

Looks like my data is going to trash but i don't understand why. Please help. Following is my table definition and the query i am using:

      CREATE TABLE `temp1`(
      `col1` int,
      `col2` int,
      `col3` int,
      `col4` int,
      `col5` int,
      `col6` int,
      `col7` int,
      `col8` int,
      `col9` int,
      `col10` int)
      ROW FORMAT SERDE
       'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
       STORED AS INPUTFORMAT
       'org.apache.hadoop.hive.ql.io.orc.OrcInputFormat'
        OUTPUTFORMAT
       'org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat'
       LOCATION
       'hdfs://mdckd.kk.hyy.com:8020/apps/hive/warehouse/test.db/temp1'
       TBLPROPERTIES (
       'COLUMN_STATS_ACCURATE'='true',
       'numFiles'='548',
       'numRows'='547',
       'rawDataSize'='131280',
       'totalSize'='483505',
       'transient_lastDdlTime'='1490261019')

    INSERT OVERWRITE TABLE temp1
    select * from
     (
       select * from tab1
       union all
       select * from tab2
       union all
       select * from tab3
       union all
       select * from tab4
       union all
       select * from tab5
    )p;

Body:
The data that is already in your table is going to trash, because this exactly what OVERWRITE means.

If you want to append and not truncate, use INSERT INTO TABLE (or INSERT INTO in newer versions).

P.s.

You don't need the outer query.

insert into table temp1

            select * from tab1
union all   select * from tab2
union all   select * from tab3
union all   select * from tab4
union all   select * from tab5
;


问:
ionic2:how can I use transfer to upload multiple files at the same time?
I want to upload several pictures to server at the same time,the native plugin provide transfer,but this plugin can only upload a file at the same time.I don't want to call transfer.upload in while or for.
What method can upload multiple files at the same time? Thank you very much for your reply!!!  http://ionicframework.com/docs/v2/native/transfer/

答:
Even though the example is for angularjs/ionic..,give it a try

Go through this tutorial.,you will get a some idea to proceed further.
https://www.thepolyglotdeveloper.com/2015/01/upload-files-remote-server-using-ionic-framework/


问:
Rebooting a server after Windows application is installed using Python
I am developing some Python (version 3.6.1) code to install an application in Windows 7. The code used is this:

```<code>winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /l C:\PowerBuild\TUmsi.log"'
output = subprocess.check_call(winCMD, shell = True)
</code>```

The application is installed successfully. The problem is that it always requires a reboot after it is finished (a popup with a message "You must restart your system for the configuration changes made to  to take effect. Click Yes to restart now or No if you plan to restart later.).

I tried to insert parameter "/forcerestart" (source here) in the installation command but it still stops to request the reboot:

```<code>def installApp():
    winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /forcerestart /l C:\PowerBuild\TUmsi.log"'
    output = subprocess.check_call(winCMD, shell = True)
</code>```

Another attempt was to create a following command like this one below, although since the previous command is not finished yet (as per my understanding) I realized it will never be called:

```<code>rebootSystem = 'shutdown -t 0 /r /f'
subprocess.Popen(rebootSystem, stdout=subprocess.PIPE, shell=True)
</code>```

Does anyone had such an issue and could solve it?

答:
As an ugly workaround, if you're not time-critical but you want to emphasise the "automatic" aspect, why not

run the installCMD in a thread

wait sufficiently long to be sure that the command has completed

perform the shutdown

like this:

```<code>import threading,time
def installApp():
    winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /l C:\PowerBuild\TUmsi.log"'
    output = subprocess.check_call(winCMD, shell = True)

t = threading.Thread(target=installApp)
t.start()
time.sleep(1800)  # half-hour should be enough
rebootSystem = 'shutdown -t 0 /r /f'
subprocess.Popen(rebootSystem, stdout=subprocess.PIPE, shell=True)
</code>```

Another (safer) way would be to find out which file is created last in the installation, and monitor for its existence in a loop like this:

```<code>while not os.path.isfile("somefile"):
     time.sleep(60)
time.sleep(60)  # another minute for safety
# perform the reboot
</code>```

To be clean, you'd have to use subprocess.Popen for the installation process, export it as global and call terminate() on it in the main process, but since you're calling a shutdown that's not necessary.

(to be clean, we wouldn't have to do that hack in the first place)

Body:
I am developing some Python (version 3.6.1) code to install an application in Windows 7. The code used is this:

winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /l C:\PowerBuild\TUmsi.log"'
output = subprocess.check_call(winCMD, shell = True)

The application is installed successfully. The problem is that it always requires a reboot after it is finished (a popup with a message "You must restart your system for the configuration changes made to  to take effect. Click Yes to restart now or No if you plan to restart later.).

I tried to insert parameter "/forcerestart" (source here) in the installation command but it still stops to request the reboot:

def installApp():
    winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /forcerestart /l C:\PowerBuild\TUmsi.log"'
    output = subprocess.check_call(winCMD, shell = True)

Another attempt was to create a following command like this one below, although since the previous command is not finished yet (as per my understanding) I realized it will never be called:

rebootSystem = 'shutdown -t 0 /r /f'
subprocess.Popen(rebootSystem, stdout=subprocess.PIPE, shell=True)

Does anyone had such an issue and could solve it?

Body:
As an ugly workaround, if you're not time-critical but you want to emphasise the "automatic" aspect, why not

run the installCMD in a thread

wait sufficiently long to be sure that the command has completed

perform the shutdown

like this:

import threading,time
def installApp():
    winCMD = r'"C:\PowerBuild\setup.exe" /v"/qr /l C:\PowerBuild\TUmsi.log"'
    output = subprocess.check_call(winCMD, shell = True)

t = threading.Thread(target=installApp)
t.start()
time.sleep(1800)  # half-hour should be enough
rebootSystem = 'shutdown -t 0 /r /f'
subprocess.Popen(rebootSystem, stdout=subprocess.PIPE, shell=True)

Another (safer) way would be to find out which file is created last in the installation, and monitor for its existence in a loop like this:

while not os.path.isfile("somefile"):
     time.sleep(60)
time.sleep(60)  # another minute for safety
# perform the reboot

To be clean, you'd have to use subprocess.Popen for the installation process, export it as global and call terminate() on it in the main process, but since you're calling a shutdown that's not necessary.

(to be clean, we wouldn't have to do that hack in the first place)


问:
reference & pointers confusing parts(declarations and their types)
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

```<code>int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};
</code>```

What will be the types of the following expressions?

```<code>&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values
</code>```

I have no idea what their types exactly are, but I tried it myself.

```<code>&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int
</code>```

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

```<code>a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;
</code>```

I'm not sure about my answers. Please help these confusing parts.

答:
First, a std::string is a complex object that contains a char array but it is definitely not a char array. And a std::vector<int> is also a complex object that contains an array of ints.

That means that for the first part some of your tries are wrong:

```<code>&(s.at(1)) : pointer to string               WRONG: pointer to char
values.at(0) : pointer to int                OK
&(values.at(0)) : pointer to pointer to int  OK
&values : pointer to pointer to int          WRONG: pointer to `vector<int>`
</code>```

For the second part, as a string is not a char array, you cannot initialize a pointer to string with a litteral char array

```<code>string *s = "hello";   WRONG syntax error
</code>```

You must first create a string and then create a pointer to it

```<code>string s = "hello";   OK std::string initialized from a const char *
string *ps = &s;      OK pointer to std::string
</code>```

c is wrong too int arr[] declares an array of int. You must write:

```<code>int *arr[] = { x };  OK array of 1 pointers initialized from x which is a pointer to int
</code>```

For e, int&z = *x; declares a reference to int initialized as a ref to a. To get a ref to a pointer, you must write:

```<code>int *&z = x;   OK ref to a pointer to int initialized as a ref to x
</code>```

Body:
I'm studying pointer and reference parts and having very hard time to study them.
I think I understand now some simple usage of reference and pointers in the function, but there is something I cannot totally understand.

Here are some variable declarations:

int a = 1;
float b = 2;
int* p = &a;
string s = "Hello";
vector<int*> values = {p};

What will be the types of the following expressions?

&a
&b
p
&p
&s
&(s.at(1))
values.at(0)
&(values.at(0))
&values

I have no idea what their types exactly are, but I tried it myself.

&a : pointer to int
&b : pointer float
 p : pointer to int
&p : pointer to pointer to int
&s : pointer to string
&(s.at(1)) : pointer to string
values.at(0) : pointer to int
&(values.at(0)) : pointer to pointer to int
&values : pointer to pointer to int

and one more problem >
write the following variable declarations:
a) A pointer to a string
b) A reference to a float
c) An array of pointers-to-ints.
d) A pointer to a pointer to bool
e) A reference to a pointer to an int

and my answers are:

a: string* s = "Hello"

b: float& f = g;

c: int n =1;
   int*x =&n;
   int arr[] = {*x};

d: bool y = true;
   bool* x = &y;
   bool** qq = &x;

e: int a = 1;
   int* x = &a;
   int& z = *x;

I'm not sure about my answers. Please help these confusing parts.

Body:
First, a std::string is a complex object that contains a char array but it is definitely not a char array. And a std::vector<int> is also a complex object that contains an array of ints.

That means that for the first part some of your tries are wrong:

&(s.at(1)) : pointer to string               WRONG: pointer to char
values.at(0) : pointer to int                OK
&(values.at(0)) : pointer to pointer to int  OK
&values : pointer to pointer to int          WRONG: pointer to `vector<int>`

For the second part, as a string is not a char array, you cannot initialize a pointer to string with a litteral char array

string *s = "hello";   WRONG syntax error

You must first create a string and then create a pointer to it

string s = "hello";   OK std::string initialized from a const char *
string *ps = &s;      OK pointer to std::string

c is wrong too int arr[] declares an array of int. You must write:

int *arr[] = { x };  OK array of 1 pointers initialized from x which is a pointer to int

For e, int&z = *x; declares a reference to int initialized as a ref to a. To get a ref to a pointer, you must write:

int *&z = x;   OK ref to a pointer to int initialized as a ref to x