问:
Android - tablayout with custom view tabs - drawable selector cannot be applied
I am trying to set up custom tabs in a tablayout using compile 'com.android.support:design:25.3.1' in gradle.

I want to use selectors so that when a tab is clicked it changes based on its state.

So I've tried the following unsuccessfully :

this is my activity xml:

```<code><ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@color/white"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill"
    style="@style/MyCustomTabLayout"
    />
</code>```

here is the style i use for the tabLayout:

```<code><style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
       <item name="tabIndicatorColor">@android:color/transparent</item>
   </style>
</code>```

which hides the underline.

here is one of my selectors for my home tab:

here is the custom view i have for each tab:

```<code><ImageView
    android:id="@+id/iv_imgview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    tools:src="@drawable/home_tab_selector"

    />

<TextView
    android:id="@+id/tv_tab_name"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="HOME"
    />
</code>```

and here is the portion of code that creates the tablayout:

```<code>for (int i = 0; i < NUM_OF_TABS; i++)
           tabLayout.addTab(tabLayout.newTab());

       adapter = new LandingPagerAdapter(getApplicationContext(),getSupportFragmentManager(), tabLayout.getTabCount());

       //Adding adapter to pager
       viewPager.setAdapter(adapter);

       tabLayout.addOnTabSelectedListener(this);
       tabLayout.setupWithViewPager(viewPager);

       // Iterate over all tabs and set the custom view
       for (int i = 0; i < tabLayout.getTabCount(); i++) {
           TabLayout.Tab tab = tabLayout.getTabAt(i);
           tab.setCustomView(adapter.getTabView(i));
       }

       tabLayout.getTabAt(0).select();
</code>```

and finally here is the getTabView method responsible for applying the selector and custom view:

```<code>public class LandingPagerAdapter extends FragmentStatePagerAdapter {

    private final Context context;
    //integer to count number of tabs
    int tabCount;
    private Fragment mCurrentFragment;

    private String[] tabTitles = new String[]{"Home", "tab2"};

    // configure tab icons
    int[] imageTabResId = {
            R.drawable.home_tab_selector,
            R.drawable.tab_two_selector,;

    //Constructor to the class
    public LandingPagerAdapter(Context context, FragmentManager fm, int tabCount) {
        super(fm);
        this.context = context;
        this.tabCount = tabCount;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                TabHomeContainerFragment tab1 = new TabHomeContainerFragment();
                return tab1;
            case 1:
                TabTwoContainerFragment tab2 = new TabTwoContainerFragment();; //Todo: these should all be containers
                return tab2;
            default:
                return null;
        }
    }

    //Overriden method getCount to get the number of tabs
    @Override
    public int getCount() {
        return tabCount;
    }

    public Fragment getCurrentFragment() {
        return mCurrentFragment;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        if (getCurrentFragment() != object) {
            mCurrentFragment = ((Fragment) object);
        }
        super.setPrimaryItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View v = LayoutInflater.from(context).inflate(R.layout.custom_landingpagetab, null);
        TextView tv = (TextView) v.findViewById(R.id.tv_tab_name);
        tv.setText(tabTitles[position]);
        ImageView img = (ImageView) v.findViewById(R.id.iv_imgview);
        img.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),imageTabResId[position]));
        return v;
    }

}
</code>```

Notice in getTabView i am setting the image resource to be the selector in the array in the class field.
but nothing happens on the device on api 24 i have been testing on.

答:
i ended up dropping the selector approach and just getting my customView from the tab. then i can change its view elements. i had a set of images in an array for selected and another for unselected.

then when the tabs switched i switch between the images based on tab position:

```<code>@Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
        TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

        iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId_selected[tab.getPosition()]));
        tv.setTextColor(ContextCompat.getColor(this, R.color.black));

    }
@Override
public void onTabUnselected(TabLayout.Tab tab) {
    ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
    TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

    iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId[tab.getPosition()]));
    tv.setTextColor(ContextCompat.getColor(this, R.color.tabs_default_text));

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
</code>```

Body:
I am trying to set up custom tabs in a tablayout using compile 'com.android.support:design:25.3.1' in gradle.

I want to use selectors so that when a tab is clicked it changes based on its state.

So I've tried the following unsuccessfully :

this is my activity xml:

<ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@color/white"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill"
    style="@style/MyCustomTabLayout"
    />

here is the style i use for the tabLayout:

which hides the underline.

here is one of my selectors for my home tab:

here is the custom view i have for each tab:

<ImageView
    android:id="@+id/iv_imgview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    tools:src="@drawable/home_tab_selector"

    />

<TextView
    android:id="@+id/tv_tab_name"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="HOME"
    />

and here is the portion of code that creates the tablayout:

for (int i = 0; i < NUM_OF_TABS; i++)
           tabLayout.addTab(tabLayout.newTab());

       adapter = new LandingPagerAdapter(getApplicationContext(),getSupportFragmentManager(), tabLayout.getTabCount());

       //Adding adapter to pager
       viewPager.setAdapter(adapter);

       tabLayout.addOnTabSelectedListener(this);
       tabLayout.setupWithViewPager(viewPager);

       // Iterate over all tabs and set the custom view
       for (int i = 0; i < tabLayout.getTabCount(); i++) {
           TabLayout.Tab tab = tabLayout.getTabAt(i);
           tab.setCustomView(adapter.getTabView(i));
       }

       tabLayout.getTabAt(0).select();

and finally here is the getTabView method responsible for applying the selector and custom view:

public class LandingPagerAdapter extends FragmentStatePagerAdapter {

    private final Context context;
    //integer to count number of tabs
    int tabCount;
    private Fragment mCurrentFragment;

    private String[] tabTitles = new String[]{"Home", "tab2"};

    // configure tab icons
    int[] imageTabResId = {
            R.drawable.home_tab_selector,
            R.drawable.tab_two_selector,;

    //Constructor to the class
    public LandingPagerAdapter(Context context, FragmentManager fm, int tabCount) {
        super(fm);
        this.context = context;
        this.tabCount = tabCount;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                TabHomeContainerFragment tab1 = new TabHomeContainerFragment();
                return tab1;
            case 1:
                TabTwoContainerFragment tab2 = new TabTwoContainerFragment();; //Todo: these should all be containers
                return tab2;
            default:
                return null;
        }
    }

    //Overriden method getCount to get the number of tabs
    @Override
    public int getCount() {
        return tabCount;
    }

    public Fragment getCurrentFragment() {
        return mCurrentFragment;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        if (getCurrentFragment() != object) {
            mCurrentFragment = ((Fragment) object);
        }
        super.setPrimaryItem(container, position, object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return tabTitles[position];
    }

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View v = LayoutInflater.from(context).inflate(R.layout.custom_landingpagetab, null);
        TextView tv = (TextView) v.findViewById(R.id.tv_tab_name);
        tv.setText(tabTitles[position]);
        ImageView img = (ImageView) v.findViewById(R.id.iv_imgview);
        img.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),imageTabResId[position]));
        return v;
    }

}

Notice in getTabView i am setting the image resource to be the selector in the array in the class field.
but nothing happens on the device on api 24 i have been testing on.

Body:
i ended up dropping the selector approach and just getting my customView from the tab. then i can change its view elements. i had a set of images in an array for selected and another for unselected.

then when the tabs switched i switch between the images based on tab position:

@Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
        TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

        iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId_selected[tab.getPosition()]));
        tv.setTextColor(ContextCompat.getColor(this, R.color.black));

    }
@Override
public void onTabUnselected(TabLayout.Tab tab) {
    ImageView iv = (ImageView) tab.getCustomView().findViewById(R.id.iv_imgview);
    TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab_name);

    iv.setImageDrawable(ContextCompat.getDrawable(this, imageTabResId[tab.getPosition()]));
    tv.setTextColor(ContextCompat.getColor(this, R.color.tabs_default_text));

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}


来源: stackexchange

问:
How to save file with custom file extension in java?
Dear brothers Hope you all right?
I'm designing a document program, however, rather to save file .text extension or using any other MS-Office API in java, i want to create my custom file format such as ".sad" extension so that this sort of file can only be read by my programs, how this can be possible?</p>

答:
I already stated why this is a bad idea. Yet I have a solution for you (more like a how-not-to-do-it)

Take your plain text you want to save, convert it to bytes and apply this "highly enthusiastic encryption nobody will ever be able to break" on it:

```<code>string plainText = "yadayada";
bytes[] bytesFromText = toBytes(plainText);
bytes[] encrypted = new Array(sizeof(bytesFromText)*2);
for(int i = 0; i < sizeof(bytesFromText); i++){
    if((i modulo 2) == 0){
        encrypted.push(toByte(Math.random modulo 255));
    }
    encrypted.push(bytesFromText[i]);
}
</code>```

I let it up to you to figure out why this is a bad idea and how to decrypt it. ;)

ContentLicense: CC BY-SA 3.0

Body:
I already stated why this is a bad idea. Yet I have a solution for you (more like a how-not-to-do-it)

Take your plain text you want to save, convert it to bytes and apply this "highly enthusiastic encryption nobody will ever be able to break" on it:

string plainText = "yadayada";
bytes[] bytesFromText = toBytes(plainText);
bytes[] encrypted = new Array(sizeof(bytesFromText)*2);
for(int i = 0; i < sizeof(bytesFromText); i++){
    if((i modulo 2) == 0){
        encrypted.push(toByte(Math.random modulo 255));
    }
    encrypted.push(bytesFromText[i]);
}

I let it up to you to figure out why this is a bad idea and how to decrypt it. ;)


问:
A list check before and after concatenation with different results
I have an assignment and the code is really simple to understand but I cant find a possible solution. Thats the code:

```<code>lucky:: [Integer] -> Bool
lucky (xs) = all (/=13) xs

catenate as []     = as
catenate as (b:bs) = b : (catenate as bs)

test_luck1 as bs = lucky as && lucky bs
test_luck2 as bs = lucky (catenate as bs)
</code>```

So the question is: For which input(the same for both functions) are the boolean values of both functions different, for example the first one true and the second one false or vice versa. So the first function tests both lists individually and the second tests the concatenation of the lists. I have been thinking all day yesterday and have absolutely no idea. Could you guys help me with finding the trick that should be used to solve the question?

答:
For infinite "lucky" bs and "unlucky" as, test_luck1 will terminate, while test_luck2 will not.

The functions test the values in different order, due to the (somewhat weird) implementation of catenate, which prepends bs to as.  Thus, test_luck1 tests as first, then bs, whereas test_luck2 tests bs first, and then as.

P.S.  This can be seen as a boundary case, as per @Mark Seemann's remark -- sorry for the spoiler ;)

Body:
I have an assignment and the code is really simple to understand but I cant find a possible solution. Thats the code:

lucky:: [Integer] -> Bool
lucky (xs) = all (/=13) xs

catenate as []     = as
catenate as (b:bs) = b : (catenate as bs)

test_luck1 as bs = lucky as && lucky bs
test_luck2 as bs = lucky (catenate as bs)

So the question is: For which input(the same for both functions) are the boolean values of both functions different, for example the first one true and the second one false or vice versa. So the first function tests both lists individually and the second tests the concatenation of the lists. I have been thinking all day yesterday and have absolutely no idea. Could you guys help me with finding the trick that should be used to solve the question?


问:
Replacing values in numpy array based on inequalities
Given a numpy array, I would like to replace its values based on inequalities. For example, given

```<code>x=np.array([0.3,7,8,-5.5,1,0.1])
</code>```

I want to replace the values that are smaller than 0 with 0, those that are between 0 and 5 would be replaced by 1, and the rest would be replaced with 2. So I want to get:

```<code>x=np.array([1,2,2,0,1,1])
</code>```

I could do that with pandas.cut as follows:

```<code>pandas.cut(pandas.DataFrame(x).iloc[:,0],[-np.inf,0,5,np.inf],labels=[0,1,2],right=False)
</code>```

but I was wondering if there is a more direct way to do that using numpy itself. Note that I could have more than 3 categories, which is why I was looking for something more systematic that behaves similarly to pandas.cut.

答:
Why not just use digitize?

```<code>import numpy as np
x = np.array([0.3,7,8,-5.5,1,0.1])
bins = np.array([-np.inf,0,5,np.inf])
np.digitize(x, bins) - 1 # Results are 1-based index
# array([1, 2, 2, 0, 1, 1], dtype=int64)
</code>```

Body:
Given a numpy array, I would like to replace its values based on inequalities. For example, given

x=np.array([0.3,7,8,-5.5,1,0.1])

I want to replace the values that are smaller than 0 with 0, those that are between 0 and 5 would be replaced by 1, and the rest would be replaced with 2. So I want to get:

x=np.array([1,2,2,0,1,1])

I could do that with pandas.cut as follows:

pandas.cut(pandas.DataFrame(x).iloc[:,0],[-np.inf,0,5,np.inf],labels=[0,1,2],right=False)

but I was wondering if there is a more direct way to do that using numpy itself. Note that I could have more than 3 categories, which is why I was looking for something more systematic that behaves similarly to pandas.cut.

Body:
Why not just use digitize?

import numpy as np
x = np.array([0.3,7,8,-5.5,1,0.1])
bins = np.array([-np.inf,0,5,np.inf])
np.digitize(x, bins) - 1 # Results are 1-based index
# array([1, 2, 2, 0, 1, 1], dtype=int64)


问:
Large Text File 1 > GB Frequency of KeyValuePair using File.ReadLine
I'm new to C# and object-oriented programming in general. I have an application which parses a very large text file.

I have two dictionaries:

Dictionary<string, string> parsingDict //key: original value, value: replacement
Dictionary<int, string> Frequency // key: count, value: counted string

I am finding the frequency of each key. I am able to get the desired output which is:

System1 has been replaced with MachineA 5 time(s)

System2 has been replaced with MachineB 7 time(s)

System3 has been replaced with MachineC 10 time(s)

System4 has been replaced with MachineD 19 time(s)

Following is my code:

```<code>String[] arrayofLine = File.ReadAllLines(File);
           foreach (var replacement in parsingDict.Keys)
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                if (arrayofLine[i].Contains(replacement))
                {
                    countr++;

                    Frequency.Add(countr, Convert.ToString(replacement));
                }
            }

        }

        Frequency = Frequency.GroupBy(s => s.Value)
                .Select(g => g.First())
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);  //Get only the distinct records.

        foreach (var freq in Frequency)
        {
            sbFreq.AppendLine(string.Format("The text {0} was replaced {2} time(s) with {1} \n",
            freq.Value, parsingDict[freq.Value],
            arrayofLine.Where(x => x.Contains(freq.Value)).Count()));
        }
</code>```

Using String[] arrayofLine = File.ReadAllLines(File); increases memory utilization.

How can arrayofLine.Where(x => x.Contains(freq.Value)).Count()) be achieve using File.ReadLine as it is memory friendly.

答:
You can read lines one at a time rather easily (ref).

The relevant code would look like this:

```<code>Dictionary<string,int> lineCount = new Dictionary<string,int>();
string line;

// Read the file and display it line by line.
using(System.IO.StreamReader file =
   new System.IO.StreamReader("c:\\test.txt"))
{
   while((line = file.ReadLine()) != null)
   {
      string value = DiscoverFreq(line);
      lineCount[value] += 1;
    }
}
</code>```

NOTE: it is important that you think about other bits of information you are storing as well.  Appending lines from a large file into a string is essentially the same as reading the whole file at once, but with more garbage collection.

NOTE 2: I simplified the part where you update the counts.  You'll have to check if the count entry is present and add it, or increment it if it is there.  Alternatively you can initialice your lineCounts with all the freq.Values set to 0 before scanning the file.

If the number of unique words are high enough, then you may need to use a small database like SQLite to store the counts for you.  That lets you query the information quickly without thinking about how to store and read a custom file you wrote yourself.

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses a very large text file.

I have two dictionaries:

Dictionary<string, string> parsingDict //key: original value, value: replacement
Dictionary<int, string> Frequency // key: count, value: counted string

I am finding the frequency of each key. I am able to get the desired output which is:

System1 has been replaced with MachineA 5 time(s)

System2 has been replaced with MachineB 7 time(s)

System3 has been replaced with MachineC 10 time(s)

System4 has been replaced with MachineD 19 time(s)

Following is my code:

String[] arrayofLine = File.ReadAllLines(File);
           foreach (var replacement in parsingDict.Keys)
        {
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                if (arrayofLine[i].Contains(replacement))
                {
                    countr++;

                    Frequency.Add(countr, Convert.ToString(replacement));
                }
            }

        }

        Frequency = Frequency.GroupBy(s => s.Value)
                .Select(g => g.First())
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);  //Get only the distinct records.

        foreach (var freq in Frequency)
        {
            sbFreq.AppendLine(string.Format("The text {0} was replaced {2} time(s) with {1} \n",
            freq.Value, parsingDict[freq.Value],
            arrayofLine.Where(x => x.Contains(freq.Value)).Count()));
        }

Using String[] arrayofLine = File.ReadAllLines(File); increases memory utilization.

How can arrayofLine.Where(x => x.Contains(freq.Value)).Count()) be achieve using File.ReadLine as it is memory friendly.

Body:
You can read lines one at a time rather easily (ref).

The relevant code would look like this:

Dictionary<string,int> lineCount = new Dictionary<string,int>();
string line;

// Read the file and display it line by line.
using(System.IO.StreamReader file =
   new System.IO.StreamReader("c:\\test.txt"))
{
   while((line = file.ReadLine()) != null)
   {
      string value = DiscoverFreq(line);
      lineCount[value] += 1;
    }
}

NOTE: it is important that you think about other bits of information you are storing as well.  Appending lines from a large file into a string is essentially the same as reading the whole file at once, but with more garbage collection.

NOTE 2: I simplified the part where you update the counts.  You'll have to check if the count entry is present and add it, or increment it if it is there.  Alternatively you can initialice your lineCounts with all the freq.Values set to 0 before scanning the file.

If the number of unique words are high enough, then you may need to use a small database like SQLite to store the counts for you.  That lets you query the information quickly without thinking about how to store and read a custom file you wrote yourself.


问:
AJAX script with json format data not working
My complete script is as follows

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(window).on('load',function(){
            $('#myModal').modal('show');
        });
    </script>
    <script>
        $( document ).ready(function () {
            $("#vote").click(function (e) {
                var poll_id = $('input[name=pollID]', '#myForm').val();
                var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
                //alert(poll_id + "AND" + poll_option_id);
                $.ajax({
                    type: "POST",
                    url: "http://localhost/poll/index.php/form/poll",
                    data: {poll_id: poll_id, poll_option_id: poll_option_id},
                    dataType: "json",
                    success: function(data) {
                        alert(data);
                    }, error: function() {
                        alert("ERROR");
                    }
                });
            });
        });
    </script>
</code>```

And I have the following inside poll function in form controller

```<code>public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}
</code>```

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

答:
Your pool  if should be like </p>

```<code>   if($voteSubmit){
                echo json_encode(array('msg' =>'Your Vote Has Been Submitted successfully.'));
            }else{
                echo json_encode(array('msg' =>'You Had Already Voted.'));
            }
</code>```

<p>and ur ajax success should be like </p>

```<code> success: function(data) {
                    alert(data.msg);
                },
error: function() {
                    alert("ERROR");
                }
</code>```

Body:
My complete script is as follows

And I have the following inside poll function in form controller

public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

Body:
Your pool  if should be like

   if($voteSubmit){
                echo json_encode(array('msg' =>'Your Vote Has Been Submitted successfully.'));
            }else{
                echo json_encode(array('msg' =>'You Had Already Voted.'));
            }

and ur ajax success should be like

 success: function(data) {
                    alert(data.msg);
                },
error: function() {
                    alert("ERROR");
                }


问:
How to filter the result from comparing a XML & XSD?
I'm comparing one XML & one XSD collection in WPF with TreeViewItem.
I finally got the missing result to show in red.
But how to filter the result from XSD collection to a listbox, so that it can show only the lines(values) which are in red  ?

```<code>private void CompareTrees(ItemCollection xml, ItemCollection xsd, List<string> path)
    {
        foreach (TreeViewItem tvixsd in xsd.OfType<TreeViewItem>())
        {
            path.Add(tvixsd.Header.ToString());

            if (tvixsd.HasItems)
            {
                CompareTrees(xml, tvixsd.Items, path);
            }
            else
            {
                TreeViewItem res = xml.OfType<TreeViewItem>().FirstOrDefault();
                foreach (var point in path.Skip(1))
                {
                    res = res.Items.OfType<TreeViewItem>().FirstOrDefault(i => i.Header.ToString() == point);
                    if (res == null)
                    {
                        treeViewCom.Items.Add(res);
                        tvixsd.Foreground = Brushes.Red;

                        break;
                    }

                    if (!res.HasItems)
                    {
                        break;
                    }
                }
            }

            if (path.Count != 0)
            {
                path.RemoveAt(path.Count - 1);
            }
        }
    }
</code>```

Thanks

答:
Set the Filter property of the ItemsCollection:

```<code>xsd.Filter = (obj) =>
{
    TreeViewItem tvi = obj as TreeViewItem;
    return tvi != null && tvi.Foreground == Brushes.Red;
};
</code>```

Body:
I'm comparing one XML & one XSD collection in WPF with TreeViewItem.
I finally got the missing result to show in red.
But how to filter the result from XSD collection to a listbox, so that it can show only the lines(values) which are in red  ?

private void CompareTrees(ItemCollection xml, ItemCollection xsd, List<string> path)
    {
        foreach (TreeViewItem tvixsd in xsd.OfType<TreeViewItem>())
        {
            path.Add(tvixsd.Header.ToString());

            if (tvixsd.HasItems)
            {
                CompareTrees(xml, tvixsd.Items, path);
            }
            else
            {
                TreeViewItem res = xml.OfType<TreeViewItem>().FirstOrDefault();
                foreach (var point in path.Skip(1))
                {
                    res = res.Items.OfType<TreeViewItem>().FirstOrDefault(i => i.Header.ToString() == point);
                    if (res == null)
                    {
                        treeViewCom.Items.Add(res);
                        tvixsd.Foreground = Brushes.Red;

                        break;
                    }

                    if (!res.HasItems)
                    {
                        break;
                    }
                }
            }

            if (path.Count != 0)
            {
                path.RemoveAt(path.Count - 1);
            }
        }
    }

Thanks

Body:
Set the Filter property of the ItemsCollection:

xsd.Filter = (obj) =>
{
    TreeViewItem tvi = obj as TreeViewItem;
    return tvi != null && tvi.Foreground == Brushes.Red;
};


问:
Button not triggering Controller method MVC 5 C#
Create cshtml takes in the address written by the user.

```<code><div class="form-group">
    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
    </div>
</div>
</code>```

the button currently does nothing but i need it to trigger the method below

```<code> @Html.AntiForgeryToken()

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default"  />
        </div>
    </div>
 }
</code>```

Orders Controller Create method takes in attributes from the user.

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Order order, ApplicationUser currentUser)
{
    if (ModelState.IsValid)
    {
        order.FirstName = currentUser.FirstName;
        order.LastName = currentUser.LastName;
        order.PostalCode = currentUser.PostalCode;
        order.State = currentUser.State;
        order.City = currentUser.City;
        order.Email = currentUser.Email;
        order.Country = currentUser.Country;
        order.Phone = currentUser.Phone;
        db.Orders.Add(order);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(order);
}
</code>```

答:
You should have the code inside a Html.BeginForm

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

}```

Body:
Create cshtml takes in the address written by the user.

    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

the button currently does nothing but i need it to trigger the method below

 @Html.AntiForgeryToken()

            <input type="submit" value="Create" class="btn btn-default"  />

 }

Orders Controller Create method takes in attributes from the user.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Order order, ApplicationUser currentUser)
{
    if (ModelState.IsValid)
    {
        order.FirstName = currentUser.FirstName;
        order.LastName = currentUser.LastName;
        order.PostalCode = currentUser.PostalCode;
        order.State = currentUser.State;
        order.City = currentUser.City;
        order.Email = currentUser.Email;
        order.Country = currentUser.Country;
        order.Phone = currentUser.Phone;
        db.Orders.Add(order);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(order);
}

Body:
You should have the code inside a Html.BeginForm

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}


问:
Maintaining environment state between subprocess.Popen commands?
I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.

The nodes are running on EC2.

One of the projects depends on a from source version of a 3rd party application.

Specifically:

```<code>cd /tmp
wget s3://.../tools/x264_20_12_2010.zip
unzip x264_20_12_2010.zip
cd x264_20_12_2010
./configure
make
checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default
</code>```

Currently I'm doing this with boto's ShellCommand (which uses subprocess.Popen internally), this looks something like this:

```<code>def deploy():
        ShellCommand("apt-get remove ffmpeg x264 libx264-dev")
        ShellCommand("apt-get update")
        ShellCommand("apt-get install -y build-essential checkinstall yasm texi2html libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support libfaac-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev zlib1g-dev")

        ShellCommand("cd /tmp")
        s3cmd_sync("s3://.../tools/x264_20_12_2010.zip", "/tmp/x264_20_12_2010.zip")
        ShellCommand("unzip x264_20_12_2010.zip")
        ShellCommand("cd x264_20_12_2010")
        ShellCommand("./configure")
        ShellCommand("make")
        ShellCommand(r'checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default')
</code>```

Sadly this fails, because cd /tmp applies to the subprocess, meaning that once I return the the father process and issue the second ShellCommand the exeenv is inherited from the father, which leans me to think that I need some execution framework for shell commands which will apply all commands in the same sub process without loosing context.

What is the recommend solution to this problem? Please note that loggings of the command line executed app is very important (how can you debug without it?), which is why I like ShellCommand... (see boto logging if interested).

Thank you,

Maxim.

答:
I ended up doing this</p>

```<code>def shell_script(appname, *commands):
        workspace = tempfile.mkdtemp(prefix=appname + '-')
        installer = open(workspace + "/installer.sh", 'w')

        installer.write("#!/bin/bash\n")
        installer.write("cd " + workspace + "\n")
        for line in commands:
                installer.write(line + "\n")
        ShellCommand("chmod u+x " + installer.name)
        installer.close()
        ShellCommand(installer.name)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a deployment engine for our system, where each project specifies his custom deployment instructions.

The nodes are running on EC2.

One of the projects depends on a from source version of a 3rd party application.

Specifically:

cd /tmp
wget s3://.../tools/x264_20_12_2010.zip
unzip x264_20_12_2010.zip
cd x264_20_12_2010
./configure
make
checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default

Currently I'm doing this with boto's ShellCommand (which uses subprocess.Popen internally), this looks something like this:

def deploy():
        ShellCommand("apt-get remove ffmpeg x264 libx264-dev")
        ShellCommand("apt-get update")
        ShellCommand("apt-get install -y build-essential checkinstall yasm texi2html libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support libfaac-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev zlib1g-dev")

        ShellCommand("cd /tmp")
        s3cmd_sync("s3://.../tools/x264_20_12_2010.zip", "/tmp/x264_20_12_2010.zip")
        ShellCommand("unzip x264_20_12_2010.zip")
        ShellCommand("cd x264_20_12_2010")
        ShellCommand("./configure")
        ShellCommand("make")
        ShellCommand(r'checkinstall --pkgname=x264 --pkgversion "2:0.HEAD" --backup=no --deldoc=yes --fstrans=no --default')

Sadly this fails, because cd /tmp applies to the subprocess, meaning that once I return the the father process and issue the second ShellCommand the exeenv is inherited from the father, which leans me to think that I need some execution framework for shell commands which will apply all commands in the same sub process without loosing context.

What is the recommend solution to this problem? Please note that loggings of the command line executed app is very important (how can you debug without it?), which is why I like ShellCommand... (see boto logging if interested).

Thank you,

Maxim.

Body:
I ended up doing this

def shell_script(appname, *commands):
        workspace = tempfile.mkdtemp(prefix=appname + '-')
        installer = open(workspace + "/installer.sh", 'w')

        installer.write("#!/bin/bash\n")
        installer.write("cd " + workspace + "\n")
        for line in commands:
                installer.write(line + "\n")
        ShellCommand("chmod u+x " + installer.name)
        installer.close()
        ShellCommand(installer.name)


问:
Magento 2 Add Bundle product into cart from code
I am trying to insert to checkout/cart some bundle product with child items.
I am using this code but it work only with simple product.

```<code>$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $objectManager->get('Magento\Catalog\Model\Product')->load(703);

$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');

$addToCartUrl =  $listBlock->getAddToCartUrl($product);

echo $addToCartUrl;
</code>```

I also used this suggest

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $this->productRepository->getById("703");

$magento = array(82=>"103",82 => "112");

$par = array('product' => $product->getId(),'bundle_options' => array( 1
=> $magento),'qty' => $qty);

$this->cart->addProduct($_product,$par);

$this->cart->save();

But still doesn't work. Can someone help me?
Thanks

答:
// Find the below code for add bundle product.

```<code>$product = $this->productRepository->getById("29");
$magento = array(21=>"1",22 => "2", 23 => "3");
$par = array('product' => $product->getId(),
             'bundle_options' => array(  1 => $magento),
             'qty' => $qty);
$this->cart->addProduct($_product,$par);
$this->cart->save();
</code>```

Reference link : https://magento.stackexchange.com/questions/112788/magento-2-add-bundled-product-to-cart-programmatically

Body:
I am trying to insert to checkout/cart some bundle product with child items.
I am using this code but it work only with simple product.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $objectManager->get('Magento\Catalog\Model\Product')->load(703);

$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');

$addToCartUrl =  $listBlock->getAddToCartUrl($product);

echo $addToCartUrl;

I also used this suggest

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $this->productRepository->getById("703");

$magento = array(82=>"103",82 => "112");

$par = array('product' => $product->getId(),'bundle_options' => array( 1
=> $magento),'qty' => $qty);

$this->cart->addProduct($_product,$par);

$this->cart->save();

But still doesn't work. Can someone help me?
Thanks

Body:
// Find the below code for add bundle product.

$product = $this->productRepository->getById("29");
$magento = array(21=>"1",22 => "2", 23 => "3");
$par = array('product' => $product->getId(),
             'bundle_options' => array(  1 => $magento),
             'qty' => $qty);
$this->cart->addProduct($_product,$par);
$this->cart->save();

Reference link : https://magento.stackexchange.com/questions/112788/magento-2-add-bundled-product-to-cart-programmatically


问:
Why do I keep getting an error saying e in endtime is invalid syntax in Python?
```<code>import time as t
t = t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))
</code>```

I don't know how I can fix my code.

答: You forgot the return statement in your function maybe this is the problem</p>

Body:
import time as t
t = t.time
starttime = t
def calcprod():
    prod = 1
    for i in range(1, 1000000):
        prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))

I don't know how I can fix my code.


问:
What are the best methods to fetch data from DB in Real time?
How to update database and fetch updates in DB in real time?

I have tried some on the internet. I have found that I can use socket.io, but I am not sure this will be the most effective procedure. I am hoping to use javascript languages. Also I have found that Angular and Firebase will do the job. but I want to use my own database.

Any idea?

Cheers.

答: For real time CRUD operations with DB better to use cloud databases, Firebase, AWS dynamoDB are better choices because they are scalable according to your need. You can make use of MongoDB also, you've to configure it with Nodejs & write simple API to read & write data in database. It works really great & easy to implement. Follow some sample of MEAN stack app. (Mean.io) Again there's cloud version of MongoDB also available (mlab.com) to host your database.</p>


问:
What essential design artifacts do you produce?
In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice?

The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI-based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices?

答:
Having worked on a lot of waterfall projects in the past and a lot of adhoc and agile projects more recently, there's a number of design artifacts I like to create although I can't state enough that it really depends on the details of the project (methodology, team structure, timescale, tools, etc.).

For a generic, server-based 'enterprise application' I'd want the bare minimum to be something along these lines:

A detailed functional design document (aka specification). Generally something along the lines of Joel s' WhatsTimeIsIt example specification, although probably with some UML use case diagrams.

A software technical design document. It is not necessarily detailed for 100% system coverage, but detailed in all the key areas and containing all the design decisions. Being a bit of an UML freak, it'd be nice to see lots of pictures along the lines of package diagrams, component diagrams, key feature class diagrams, and probably some sequence diagrams thrown in for good measure.

An infrastructure design document. Probably with UML deployment diagram for the conceptual design and perhaps a network diagram for something more physical.

When I say document, any of the above might be broken down into multiple documents, or perhaps stored on a wiki/some other tool.

As for their usefulness, my philosophy has always been that a development team should always be able to hand over an application to a support team without having to hand over their phone numbers. If the design artifacts don't clearly indicate what the application does, how it does it, and where it does it then you know the support teams are going to give the app the same care and attention they would a rabid dog.

I should mention I'm not vindicating the practice of handing software over from a development team to a support team once it's finished, which raises all manner of interesting issues; I'm just saying it should be possible if the management so desired.

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Ubiguchi

LastEditorDisplayName: Ubiguchi


问:
How do you avoid the n+1 problem with SubSonic?
Ayende has a blog post detailing how to combat the "n+1" problem in nHibernate.  In essence, the problem is this:

Assume you have two tables, "BlogPosts" and "Comments" with a one-to-many relationship between them (i.e. each BlogPost can have multiple Comments).  Now, let's say you want to execute the following nested for loop:

```<code>foreach (BlogPost post in blogposts)
{
    foreach (Comment comment in post.Comments)
    {
        // Do something
    }
}
</code>```

From what I understand, the classes that SubSonic generate are lazyload by default (I don't want to turn this off completely because it's useful in most circumstances, just not this one).  That means that every time the inner loop is executed (i.e. when post.Comments is accessed), a separate query must be sent to the database to retrieve the comments.

So if you have 80 blog posts, that's 1 query to get the list of blog posts, then 80 queries to get the comments for each of them.  If the comments were eager loaded, however, this would be reduced to 1 query.

Is there any way to combat this problem in SubSonic currently?

答: I think what you should do is create a partial class method that will get all the comments. Not so clean but should work.</p>

OwnerDisplayName: Kevin Pang

Body:
Ayende has a blog post detailing how to combat the "n+1" problem in nHibernate.  In essence, the problem is this:

Assume you have two tables, "BlogPosts" and "Comments" with a one-to-many relationship between them (i.e. each BlogPost can have multiple Comments).  Now, let's say you want to execute the following nested for loop:

foreach (BlogPost post in blogposts)
{
    foreach (Comment comment in post.Comments)
    {
        // Do something
    }
}

From what I understand, the classes that SubSonic generate are lazyload by default (I don't want to turn this off completely because it's useful in most circumstances, just not this one).  That means that every time the inner loop is executed (i.e. when post.Comments is accessed), a separate query must be sent to the database to retrieve the comments.

So if you have 80 blog posts, that's 1 query to get the list of blog posts, then 80 queries to get the comments for each of them.  If the comments were eager loaded, however, this would be reduced to 1 query.

Is there any way to combat this problem in SubSonic currently?

OwnerDisplayName: Yitzchok-adminjew


问:
Can I generate a Spring Feign client with Multipart parameters?
I am getting the error:
   "Method has too many Body parameters"
when trying to generate a Spring Feign client

```<code>@RequestMapping(value="/media", method=RequestMethod.POST)
String uploadMedia(@RequestHeader("Authentication") String token,
    @RequestPart("media") MultipartFile audio,
    @RequestPart("a-json-object") SomeClass someClazz,
    @RequestPart("another-json-object") AnotherClass anotherClazz);
</code>```

I found the following solution, which works when using regular Feign annotations, but not with Spring MVC annotations:

'Too many body parameters' Exception on Feign Client

答:
It should be possible now. Add the following dependencies:

```<code><dependencies>
...
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>2.2.0</version>
</dependency>
...
</code>```

and use this client configuration:

```<code>@FeignClient(name = "file-upload-service", configuration = FileUploadServiceClient.MultipartSupportConfig.class)
public interface FileUploadServiceClient extends IFileUploadServiceClient {

    @Configuration
    public class MultipartSupportConfig {

        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }
}
</code>```

Example was taken from: feign-form docs

Body:
I am getting the error:
   "Method has too many Body parameters"
when trying to generate a Spring Feign client

@RequestMapping(value="/media", method=RequestMethod.POST)
String uploadMedia(@RequestHeader("Authentication") String token,
    @RequestPart("media") MultipartFile audio,
    @RequestPart("a-json-object") SomeClass someClazz,
    @RequestPart("another-json-object") AnotherClass anotherClazz);

I found the following solution, which works when using regular Feign annotations, but not with Spring MVC annotations:

'Too many body parameters' Exception on Feign Client

Body:
It should be possible now. Add the following dependencies:

<dependencies>
...
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>2.2.0</version>
</dependency>
...

and use this client configuration:

@FeignClient(name = "file-upload-service", configuration = FileUploadServiceClient.MultipartSupportConfig.class)
public interface FileUploadServiceClient extends IFileUploadServiceClient {

    @Configuration
    public class MultipartSupportConfig {

        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }
}

Example was taken from: feign-form docs


问:
Better way to write this jQuery Function?
basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?</p>

```<code>$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});
</code>```

Body:
basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?

$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});

Body:
$('#l1,#l2,#l3,#l4,#l5,#l6,#l7').hover(function() {
    $(this).fadeOut(300);
    $("#" + this.id + "c").fadeIn(300);
});

$('#l1c,#l2c,#l3c,#l4c,#l5c,#l6c,#l7c').mouseout(function() {
    $(this).fadeOut(300);
    $("#" + this.id.substring(0, this.id.length - 1)).fadeIn(300);
});


问:
sqlite select only first row with unique cell in column
I need to select from sqlite table based on column "categ" first row with unique name.
Here is what I have:

```<code>|id     |val    |categ
|1      |any1   |categ1
|2      |any2   |categ1
|3      |any3   |categ2
|4      |any4   |categ2
|5      |any5   |categ2
|6      |any6   |categ3
|7      |any7   |categ3
|8      |any8   |categ4
|9      |any9   |categ4
|10     |any10  |categ4
</code>```

And here is what I need as result:

```<code>|id     |val    |categ
|1      |any1   |categ1
|3      |any3   |categ2
|6      |any6   |categ3
|8      |any8   |categ4
</code>```

First row are column names. And filter should be done by column "categ".
I need to get as results 1 row from each categ.
The name of categs are just as example, in real table the "categ" names are person names (Example: John, Mary etc)

Any suggestion?

答: Use Group By clause on Categ column</p>

Body:
I need to select from sqlite table based on column "categ" first row with unique name.
Here is what I have:

|id     |val    |categ
|1      |any1   |categ1
|2      |any2   |categ1
|3      |any3   |categ2
|4      |any4   |categ2
|5      |any5   |categ2
|6      |any6   |categ3
|7      |any7   |categ3
|8      |any8   |categ4
|9      |any9   |categ4
|10     |any10  |categ4

And here is what I need as result:

|id     |val    |categ
|1      |any1   |categ1
|3      |any3   |categ2
|6      |any6   |categ3
|8      |any8   |categ4

First row are column names. And filter should be done by column "categ".
I need to get as results 1 row from each categ.
The name of categs are just as example, in real table the "categ" names are person names (Example: John, Mary etc)

Any suggestion?

Body: Use Group By clause on Categ column


问:
gitignore won't ignore my .settings/ directory (created by eclipse)
git status:

```<code>Untracked files:
(use "git add <file>..." to include in what will be committed)
    .settings/
</code>```

I've tried the following variations on my .gitignore file and nothing seems to work:

```<code>.settings/

*settings*

*.settings/

.settings/*
</code>```

I've never had this much trouble with .gitignore, it usually just works. I must be doing something real dumb.

NOTE: My .gitignore file has more in it than just that one line (all the other lines works correctly).

答:
/**/.settings/

worked to ignore the .settings folders below the root.

Body:
git status:

Untracked files:
(use "git add <file>..." to include in what will be committed)
    .settings/

I've tried the following variations on my .gitignore file and nothing seems to work:

.settings/

*settings*

*.settings/

.settings/*

I've never had this much trouble with .gitignore, it usually just works. I must be doing something real dumb.

NOTE: My .gitignore file has more in it than just that one line (all the other lines works correctly).


问:
Returning a Python object instance of an inner class of a function
I wrote a function in Python that is supposed to work similar to a factory in Java, as it instances the correct class for the given parameters and returns this instance.

A minimal example with only one class inside the function would be this:

```<code>def create_object(param):

    class SpecialClass(ParentClass):
        def func(self, param):
            doSomething()

    class_instance = SpecialClass(param)
    return class_instance
</code>```

I can flawlessly use this object when I call this function from outside. Coming from a Java background, I assume this has something to do with the dynamic typing in Python but I'm still not sure why this actually works. Isn't the scope where that class is known just within the function itself?

答:
To answer your question, you have returned an object and Python will let you use it regardless of where the original class was defined. There are no private classes in Python and functions themselves are objects, so basically when you return the object, everything outside of that function sees the object as an instance of create_object.SpecialClass.

In practice though factories are not something that you make in Python. You should be using a class method that will simply return an instance of the class. You can read more about it here: https://docs.python.org/3/library/functions.html#classmethod

If you're confused just google python classmethod decorator and there are some good Stackoverflow explanations of how to use them.

Body:
I wrote a function in Python that is supposed to work similar to a factory in Java, as it instances the correct class for the given parameters and returns this instance.

A minimal example with only one class inside the function would be this:

def create_object(param):

    class SpecialClass(ParentClass):
        def func(self, param):
            doSomething()

    class_instance = SpecialClass(param)
    return class_instance

I can flawlessly use this object when I call this function from outside. Coming from a Java background, I assume this has something to do with the dynamic typing in Python but I'm still not sure why this actually works. Isn't the scope where that class is known just within the function itself?


问:
How complex can an enum get before reading lines of data from a file is better (e.g. .csv)?
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

```<code>PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);
</code>```

Would it be best to specify data in a file and read it instead?

答:
The beauty of enum is that they are fixed in code and will not change. This provides huge benefits when coding, type checking and you can make Maps and Set of them and you can iterate across them and even switch-case with them (although that is less common now they can have their own functionality). You can even save them in a database so long as you use their names and the data still maps back correctly even when the enum list changes.

As such, I would not abandon them , I would probably add a new one called perhaps "OTHERS" which can somehow provide any new ones that are experimental etc.

If your core issue is with the tediousness of maintaining the parameters then by all means read that data in from configuration using a static initialiser.

Body:
I have created part of a platformer game where I have an actor class, representing instances of objects and characters, and a type enum which denotes what data each actor will have (such as speed, attack, defence, etc).
Specifying all the data of each type seems somewhat tedious with hardcoded enum definitions.
E.g.

PLANE("Plane", 10, 10, 2, 0),
MISSILE("Missile", 1, 0, 0, 4);

Would it be best to specify data in a file and read it instead?


问:
PHP - Excel renders PDF without image
I'm developing with the yii2 framework. I need to render some reports which should have some images. Everything is working in my excel file. But in PDF there are no images.

What I have in excel:

What I have in PDF:

My test code looks like this:

```<code>public function run($format = self::EXCEL) {
    $this->format = $format;
    if ($this->format == self::PDF) {
        $rendererName = \PHPExcel_Settings::PDF_RENDERER_MPDF;
        $rendererLibraryPath = Yii::getAlias('@vendor/mpdf/mpdf/');

        if (!\PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibraryPath)) {
            throw new BadRequestHttpException('Export pdf fail');
        }
        $this->headerContentType .= 'pdf';
        $this->headerFilename .= date('d_m_Y') . '.pdf';
    } elseif ($this->format == self::EXCEL) {
        $this->headerContentType .= 'vnd.ms-excel';
        $this->headerFilename .= date('d_m_Y') . '.xls';
    } else {
        throw new Exception('Unknown format for export');
    }

    $this->objPHPExcel->setActiveSheetIndex(0);
    $activeSheet = $this->objPHPExcel->getActiveSheet();
    $activeSheet->setTitle('Sample' . date('d_m_Y'));

        $objDrawing = new PHPExcel_Worksheet_Drawing();
        $objDrawing->setWorksheet($activeSheet);
        $activeSheet->getColumnDimension('B')->setWidth(50);
        $activeSheet->getRowDimension(2)->setRowHeight(80);
        $activeSheet->setCellValue('A2','img -> ');
        $activeSheet->setCellValue('B2',' ');
        $objDrawing->setCoordinates('B'.2);
        $objDrawing->setOffsetX(10)->setOffsetY(10);

        $objDrawing->setName('Sample_image');
        $objDrawing->setDescription('Sample_image');
        $objDrawing->setPath('/home/vladimir/projects/temp/img.jpg');
        $objDrawing->setWidth(50)->setHeight(50);

    header($this->headerContentType);
    header($this->headerFilename);
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel, $this->format);
    $objWriter->save('php://output');
    exit;
}
</code>```

答:
I was stuck in CI3 and if you are using CI put the images folder outside of application folder and add path as </p>

```<code>$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('uploads/organizations/1.jpg');
$objDrawing->setHeight(36);
$objDrawing->setWorksheet($this->excel_reader_writer->getSheetByName($download_section));
</code>```

<p>The File Structure is </p>

```<code>/- application
/- system
/- user_guide
/- uploads
</code>```

Title: PHP - Excel renders PDF without image

Body:
I'm developing with the yii2 framework. I need to render some reports which should have some images. Everything is working in my excel file. But in PDF there are no images.

What I have in excel:

What I have in PDF:

My test code looks like this:

public function run($format = self::EXCEL) {
    $this->format = $format;
    if ($this->format == self::PDF) {
        $rendererName = \PHPExcel_Settings::PDF_RENDERER_MPDF;
        $rendererLibraryPath = Yii::getAlias('@vendor/mpdf/mpdf/');

        if (!\PHPExcel_Settings::setPdfRenderer($rendererName, $rendererLibraryPath)) {
            throw new BadRequestHttpException('Export pdf fail');
        }
        $this->headerContentType .= 'pdf';
        $this->headerFilename .= date('d_m_Y') . '.pdf';
    } elseif ($this->format == self::EXCEL) {
        $this->headerContentType .= 'vnd.ms-excel';
        $this->headerFilename .= date('d_m_Y') . '.xls';
    } else {
        throw new Exception('Unknown format for export');
    }

    $this->objPHPExcel->setActiveSheetIndex(0);
    $activeSheet = $this->objPHPExcel->getActiveSheet();
    $activeSheet->setTitle('Sample' . date('d_m_Y'));

        $objDrawing = new PHPExcel_Worksheet_Drawing();
        $objDrawing->setWorksheet($activeSheet);
        $activeSheet->getColumnDimension('B')->setWidth(50);
        $activeSheet->getRowDimension(2)->setRowHeight(80);
        $activeSheet->setCellValue('A2','img -> ');
        $activeSheet->setCellValue('B2',' ');
        $objDrawing->setCoordinates('B'.2);
        $objDrawing->setOffsetX(10)->setOffsetY(10);

        $objDrawing->setName('Sample_image');
        $objDrawing->setDescription('Sample_image');
        $objDrawing->setPath('/home/vladimir/projects/temp/img.jpg');
        $objDrawing->setWidth(50)->setHeight(50);

    header($this->headerContentType);
    header($this->headerFilename);
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel, $this->format);
    $objWriter->save('php://output');
    exit;
}

Body:
I was stuck in CI3 and if you are using CI put the images folder outside of application folder and add path as

$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('uploads/organizations/1.jpg');
$objDrawing->setHeight(36);
$objDrawing->setWorksheet($this->excel_reader_writer->getSheetByName($download_section));

The File Structure is

/- application
/- system
/- user_guide
/- uploads


问:
Unable to install package car
I am using R version 3.2.3 in Linux mint 17.3 64 bit. I was trying to install the package "car" with dependencies=TRUE, but the installation failed with the following error messages:

```<code>> warnings()
Warning messages:
1: In install.packages("car", dependencies = T) :
installation of package ‘minqa’ had non-zero exit status
2: In install.packages("car", dependencies = T) :
installation of package ‘RcppEigen’ had non-zero exit status
3: In install.packages("car", dependencies = T) :
installation of package ‘leaps’ had non-zero exit status
4: In install.packages("car", dependencies = T) :
installation of package ‘lmtest’ had non-zero exit status
5: In install.packages("car", dependencies = T) :
installation of package ‘rgl’ had non-zero exit status
6: In install.packages("car", dependencies = T) :
installation of package ‘SparseM’ had non-zero exit status
7: In install.packages("car", dependencies = T) :
installation of package ‘quantreg’ had non-zero exit status
8: In install.packages("car", dependencies = T) :
installation of package ‘lme4’ had non-zero exit status
9: In install.packages("car", dependencies = T) :
installation of package ‘effects’ had non-zero exit status
10: In install.packages("car", dependencies = T) :
installation of package ‘pbkrtest’ had non-zero exit status
11: In install.packages("car", dependencies = T) :
installation of package ‘car’ had non-zero exit status
12: In install.packages("car", dependencies = T) :
installation of package ‘alr4’ had non-zero exit status
</code>```

How do I resolve the issue? Please help.

答:
Install r-cran-car

Installing r-cran-car package on Ubuntu 16.04 (Xenial Xerus) is as easy as running the following command on terminal:

sudo apt-get update

sudo apt-get install r-cran-car

Title: Unable to install package car

Body:
I am using R version 3.2.3 in Linux mint 17.3 64 bit. I was trying to install the package "car" with dependencies=TRUE, but the installation failed with the following error messages:

> warnings()
Warning messages:
1: In install.packages("car", dependencies = T) :
installation of package ‘minqa’ had non-zero exit status
2: In install.packages("car", dependencies = T) :
installation of package ‘RcppEigen’ had non-zero exit status
3: In install.packages("car", dependencies = T) :
installation of package ‘leaps’ had non-zero exit status
4: In install.packages("car", dependencies = T) :
installation of package ‘lmtest’ had non-zero exit status
5: In install.packages("car", dependencies = T) :
installation of package ‘rgl’ had non-zero exit status
6: In install.packages("car", dependencies = T) :
installation of package ‘SparseM’ had non-zero exit status
7: In install.packages("car", dependencies = T) :
installation of package ‘quantreg’ had non-zero exit status
8: In install.packages("car", dependencies = T) :
installation of package ‘lme4’ had non-zero exit status
9: In install.packages("car", dependencies = T) :
installation of package ‘effects’ had non-zero exit status
10: In install.packages("car", dependencies = T) :
installation of package ‘pbkrtest’ had non-zero exit status
11: In install.packages("car", dependencies = T) :
installation of package ‘car’ had non-zero exit status
12: In install.packages("car", dependencies = T) :
installation of package ‘alr4’ had non-zero exit status

How do I resolve the issue? Please help.


问:
setting ylim on seaborn boxplot
Is it possible to set ylim parameters on a seaborn boxplot?

as an example:

```<code>y = np.random.randn(300)
sns.boxplot (y=y)
</code>```

Displays

boxplot

but if I try

```<code>ax.set_ylim=(-5, 5)
</code>```

It makes no difference. Is it possible to set ylim values for a boxplot different from the default ones for a given dataset plot?

答:
You use the axes-approach without having an axes-object.

Try (figure-based approach):

```<code>import matplotlib.pyplot as plt
plt.ylim([-5,5])
</code>```

or probably better in your case:

```<code>ax = sns.boxplot (y=y)
ax.set_ylim([-5, 5])      # function! your code-sample is wrong here!
</code>```

The docs here show the return-value of sns.boxplot.

And here is the general overview of matplotlib's objects.

Title: setting ylim on seaborn boxplot

Body:
Is it possible to set ylim parameters on a seaborn boxplot?

as an example:

y = np.random.randn(300)
sns.boxplot (y=y)

Displays

boxplot

but if I try

ax.set_ylim=(-5, 5)

It makes no difference. Is it possible to set ylim values for a boxplot different from the default ones for a given dataset plot?

Body:
You use the axes-approach without having an axes-object.

Try (figure-based approach):

import matplotlib.pyplot as plt
plt.ylim([-5,5])

or probably better in your case:

ax = sns.boxplot (y=y)
ax.set_ylim([-5, 5])      # function! your code-sample is wrong here!

The docs here show the return-value of sns.boxplot.

And here is the general overview of matplotlib's objects.


问:
Laravel 5.4 pusher error
I am using pusher in Laravel 5.4 but I'm getting following error:

WebSocket connection to 'ws://ws.pusherapp.com/app/731e32c5f123456298e?protocol=7&client=js&version=4.1.0&flash=false' failed: WebSocket is closed before the connection is established.

Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":4001,"message":"Did you forget to specify the cluster when creating the Pusher instance?  App key 731e32c5f123456298e does not exist in this cluster."}}}

答: It looks like you've copied your pusher app_key incorrectly. Pusher app keys typically have 20 characters, yours has 19.

Title: Laravel 5.4 pusher error


问:
UIButton animation view
I am new developer in iPhone.

I want to create uibutton.

When I click the button, then the button will be flash like as below.

How to create the flash, when I click my button?

答:
There is a property of UIButton named showsTouchWhenHighlighted. If you set the property to YES, it will show the glow when you touch the button. It's default value is NO.

[yourButton setShowsTouchWhenHighlighted:YES];

Title: UIButton animation view


问:
Cloudant create views to count every last values array fields
I have many json documents stored in a Cloudant database. The structure of document:

```<code>{
  "_id": "00229e31d5751d337abf409a4bd75492",
  "_rev": "1-d95d7ad32264d233453a0436b1557e7d",
  "timestamp": "2017-07-04T21:28:46.886Z",
  "APIresponse": {
    "intents": [
      {
        "intent": "greetings",
        "confidence": 1
      },
      {
        "intent": "machineBusy",
        "confidence": 0
      },
      {
        "intent": "set_weights",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesPAAmount",
        "confidence": 0
      },
      {
        "intent": "chat",
        "confidence": 0
      },
      {
        "intent": "feedback-no",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesWhatsnew",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesChildren",
        "confidence": 0
      },
      {
        "intent": "thanks",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesPAvsFederal",
        "confidence": 0
      }
    ],
    "entities": [],
    "input": {
      "text": "hey"
    },
    "output": {
      "text": [
        "Hey there!",
        "How a beautiful day to train :) Do you agree #firstName?"
      ],
      "nodes_visited": [
        "Greetings",
        "Initial greetings",
        "node_2_1495711348295"
      ],
      "error": "SpelEvaluationException when evaluating DialogNode Id [check PROFILING interrupted ASPFINDER]. Condition [$trainingContext.status == \"no_tp\" && $aspFinder.dob != null || $aspFinder.height != null || $aspFinder.weight != null || $aspFinder.impedIsPresent != null || $aspFinder.goal != null || $aspFinder.timesAWeek != null || $aspFinder.duration != null || $aspFinder.location != null || $aspFinder.level != null || $userContext.height != null] evaluated to FALSE.\norg.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'weight' cannot be found on null\n",
      "log_messages": [
        {
          "level": "err",
          "msg": "SpelEvaluationException when evaluating DialogNode Id [check PROFILING interrupted ASPFINDER]. Condition [$trainingContext.status == \"no_tp\" && $aspFinder.dob != null || $aspFinder.height != null || $aspFinder.weight != null || $aspFinder.impedIsPresent != null || $aspFinder.goal != null || $aspFinder.timesAWeek != null || $aspFinder.duration != null || $aspFinder.location != null || $aspFinder.level != null || $userContext.height != null] evaluated to FALSE.\norg.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'weight' cannot be found on null\n"
        }
      ]
    },
    "context": {
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "node_2_1495711348295"
          }
        ],
        "dialog_request_counter": 5,
        "dialog_turn_counter": 5,
        "_node_output_map": {
          "node_3_1495711396477": [
            0
          ],
          "node_1_1495037449418": [
            0,
            0,
            1
          ],
          "node_12_1494424156763": [
            0,
            3,
            0,
            1,
            2,
            4
          ],
          "in exercise": [
            0
          ],
          "Workout Feedback": [
            0,
            2,
            1,
            0,
            3
          ],
          "Greetings": [
            0
          ],
          "node_2_1495711348295": [
            0,
            2,
            1,
            0
          ]
        }
      },
      "repeat": false,
      "lastMsg": [
        "Great job!",
        "We're done for today training! Great job :)"
      ],
      "conversation_id": "919d2d6b-e085-4fbe-bd12-19486aa0394e",
      "last": {
        "trainingContext": {
          "status": "no_workout",
          "suggested_workout_id": "W-fb2038d7d45a48a6af844a53f52a1759-T-74e57d317b9649feb5f024c049766fd7-F-technogym"
        },
        "notify_ui": "workout_closed",
        "output": {
          "nodes_visited": [
            "node_9_1494423774989",
            "node_1_1494427286758",
            "node_12_1494424156763"
          ],
          "text": [
            "Great job!",
            "We're done for today training! Great job :)"
          ],
          "log_messages": []
        }
      },
      "_currentSession": {
        "current_exe": 7
      },
      "currentSession": {
        "feedback": 5
      },
      "_timestamp": "2017-07-04T21:28:46.561Z",
      "trainingContext": {
        "status": "no_workout",
        "suggested_workout_id": "W-fb2038d7d45a48a6af844a53f52a1759-T-74e57d317b9649feb5f024c049766fd7-F-technogym"
      },
      "userContext": {
        "height": 160,
        "userID": "e37e39f4-61ba-41da-a356-2c6cbfae8392",
        "lastName": "#lastName",
        "facilityId": "4419597c-b63e-4358-b8ba-cc388bb192c3",
        "weight": 56,
        "userToken": "MjAxNzA3MDQyMTI4MzR8MzQyYzJkZmEyNGVkNGZlZDhiOWU5NDg0NWE1YzAxNTJ8ZWMxZDM4ZDdkMzU5NDhkMGE2MGNkOGMwYjhmYjlkZjl8MXxXLiBFdXJvcGUgU3RhbmRhcmQgVGltZXxpdC1JVHxlMzdlMzlmNDYxYmE0MWRhYTM1NjJjNmNiZmFlODM5Mnx8fHwxfDF8MHwxMDB8fHw1OHw2ODk0fDB8Y29tLm15d2VsbG5lc3M1.BC8BBB1E2066444DEA5F5E1F42627CF6443F3077",
        "firstName": "#firstName",
        "dob": "03/07/1986"
      }
    }
  }
}
</code>```

The value odf the json I'm interested in is the always the last in the array field APIresponse.outout.nodes_visited. To be more specific, I would like to have a structure in which I obtain the count of every last value of the array field APIresponse.outout.nodes_visited and the associated value linked to that count (the name of count).

I usually use selector to query Cloudant but it seems that it does'nt provide a way to obtain the specific count I'm looking for.

I have tried to create a map reduce function in a design document but I have been not able to succeed.

Then the questions are:

How can I access to the last element of an array field in Cloudant?

How can I obtain the total count of every last element of the array in my database?

Thank you for any help,

Filippo

答:
You can do this with a map-reduce view. Firstly, key your emit with the field from the array with a value of 1:

```<code>function(doc) {
    if (doc && doc.APIresponse &&
        doc.APIresponse.output && doc.APIresponse.output.nodes_visited){
        var arr = doc.APIresponse.output.nodes_visited;
        emit(arr[arr.length-1], 1);
    }
}
</code>```

and pick the built-in _count reduce function.

You should now be able to see all your nodes visited, with totals using something like

```<code>curl 'https://USER:PASS@ACCOUNT.cloudant.com/DB/_design/DDOC/_view/VIEWNAME?group=true'
</code>```

You can see your example data loaded in one of my databases:

https://skruger.cloudant.com/testdb -- it's open for reading.

I put the above suggested view function in, and here's the query:

```<code>curl 'https://skruger.cloudant.com/testdb/_design/ddoc/_view/nodes?group=true'
{"rows":[
    {"key":"ask exercise feedback","value":1},
    {"key":"Assign workout","value":2},
    {"key":"Capabilities","value":1},
    {"key":"Feedback_tester","value":1},
    {"key":"First Exercise","value":2},
    {"key":"mark exercise done","value":1},
    {"key":"no_tp","value":8},
    {"key":"node_1_1495716162431","value":10},
    {"key":"node_2_1495711348295","value":1},
    {"key":"node_21_1494245522737","value":1},
    {"key":"node_26_1494249967653","value":1},
    {"key":"node_3_1495716340965","value":2},
    {"key":"node_3_1495922533369","value":2},
    {"key":"node_4_1494233636522","value":2},
    {"key":"node_6_1493835340035","value":1},
    {"key":"node_7_1493835487968","value":1},
    {"key":"node_8_1492030091650","value":1},
    {"key":"node_8_1494235961152","value":2},
    {"key":"node_9_1495711958382","value":1},
    {"key":"pr exit service fail","value":7},
    {"key":"profiling - ending","value":8},
    {"key":"profiling - question duration","value":7},
    {"key":"profiling - question goal","value":7},
    {"key":"profiling - question impediments","value":7},
    {"key":"profiling - question level","value":7},
    {"key":"profiling - question location","value":7},
    {"key":"profiling - question timesWeek","value":7},
    {"key":"show next exercise","value":2}
]}
</code>```

Body:
I have many json documents stored in a Cloudant database. The structure of document:

{
  "_id": "00229e31d5751d337abf409a4bd75492",
  "_rev": "1-d95d7ad32264d233453a0436b1557e7d",
  "timestamp": "2017-07-04T21:28:46.886Z",
  "APIresponse": {
    "intents": [
      {
        "intent": "greetings",
        "confidence": 1
      },
      {
        "intent": "machineBusy",
        "confidence": 0
      },
      {
        "intent": "set_weights",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesPAAmount",
        "confidence": 0
      },
      {
        "intent": "chat",
        "confidence": 0
      },
      {
        "intent": "feedback-no",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesWhatsnew",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesChildren",
        "confidence": 0
      },
      {
        "intent": "thanks",
        "confidence": 0
      },
      {
        "intent": "faqGuidelinesPAvsFederal",
        "confidence": 0
      }
    ],
    "entities": [],
    "input": {
      "text": "hey"
    },
    "output": {
      "text": [
        "Hey there!",
        "How a beautiful day to train :) Do you agree #firstName?"
      ],
      "nodes_visited": [
        "Greetings",
        "Initial greetings",
        "node_2_1495711348295"
      ],
      "error": "SpelEvaluationException when evaluating DialogNode Id [check PROFILING interrupted ASPFINDER]. Condition [$trainingContext.status == \"no_tp\" && $aspFinder.dob != null || $aspFinder.height != null || $aspFinder.weight != null || $aspFinder.impedIsPresent != null || $aspFinder.goal != null || $aspFinder.timesAWeek != null || $aspFinder.duration != null || $aspFinder.location != null || $aspFinder.level != null || $userContext.height != null] evaluated to FALSE.\norg.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'weight' cannot be found on null\n",
      "log_messages": [
        {
          "level": "err",
          "msg": "SpelEvaluationException when evaluating DialogNode Id [check PROFILING interrupted ASPFINDER]. Condition [$trainingContext.status == \"no_tp\" && $aspFinder.dob != null || $aspFinder.height != null || $aspFinder.weight != null || $aspFinder.impedIsPresent != null || $aspFinder.goal != null || $aspFinder.timesAWeek != null || $aspFinder.duration != null || $aspFinder.location != null || $aspFinder.level != null || $userContext.height != null] evaluated to FALSE.\norg.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'weight' cannot be found on null\n"
        }
      ]
    },
    "context": {
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "node_2_1495711348295"
          }
        ],
        "dialog_request_counter": 5,
        "dialog_turn_counter": 5,
        "_node_output_map": {
          "node_3_1495711396477": [
            0
          ],
          "node_1_1495037449418": [
            0,
            0,
            1
          ],
          "node_12_1494424156763": [
            0,
            3,
            0,
            1,
            2,
            4
          ],
          "in exercise": [
            0
          ],
          "Workout Feedback": [
            0,
            2,
            1,
            0,
            3
          ],
          "Greetings": [
            0
          ],
          "node_2_1495711348295": [
            0,
            2,
            1,
            0
          ]
        }
      },
      "repeat": false,
      "lastMsg": [
        "Great job!",
        "We're done for today training! Great job :)"
      ],
      "conversation_id": "919d2d6b-e085-4fbe-bd12-19486aa0394e",
      "last": {
        "trainingContext": {
          "status": "no_workout",
          "suggested_workout_id": "W-fb2038d7d45a48a6af844a53f52a1759-T-74e57d317b9649feb5f024c049766fd7-F-technogym"
        },
        "notify_ui": "workout_closed",
        "output": {
          "nodes_visited": [
            "node_9_1494423774989",
            "node_1_1494427286758",
            "node_12_1494424156763"
          ],
          "text": [
            "Great job!",
            "We're done for today training! Great job :)"
          ],
          "log_messages": []
        }
      },
      "_currentSession": {
        "current_exe": 7
      },
      "currentSession": {
        "feedback": 5
      },
      "_timestamp": "2017-07-04T21:28:46.561Z",
      "trainingContext": {
        "status": "no_workout",
        "suggested_workout_id": "W-fb2038d7d45a48a6af844a53f52a1759-T-74e57d317b9649feb5f024c049766fd7-F-technogym"
      },
      "userContext": {
        "height": 160,
        "userID": "e37e39f4-61ba-41da-a356-2c6cbfae8392",
        "lastName": "#lastName",
        "facilityId": "4419597c-b63e-4358-b8ba-cc388bb192c3",
        "weight": 56,
        "userToken": "MjAxNzA3MDQyMTI4MzR8MzQyYzJkZmEyNGVkNGZlZDhiOWU5NDg0NWE1YzAxNTJ8ZWMxZDM4ZDdkMzU5NDhkMGE2MGNkOGMwYjhmYjlkZjl8MXxXLiBFdXJvcGUgU3RhbmRhcmQgVGltZXxpdC1JVHxlMzdlMzlmNDYxYmE0MWRhYTM1NjJjNmNiZmFlODM5Mnx8fHwxfDF8MHwxMDB8fHw1OHw2ODk0fDB8Y29tLm15d2VsbG5lc3M1.BC8BBB1E2066444DEA5F5E1F42627CF6443F3077",
        "firstName": "#firstName",
        "dob": "03/07/1986"
      }
    }
  }
}

The value odf the json I'm interested in is the always the last in the array field APIresponse.outout.nodes_visited. To be more specific, I would like to have a structure in which I obtain the count of every last value of the array field APIresponse.outout.nodes_visited and the associated value linked to that count (the name of count).

I usually use selector to query Cloudant but it seems that it does'nt provide a way to obtain the specific count I'm looking for.

I have tried to create a map reduce function in a design document but I have been not able to succeed.

Then the questions are:

How can I access to the last element of an array field in Cloudant?

How can I obtain the total count of every last element of the array in my database?

Thank you for any help,

Filippo

Body:
You can do this with a map-reduce view. Firstly, key your emit with the field from the array with a value of 1:

function(doc) {
    if (doc && doc.APIresponse &&
        doc.APIresponse.output && doc.APIresponse.output.nodes_visited){
        var arr = doc.APIresponse.output.nodes_visited;
        emit(arr[arr.length-1], 1);
    }
}

and pick the built-in _count reduce function.

You should now be able to see all your nodes visited, with totals using something like

curl 'https://USER:PASS@ACCOUNT.cloudant.com/DB/_design/DDOC/_view/VIEWNAME?group=true'

You can see your example data loaded in one of my databases:

https://skruger.cloudant.com/testdb -- it's open for reading.

I put the above suggested view function in, and here's the query:

curl 'https://skruger.cloudant.com/testdb/_design/ddoc/_view/nodes?group=true'
{"rows":[
    {"key":"ask exercise feedback","value":1},
    {"key":"Assign workout","value":2},
    {"key":"Capabilities","value":1},
    {"key":"Feedback_tester","value":1},
    {"key":"First Exercise","value":2},
    {"key":"mark exercise done","value":1},
    {"key":"no_tp","value":8},
    {"key":"node_1_1495716162431","value":10},
    {"key":"node_2_1495711348295","value":1},
    {"key":"node_21_1494245522737","value":1},
    {"key":"node_26_1494249967653","value":1},
    {"key":"node_3_1495716340965","value":2},
    {"key":"node_3_1495922533369","value":2},
    {"key":"node_4_1494233636522","value":2},
    {"key":"node_6_1493835340035","value":1},
    {"key":"node_7_1493835487968","value":1},
    {"key":"node_8_1492030091650","value":1},
    {"key":"node_8_1494235961152","value":2},
    {"key":"node_9_1495711958382","value":1},
    {"key":"pr exit service fail","value":7},
    {"key":"profiling - ending","value":8},
    {"key":"profiling - question duration","value":7},
    {"key":"profiling - question goal","value":7},
    {"key":"profiling - question impediments","value":7},
    {"key":"profiling - question level","value":7},
    {"key":"profiling - question location","value":7},
    {"key":"profiling - question timesWeek","value":7},
    {"key":"show next exercise","value":2}
]}


问:
Remove single br in paragraph but not double br?
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

```<code>p br {display:none}
</code>```

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

```<code>p br { content: ' '; }
</code>```

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

```<code><p> oremipsum lorem<br/>
orem blalgr<br/><br/>
loremg grthrt
</p>
</code>```

答:
If the other contents of the p is just text, you can replace all single br using regular expressions:

var $p = $("p");
console.log($p.html());
$p.html($p.html().replace(/(\s*[^>\s]\s*)
\s*(?!\s*
)/gi, '$1'));
console.log($p.html());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  oremipsum lorem    <br/>
  orem blalgr <br/>  <br/>
  loremg grthrt
</p></code>```

Body:
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

p br {display:none}

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

p br { content: ' '; }

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

 oremipsum lorem

orem blalgr

loremg grthrt

Body:
If the other contents of the p is just text, you can replace all single br using regular expressions:

var $p = $("p");
console.log($p.html());
$p.html($p.html().replace(/(\s*[^>\s]\s*)<br>\s*(?!\s*<br>)/gi, '$1'));
console.log($p.html());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  oremipsum lorem    <br/>
  orem blalgr <br/>  <br/>
  loremg grthrt
</p>


问:
How to implement a listener to check i have read a text file and ignore it
I have written a small program to monitor a folder. I have not used the folderWatcher in .NET because multiple files can be added to the folder simultaneously and folderWatcher can sometimes miss them. Basically, I am checking the folder for a file that starts and ends with certain characters. The timer is checking the folder every 10 seconds.

My issue: my program will read the same file multiple times. I need to set a condition or have a listener check if the file has already been read to ignore it.

The problem is I'm not sure how to go about this, can anyone shed some light on the best way to maybe implement a listener that will check if I have read this file and ignore it and move onto the next file, please?

I couldn't find another thread on here that helped me with the answer I am looking for.

答:
Basicly, you sould keep somewhere (maybe in a text file) the last scan date and can check the creation time of files.

```<code>    void ReadFiles()
    {
        try
        {
            DateTime lastScanDate = GetLastScanDate();

            SetLastScanDate();
            foreach (string filePath in System.IO.Directory.GetFiles(@"C:\Users\cozogul\Desktop\test"))
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                if (fi.CreationTime >= lastScanDate)
                {
                    //read file
                }
                else
                {
                    //Don't read file.
                }
            }
        }
        catch (Exception ex)
        {
            //Log your error
        }
    }

    DateTime GetLastScanDate()
    {
        if (System.IO.File.Exists(@"C:\Users\cozogul\Desktop\test\datefile.txt"))
        {
            using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\Users\cozogul\Desktop\test\datefile.txt", System.IO.FileMode.Open))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string dateString = System.Text.Encoding.UTF8.GetString(buffer);
                DateTime date = Convert.ToDateTime(dateString);
                return date;
            }
        }
        //Will read all files.
        else
            return DateTime.MinValue;
    }

    public void SetLastScanDate()
    {
        using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\Users\cozogul\Desktop\test\datefile.txt", System.IO.FileMode.Create))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString());
            fs.Write(buffer, 0, buffer.Length);
        }
    }
</code>```

Or you can keep filenames in a file or a database table to check a file is before read.

Body:
Basicly, you sould keep somewhere (maybe in a text file) the last scan date and can check the creation time of files.

    void ReadFiles()
    {
        try
        {
            DateTime lastScanDate = GetLastScanDate();

            SetLastScanDate();
            foreach (string filePath in System.IO.Directory.GetFiles(@"C:\Users\cozogul\Desktop\test"))
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                if (fi.CreationTime >= lastScanDate)
                {
                    //read file
                }
                else
                {
                    //Don't read file.
                }
            }
        }
        catch (Exception ex)
        {
            //Log your error
        }
    }

    DateTime GetLastScanDate()
    {
        if (System.IO.File.Exists(@"C:\Users\cozogul\Desktop\test\datefile.txt"))
        {
            using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\Users\cozogul\Desktop\test\datefile.txt", System.IO.FileMode.Open))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string dateString = System.Text.Encoding.UTF8.GetString(buffer);
                DateTime date = Convert.ToDateTime(dateString);
                return date;
            }
        }
        //Will read all files.
        else
            return DateTime.MinValue;
    }

    public void SetLastScanDate()
    {
        using (System.IO.FileStream fs = new System.IO.FileStream(@"C:\Users\cozogul\Desktop\test\datefile.txt", System.IO.FileMode.Create))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString());
            fs.Write(buffer, 0, buffer.Length);
        }
    }

Or you can keep filenames in a file or a database table to check a file is before read.