问:
setting legend only for one of the marginal plots in seaborn
I am creating a JointGrid plot using seaborn.

```<code>import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20,label='X')
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(prop=legend_properties,loc='upper right')
</code>```

I get this:

I would like to get rid of the legend within the vertical marginal plot (the one on the right side) but keep the one for the horizontal margin.
how to achieve that?

EDIT: The solution from @ImportanceOfBeingErnest works fine for one plot. However, if I repeat it in a for loops something unexpected happens.
I still get a legend in the upper plot and that is unexpected.
How to get rid of it?

The following code:

```<code>import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
LABEL_LIST=['x','Y','Z']
for n in range(0,3):

    g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20,label=LABEL_LIST[n])
    g=g.plot_joint(plt.scatter,label=LABEL_LIST[n])

    legend_properties = {'weight':'bold','size':8}
    legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

    legendSide=g.ax_marg_y.legend(labels=[LABEL_LIST[n]],prop=legend_properties,loc='upper right')
</code>```

gives:

which is almost perfect, byt I need to get rid of the last legend entry in the plo on the right.

答:
You may decide not to give any label to the marginals, but instead add the label when creating the legend inside the top marginal axes.

```<code>import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',
                   kde=True,hist=False,rug=True,bins=20)
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(labels=["x"],
                              prop=legend_properties,loc='upper right')

plt.show()
</code>```

The solution is the same for a plot in a loop.

```<code>import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
LABEL_LIST=['x','Y','Z']
for n in range(0,3):
    g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20)
    g=g.plot_joint(plt.scatter,label=LABEL_LIST[n])

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')
legendSide=g.ax_marg_x.legend(labels=LABEL_LIST,prop=legend_properties,loc='upper right')

plt.show()
</code>```

Body:
I am creating a JointGrid plot using seaborn.

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20,label='X')
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(prop=legend_properties,loc='upper right')

I get this:

I would like to get rid of the legend within the vertical marginal plot (the one on the right side) but keep the one for the horizontal margin.
how to achieve that?

EDIT: The solution from @ImportanceOfBeingErnest works fine for one plot. However, if I repeat it in a for loops something unexpected happens.
I still get a legend in the upper plot and that is unexpected.
How to get rid of it?

The following code:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
LABEL_LIST=['x','Y','Z']
for n in range(0,3):

    g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20,label=LABEL_LIST[n])
    g=g.plot_joint(plt.scatter,label=LABEL_LIST[n])

    legend_properties = {'weight':'bold','size':8}
    legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

    legendSide=g.ax_marg_y.legend(labels=[LABEL_LIST[n]],prop=legend_properties,loc='upper right')

gives:

which is almost perfect, byt I need to get rid of the last legend entry in the plo on the right.

Body:
You may decide not to give any label to the marginals, but instead add the label when creating the legend inside the top marginal axes.

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',
                   kde=True,hist=False,rug=True,bins=20)
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(labels=["x"],
                              prop=legend_properties,loc='upper right')

plt.show()

The solution is the same for a plot in a loop.

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
LABEL_LIST=['x','Y','Z']
for n in range(0,3):
    g=g.plot_marginals(sns.distplot,color='black',kde=True,hist=False,rug=True,bins=20)
    g=g.plot_joint(plt.scatter,label=LABEL_LIST[n])

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')
legendSide=g.ax_marg_x.legend(labels=LABEL_LIST,prop=legend_properties,loc='upper right')

plt.show()


来源: stackexchange

问:
Plotting multiple bar plots on same y-axis but each on separate x-axis in ggplot2 for count data
I have some count variables against which I want to make bar-plots on the same y-axis but I have no grouping variable. Something like the following plot

```<code>B <- 25

iter_M1
[1] 5 13 14 11  7  8 10 14 10  5  7 13 10 12  4  5  9  6  5 12  8  8  7 11  9

max_M1 <- max(iter_M1)

count_M1 <- integer(max_M1)
for(i in 1:max_M1)
 {
    for(j in 1:B)
     {
        if(iter_M1[j] == i)
        count_M1[i] = count_M1[i] +1
     }
 }

 count_M1
 [1] 0 0 0 1 4 1 3 3 2 3 2 2 2 2

 df <- data.frame(x = 1:max_M1, y = count_M1)
 p_M1 <-ggplot(data=df, aes(x=x, y=y)) +  geom_bar(stat="identity")
 p_M1
</code>```

This results in a plot like this

and another similar variable

```<code>iter_M2
[1] 3 1 3 2 6 3 4 4 3 7 4 2 2 3 4 3 4 4 1 3 7 3 2 4 2

max_M2 <- max( iter_M2)
count_M2  <- integer(max_M2)
for(i in 1:max_M2)
{
 for(j in 1:B)
 {
 if(iter_M2[j] == i)
 count_M2[i] = count_M2[i] +1
 }
}

count_M2
[1] 2 5 8 7 0 1 2 df1 <- data.frame(x1 = 1:max_M2, y1 = count_M2)

p_M2 <-ggplot(data=df1, aes(x=x1, y=y1)) +
geom_bar(stat="identity") p_M2
</code>```

which results in a second plot as

and similar variables like these... How can I plot this data side by side. Also the way I'hv generated data currently, there is no common y-axis for all x-axis. Are there some suggestion to generate such a plot or dataset in other format to achive the requried plot.

答:
As suggested in the comments, making a factor (class) is the easiest way, allowing you to facet the plot.

But you seem explicitly just to want to have the same y-axis. This is achievable with the scale limits. For example, generate a vector with the limits based on max and then use this in your plots.

```<code>ylimits <- c(0, max(c(count_M1, count_M2)))

p_M1 + ylim(ylimits)

p_M2 + ylim(ylimits)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some count variables against which I want to make bar-plots on the same y-axis but I have no grouping variable. Something like the following plot

B <- 25

iter_M1
[1] 5 13 14 11  7  8 10 14 10  5  7 13 10 12  4  5  9  6  5 12  8  8  7 11  9

max_M1 <- max(iter_M1)

count_M1 <- integer(max_M1)
for(i in 1:max_M1)
 {
    for(j in 1:B)
     {
        if(iter_M1[j] == i)
        count_M1[i] = count_M1[i] +1
     }
 }

 count_M1
 [1] 0 0 0 1 4 1 3 3 2 3 2 2 2 2

 df <- data.frame(x = 1:max_M1, y = count_M1)
 p_M1 <-ggplot(data=df, aes(x=x, y=y)) +  geom_bar(stat="identity")
 p_M1

This results in a plot like this

and another similar variable

iter_M2
[1] 3 1 3 2 6 3 4 4 3 7 4 2 2 3 4 3 4 4 1 3 7 3 2 4 2

max_M2 <- max( iter_M2)
count_M2  <- integer(max_M2)
for(i in 1:max_M2)
{
 for(j in 1:B)
 {
 if(iter_M2[j] == i)
 count_M2[i] = count_M2[i] +1
 }
}

count_M2
[1] 2 5 8 7 0 1 2 df1 <- data.frame(x1 = 1:max_M2, y1 = count_M2)

p_M2 <-ggplot(data=df1, aes(x=x1, y=y1)) +
geom_bar(stat="identity") p_M2

which results in a second plot as

and similar variables like these... How can I plot this data side by side. Also the way I'hv generated data currently, there is no common y-axis for all x-axis. Are there some suggestion to generate such a plot or dataset in other format to achive the requried plot.

Body:
As suggested in the comments, making a factor (class) is the easiest way, allowing you to facet the plot.

But you seem explicitly just to want to have the same y-axis. This is achievable with the scale limits. For example, generate a vector with the limits based on max and then use this in your plots.

ylimits <- c(0, max(c(count_M1, count_M2)))

p_M1 + ylim(ylimits)

p_M2 + ylim(ylimits)


问:
listview in dialougbox shows nothing
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

```<code> public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }
</code>```

答:
Try this</p>

```<code>public void shw(View view) {

    Dialog dialog=new Dialog(MainActivity.this);
    dialog.setTitle("Dialog Title");
    dialog.setContentView(R.layout.custadd);
    ListView lv=(ListView) dialog.findViewById(R.id.listv);
    String s1[]={"sunday","monday","tuesday"};

     ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1, s1 );
    lv.setAdapter(arrayAdapter);
    dialog.show();

}
</code>```

Title: listview in dialougbox shows nothing

Body:
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

 public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }

Body:
Try this

public void shw(View view) {

    Dialog dialog=new Dialog(MainActivity.this);
    dialog.setTitle("Dialog Title");
    dialog.setContentView(R.layout.custadd);
    ListView lv=(ListView) dialog.findViewById(R.id.listv);
    String s1[]={"sunday","monday","tuesday"};

     ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1, s1 );
    lv.setAdapter(arrayAdapter);
    dialog.show();

}


问:
Hibernate not generating proper insert statement after adding a new column

For a table, I added a new column

In hibernate mapping file, I ensured that, the new column is added

But at runtime, hibernate is generating insert statement, which does not include the new column

For example,

old hibernate mapping definition:

```<code><joined-subclass name="MyClass" extends="MySuperClass" table="tableName">
        <property name="propA" column="colA" />
        <property name="propB" column="colB" />
        <property name="propC" column="colC" />
        <property name="propD" column="colD" />
        <property name="propE" column="colE" />
    </joined-subclass>
</code>```

new hibernate mapping definition:

```<code><joined-subclass name="MyClass" extends="MySuperClass" table="tableName">
        <property name="propA" column="colA" />
        <property name="propB" column="colB" />
        <property name="propC" column="colC" />
        <property name="propD" column="colD" />
        <property name="propE" column="colE" />
        <component name="propF" class="compClass">
            <property name="compName"  column="colF" />
        </component>
    </joined-subclass>
</code>```

Basically the insert statement is not taking colF into consideration.

答:
You need to refer the component class in entity class and populate component and then set in the main entity class like:

```<code>        Student student = new Student();
    student.setStudentName("HarKrishan");
    Address address = new Address();
    address.setCity("HMR");
    student.setStudentAddress(address);
    session.save(student);
</code>```

Body:
For a table, I added a new column

In hibernate mapping file, I ensured that, the new column is added

But at runtime, hibernate is generating insert statement, which does not include the new column

For example,

old hibernate mapping definition:

<joined-subclass name="MyClass" extends="MySuperClass" table="tableName">
        <property name="propA" column="colA" />
        <property name="propB" column="colB" />
        <property name="propC" column="colC" />
        <property name="propD" column="colD" />
        <property name="propE" column="colE" />
    </joined-subclass>

new hibernate mapping definition:

<joined-subclass name="MyClass" extends="MySuperClass" table="tableName">
        <property name="propA" column="colA" />
        <property name="propB" column="colB" />
        <property name="propC" column="colC" />
        <property name="propD" column="colD" />
        <property name="propE" column="colE" />
        <component name="propF" class="compClass">
            <property name="compName"  column="colF" />
        </component>
    </joined-subclass>

Basically the insert statement is not taking colF into consideration.

Body:
You need to refer the component class in entity class and populate component and then set in the main entity class like:

        Student student = new Student();
    student.setStudentName("HarKrishan");
    Address address = new Address();
    address.setCity("HMR");
    student.setStudentAddress(address);
    session.save(student);


问:
PHP line break inside of cell remove qoute
This is my PHP

```<code>$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}
</code>```

The result is

```<code>//this is inside of cell
sample
"sample
"sample
</code>```

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

答:
I think you can use the php function trim like this:

```<code>$val = "";
foreach($data as $v){
  if( ''==$val) {
      $val .= trim('"' . $v . "\n" . '"','"');
  }else{
      $val .= '"' . $v . "\n" . '"','"';
  }
}
</code>```

Body:
This is my PHP

$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}

The result is

//this is inside of cell
sample
"sample
"sample

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

Body:
I think you can use the php function trim like this:

$val = "";
foreach($data as $v){
  if( ''==$val) {
      $val .= trim('"' . $v . "\n" . '"','"');
  }else{
      $val .= '"' . $v . "\n" . '"','"';
  }
}


问:
Directive inside templateUrl of another directive and passing attribute
I'm having two directives and I'm trying to call one directive inside another directive's templateUrl with some attribute but I'm not able to get the compiled attribute value in the second directive. Code is like this:

1st directive

```<code>app.directive('myDir', function() {
   return {
     link: function(scope, element, attrs, controller) {
         scope.myVal='hello';
     },
     templateUrl: 'directive1.html',
     scope: {}
  }
</code>```

directive.html

```<code><div>
   <child-dir attrval="{{myVal}}"></child-dir>
<div>
</code>```

2nd directive

```<code>app.directive('childDir', function() {
       return {
         templateUrl: template(element,attrs) {
             alert(attrs.attrval);
         },
         scope: {}
      }
</code>```

Here, attrs.attrval is coming like this {{myVal}}.
but I want the value hello. Can anyone help me?
Please note two things here:

1) I'm using templateUrl.
2) I'm passing a scope variable's value as an attribute to the child directive.

答:
I had the same problem and finally found the solution (probably not the best, but it's working for me). Your example is a litte bit different from mine, but I suppose in your example would be:

Parent directive and directive.html equals, but child directive:

```<code>app.directive('childDir', function() {
   return {
     templateUrl: template(element,attrs) {
           attrs.$observe("attrval", function(){
             alert(attrs.attrval);
           });
     },
     scope: {}
  }
</code>```

When template is set in parent directive the value is not set yet, but child directive is trying to use it. With 'observe', child directive can force refresh when attrval is really set.

If not works for you, tell me and I will post parts of my code in case it would be useful.

Body:
I'm having two directives and I'm trying to call one directive inside another directive's templateUrl with some attribute but I'm not able to get the compiled attribute value in the second directive. Code is like this:

1st directive

app.directive('myDir', function() {
   return {
     link: function(scope, element, attrs, controller) {
         scope.myVal='hello';
     },
     templateUrl: 'directive1.html',
     scope: {}
  }

directive.html

   <child-dir attrval="{{myVal}}"></child-dir>

2nd directive

app.directive('childDir', function() {
       return {
         templateUrl: template(element,attrs) {
             alert(attrs.attrval);
         },
         scope: {}
      }

Here, attrs.attrval is coming like this {{myVal}}.
but I want the value hello. Can anyone help me?
Please note two things here:

1) I'm using templateUrl.
2) I'm passing a scope variable's value as an attribute to the child directive.

Body:
I had the same problem and finally found the solution (probably not the best, but it's working for me). Your example is a litte bit different from mine, but I suppose in your example would be:

Parent directive and directive.html equals, but child directive:

app.directive('childDir', function() {
   return {
     templateUrl: template(element,attrs) {
           attrs.$observe("attrval", function(){
             alert(attrs.attrval);
           });
     },
     scope: {}
  }

When template is set in parent directive the value is not set yet, but child directive is trying to use it. With 'observe', child directive can force refresh when attrval is really set.

If not works for you, tell me and I will post parts of my code in case it would be useful.


问:
Ansible lineinfile not copying last line to server
I am trying to copy a secret Python settings file from a settings server to the production environment. Since the settings contains passwords I am using Ansible Vault.

My playbook looks like this:

```<code>---
- hosts: production
  tasks:
  - include_vars: settings.yml
  - name: Set properties
    lineinfile:
      dest: ~/temp/deploy
      regexp: "{{ item.split('=')[0] }}\\s*="
      line: "{{ item }}"
    with_lines: echo "{{ config }}"
</code>```

And my settings.yml looks like this:

```<code>config:  |
  ASD='DEF'
  PROGRAM='PROG'
  PASSWORD='MAGNUS123'
  TEMP='TEST'
</code>```

However when I run the playbook I get the file:

```<code>ASD='DEF'
PROGRAM='PROG'
PASSWORD='MAGNUS123'
</code>```

Even though Ansible claims the last line is also copied:

```<code>changed: [ssh.pythonanywhere.com] => (item=ASD='DEF' )
changed: [ssh.pythonanywhere.com] => (item=PROGRAM='PROG')
changed: [ssh.pythonanywhere.com] => (item=PASSWORD='MAGNUS123')
changed: [ssh.pythonanywhere.com] => (item=TEMP='TEST')
changed: [ssh.pythonanywhere.com] => (item=)
</code>```

What am I doing wrong to cause this?

Ansible version:

```<code>ansible --version
ansible 2.4.1.0
  config file = None
  ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.2 (default, Jul 17 2017, 16:44:45) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]
</code>```

答:
You are doing something completely unnecessary (skip to the bottom), but let's give it a try...

What am I doing wrong to cause this?

If you run the following:

```<code>- shell: echo "{{ config }}" | hexdump
  register: echo

- debug:
    var: echo.stdout
</code>```

You'll see that the output ends with:

```<code>54 45 4d 50 3d 27 54 45 53 54 27 0a 0a
</code>```

which is TEMP='TEST' followed by two newline characters. When used in with_lines loop this will cause two iterations -- the last one with an empty value passed to item.

Now, think what happens to your arguments when item is empty:

regexp becomes \\s*= and line is empty.

In other words you instruct Ansible to replace some line containing = with an empty line.

If the starting point is an empty file, Ansible does the following:

Adds ASD='DEF' line.

Adds PROGRAM='PROG' line.

Adds PASSWORD='MAGNUS123' line.

Adds TEMP='TEST' line.

Replaces a line with = with an empty line (in fact it happens to be the very last line).

And that is the result you get: three lines and an empty one.

You can also arrive at the same conclusion simply running using debug module to display the values of "{{ item.split('=')[0] }}\\s*=" and {{ item }} which you pass to the lineinfile arguments.

echo has -n argument ("Do not print the trailing newline character"), but for a reason beyond my current understanding, it does not change the result (check with hexdump).

If you however replaced echo with printf -- the dangling 0x0a is not there and you get expected result  (check with hexdump).

All this, apart from being a nice conundrum, is yet another argument against using linefile module in Ansible.

Use copy (you can protect the whole file with Ansible Vault - see decrypt argument) or template (you can have a public template and store the variable values in a Vault-protected form). Define the desired state, do not rely on current state. Period.

Body:
I am trying to copy a secret Python settings file from a settings server to the production environment. Since the settings contains passwords I am using Ansible Vault.

My playbook looks like this:

---
- hosts: production
  tasks:
  - include_vars: settings.yml
  - name: Set properties
    lineinfile:
      dest: ~/temp/deploy
      regexp: "{{ item.split('=')[0] }}\\s*="
      line: "{{ item }}"
    with_lines: echo "{{ config }}"

And my settings.yml looks like this:

config:  |
  ASD='DEF'
  PROGRAM='PROG'
  PASSWORD='MAGNUS123'
  TEMP='TEST'

However when I run the playbook I get the file:

ASD='DEF'
PROGRAM='PROG'
PASSWORD='MAGNUS123'

Even though Ansible claims the last line is also copied:

changed: [ssh.pythonanywhere.com] => (item=ASD='DEF' )
changed: [ssh.pythonanywhere.com] => (item=PROGRAM='PROG')
changed: [ssh.pythonanywhere.com] => (item=PASSWORD='MAGNUS123')
changed: [ssh.pythonanywhere.com] => (item=TEMP='TEST')
changed: [ssh.pythonanywhere.com] => (item=)

What am I doing wrong to cause this?

Ansible version:

ansible --version
ansible 2.4.1.0
  config file = None
  ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.6.2 (default, Jul 17 2017, 16:44:45) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]

Body:
You are doing something completely unnecessary (skip to the bottom), but let's give it a try...

What am I doing wrong to cause this?

If you run the following:

- shell: echo "{{ config }}" | hexdump
  register: echo

- debug:
    var: echo.stdout

You'll see that the output ends with:

54 45 4d 50 3d 27 54 45 53 54 27 0a 0a

which is TEMP='TEST' followed by two newline characters. When used in with_lines loop this will cause two iterations -- the last one with an empty value passed to item.

Now, think what happens to your arguments when item is empty:

regexp becomes \\s*= and line is empty.

In other words you instruct Ansible to replace some line containing = with an empty line.

If the starting point is an empty file, Ansible does the following:

Adds ASD='DEF' line.

Adds PROGRAM='PROG' line.

Adds PASSWORD='MAGNUS123' line.

Adds TEMP='TEST' line.

Replaces a line with = with an empty line (in fact it happens to be the very last line).

And that is the result you get: three lines and an empty one.

You can also arrive at the same conclusion simply running using debug module to display the values of "{{ item.split('=')[0] }}\\s*=" and {{ item }} which you pass to the lineinfile arguments.

echo has -n argument ("Do not print the trailing newline character"), but for a reason beyond my current understanding, it does not change the result (check with hexdump).

If you however replaced echo with printf -- the dangling 0x0a is not there and you get expected result  (check with hexdump).

All this, apart from being a nice conundrum, is yet another argument against using linefile module in Ansible.

Use copy (you can protect the whole file with Ansible Vault - see decrypt argument) or template (you can have a public template and store the variable values in a Vault-protected form). Define the desired state, do not rely on current state. Period.


问:
Implementing SSL using PHP and .htaccess only
my hosting company is holding me to ransom to pay for SSL

It would seem logical that I can SSL (RSA) encode my site using PHP...

Would this be sufficient to give me the lock symbol?

If not what can I do to add a certificate? can I create one and use it across all my sites?

答:
SSL is 'protocol', it requires 'negotiation of encryption' (send and receive few messages) - not just simple encrypted answer.

PHP code can just send one answer. It can't negotiate (read few requests and send few answers thru one connection).

After successful negotiation, SSL is enabled in web browers, so user also send to you encrypted (safe) request (login/password from forms and everything else is protected). Your server needs to decrypt requests, not only send encrypted answers.

To use SSL you need webserver (hosted by your company) that negotiate encryption and encrypt/decrypt data send by/to web server.

If you are looking for free (and weak) SSL protection you can try to use cloudflare.com. They give you 1/2 of SSL (some attacks are still possible - connection between your web company and cloudflare is not encrypted), but they are free. In web browser it will show 'lock' and your website will look like 'secure' website.


问:
How to get values from within brackets?
I have a value Mac(user, name)

How do i use perl reg expression to do a check on values inside the brackets.

Value: Mac(user,name)
Remove Mac.. and Do a check on (user,name) to check if it contains 'user'...?

Thanks for help!! :D

答:
thanks all... i manage to use split to get data from my value

```<code>my @array = split (/[()]/, $input);
</code>```

With this.. my value is store inside $array[1] :)

ContentLicense: CC BY-SA 2.5

Title: How to get values from within brackets?

Body:
thanks all... i manage to use split to get data from my value

my @array = split (/[()]/, $input);

With this.. my value is store inside $array[1] :)


问:
findcontours assertion failed
I'm a newbie of C++ and opencv. I've written a simple program that you can find below but when I run it I always get an exception thrown by findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE) raised by type assertion failed

OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN
  (type0) && ((1 << type0) & fixedDepthMask) != 0)) in create, file C:\opencv\modu
  les\core\src\matrix.cpp, line 1466.

I need a class that represents a single contour and integrates contour analisys method. I know that CONTOUR is a different type respect to vector<Point> but since it extends the latter, shouldn't CONTOUR be also a vector<Point> type (and in the same way vector<CONTOUR> be also a vector< vector<Point> > ) ? Am I wrong?

Please note that if you declare CONTOUR as a class derived from vector<vector<Point>> and declare Ctr in the code below as a CONTOUR object in place of vector<CONTOUR> everything work out fine.

Many thanks in advance.

Here is my code

```<code>#include "opencv2/opencv.hpp"

#include <vector>

using namespace cv;
using namespace std;

class CONTOUR : public vector<Point>
{
public:
    CONTOUR() : vector<Point>(){ };
    CONTOUR(const CONTOUR& orig) : vector<Point> (orig){ };
    virtual ~CONTOUR(){ };

    CONTOUR& operator=(const CONTOUR& rhs)
    {
        vector<Point> :: operator = (rhs);
        return *this;
    }

    CONTOUR& operator=(const vector<Point>& rhs)
    {
        vector<Point> :: operator = (rhs);
        return *this;
    }
};

/** @function main */
int main(int argc, char** argv)
{
    VideoCapture Camera;

    if(Camera.open(0))
    {
        Mat img;

        namedWindow("VIDEO", CV_WINDOW_AUTOSIZE);

        for(;;)
        {

            Camera >> img;

            if(!img.empty())
            {
                CONTOUR ctr;
                RNG n(12345);

                GaussianBlur(img, img, Size(5,5), 1.0, 1.0);
                cvtColor(img, img, CV_BGR2GRAY);
                Canny(img, img, 20, 80, 3);

                findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

                Mat shape = Mat::zeros( img.size(), CV_8UC3 );

                for( unsigned int i = 0; i< ctr.size(); i++ )
                {
                    Scalar color(n.uniform(0,255), n.uniform(0,255), n.uniform(0,255));
                    drawContours(shape, ctr, i, color, 1, 8);
                }

                imshow("VIDEO", shape);

                if(waitKey(30) >= 0)
                {
                    break;
                }
            }
        }
    }
    else
    {
        cout << "Camera not opened" << endl;
    }

    return 0;
}
</code>```

答:
Assertion fail error in findContour function is only due to mismatch in your compiler and opencv binary.
Choose those proper compiler from project property.</p>

Title: findcontours assertion failed

Body:
I'm a newbie of C++ and opencv. I've written a simple program that you can find below but when I run it I always get an exception thrown by findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE) raised by type assertion failed

OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN
  (type0) && ((1 << type0) & fixedDepthMask) != 0)) in create, file C:\opencv\modu
  les\core\src\matrix.cpp, line 1466.

I need a class that represents a single contour and integrates contour analisys method. I know that CONTOUR is a different type respect to vector<Point> but since it extends the latter, shouldn't CONTOUR be also a vector<Point> type (and in the same way vector<CONTOUR> be also a vector< vector<Point> > ) ? Am I wrong?

Please note that if you declare CONTOUR as a class derived from vector<vector<Point>> and declare Ctr in the code below as a CONTOUR object in place of vector<CONTOUR> everything work out fine.

Many thanks in advance.

Here is my code

#include "opencv2/opencv.hpp"

#include <vector>

using namespace cv;
using namespace std;

class CONTOUR : public vector<Point>
{
public:
    CONTOUR() : vector<Point>(){ };
    CONTOUR(const CONTOUR& orig) : vector<Point> (orig){ };
    virtual ~CONTOUR(){ };

    CONTOUR& operator=(const CONTOUR& rhs)
    {
        vector<Point> :: operator = (rhs);
        return *this;
    }

    CONTOUR& operator=(const vector<Point>& rhs)
    {
        vector<Point> :: operator = (rhs);
        return *this;
    }
};

/** @function main */
int main(int argc, char** argv)
{
    VideoCapture Camera;

    if(Camera.open(0))
    {
        Mat img;

        namedWindow("VIDEO", CV_WINDOW_AUTOSIZE);

        for(;;)
        {

            Camera >> img;

            if(!img.empty())
            {
                CONTOUR ctr;
                RNG n(12345);

                GaussianBlur(img, img, Size(5,5), 1.0, 1.0);
                cvtColor(img, img, CV_BGR2GRAY);
                Canny(img, img, 20, 80, 3);

                findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

                Mat shape = Mat::zeros( img.size(), CV_8UC3 );

                for( unsigned int i = 0; i< ctr.size(); i++ )
                {
                    Scalar color(n.uniform(0,255), n.uniform(0,255), n.uniform(0,255));
                    drawContours(shape, ctr, i, color, 1, 8);
                }

                imshow("VIDEO", shape);

                if(waitKey(30) >= 0)
                {
                    break;
                }
            }
        }
    }
    else
    {
        cout << "Camera not opened" << endl;
    }

    return 0;
}


问:
Starting rails dev server results in cannot open shared object file: No such file or directory puma_http11.so (LoadError)
I'm trying to start rails server (puma) using command rails s

I get this error:

rails s I, [2017-11-16T10:47:05.872867 #16905]  INFO -- sentry: **
  [Raven] Raven 2.5.1 configured not to capture errors: Not configured
  to send/capture in environment 'development'
  => Booting Puma
  => Rails 5.1.3 application starting in development on http://localhost:3000
  => Run rails server -h for more startup options Exiting /home/mariusz/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/activesupport-5.1.3/lib/active_support/dependencies.rb:292:in require': libssl.so.1.0.2: cannot open shared object file: No such
  file or directory -
  /home/mariusz/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/puma-3.10.0/lib/puma/puma_http11.so
  (LoadError)   from
  /home/mariusz/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/activesupport-5.1.3/lib/active_support/dependencies.rb:292:inblock in require'

My project info:
puma (3.10.0), rails (5.1.3), ruby 2.4.0

答: The problem was with invalid environment. I needed to restore all my gems to pristine state. Running gem pristine --all helped. (it takes about 10 min to finish it)


问:
Update value of a property using LINQ
I have following class structure

```<code>public class OfferModelCollection
{
    List<OfferModel> offers = new List<OfferModel>();
}

public class OfferModel
{
     public int ID { get; set; }
     public ProviderModel Provider { get; set; }
     public ProviderType ProviderType { get; set; }   //Enum

}

public class ProviderModel : BaseModel, IIdentity
{
     public string ProviderCode { get; set; }
     public string ProviderName { get; set; }
}
</code>```

I am now trying to update ProviderType of those offers whose Provider.ProviderCode matches to some string value. How can I achieve it in LINQ?

Something like this:

```<code>offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10"))).ProviderType = ProviderType.Default;
</code>```

答:
You have to use a foreach(at least that is the common and most efficient approach).

```<code>var toUpdate = offersVM.Offers.Where(x=> x.Provider.ProviderCode.Contains("p10"));

foreach(var x in toUpdate)
    x.ProviderType = ProviderType.Default;
</code>```

Use LINQ to query a datasource, not to modify it!

Title: Update value of a property using LINQ

Body:
I have following class structure

public class OfferModelCollection
{
    List<OfferModel> offers = new List<OfferModel>();
}

public class OfferModel
{
     public int ID { get; set; }
     public ProviderModel Provider { get; set; }
     public ProviderType ProviderType { get; set; }   //Enum

}

public class ProviderModel : BaseModel, IIdentity
{
     public string ProviderCode { get; set; }
     public string ProviderName { get; set; }
}

I am now trying to update ProviderType of those offers whose Provider.ProviderCode matches to some string value. How can I achieve it in LINQ?

Something like this:

offersVM.Offers.Where(x=>x.Provider.ProviderCode.Contains("p10"))).ProviderType = ProviderType.Default;

Body:
You have to use a foreach(at least that is the common and most efficient approach).

var toUpdate = offersVM.Offers.Where(x=> x.Provider.ProviderCode.Contains("p10"));

foreach(var x in toUpdate)
    x.ProviderType = ProviderType.Default;

Use LINQ to query a datasource, not to modify it!


问:
Oracle update skip locked with dependency on other rows
For multithreaded env in our application we implemented oracle skip locked where no two threads pick up the same record in the database for processing(We add 'waiting' to 'working' flag).

Now, we have a modification where if two records in the database which are queued for processing have the same ID(workid) should not picked up the same time.(i.e - the other record status should not be updated to WORKING if already one record has a flag was 'WORKING'
Can someone help as to how this can be achieved?

Below is the procedure for the same where single record is locked without comparison.

```<code>create or replace PROCEDURE DEQUEUE_MANAGER(
    v_managerName IN Queue.manager%TYPE,
    v_workid IN VARCHAR2,
    v_key OUT NUMBER,
    v_datatablekey OUT Queue.DATA_TABLE_KEY%TYPE,
    v_tasktype OUT Queue.TASK_TYPE%TYPE,
    v_no_of_attempts OUT Queue.ATTEMPT%TYPE,
    v_result OUT NUMBER,
    v_error_desc OUT VARCHAR2)
IS
    v_recordrow Queue%ROWTYPE;
    v_qeuuestatus  VARCHAR2(255);
    v_updatedstaus VARCHAR2(255);
    CURSOR c IS
        select *
        from QUEUE
        WHERE MANAGER =v_managerName
        AND STATUS =v_qeuuestatus
        AND workid=v_workid
        AND DATE_RELEASE<=SYSDATE
    FOR UPDATE SKIP LOCKED;
BEGIN
    v_result      := -1;
    v_qeuuestatus :='WAITING';
    v_updatedstaus:='WORKING';
    v_tasktype :='';
    v_datatablekey:=-1;
    v_key:=-1;
    v_error_desc:='No Data Found';
    v_no_of_attempts:=0;
    OPEN c;
    FOR i IN 1..1 LOOP
        FETCH c INTO v_recordrow;
        EXIT WHEN c%NOTFOUND;
        select v_recordrow.key into v_key
        from QUEUE
        where key = v_recordrow.key
        for update;

        UPDATE Queue
        SET STATUS=v_updatedstaus
        WHERE KEY=v_recordrow.key;
        COMMIT;
        v_datatablekey:=v_recordrow.data_table_key;
        v_tasktype    := v_recordrow.task_type;
        v_no_of_attempts := v_recordrow.attempt;
        v_result      := 0;
        IF (v_no_of_attempts IS NULL) THEN
            v_no_of_attempts:=0;
        END IF;
    END LOOP;
    CLOSE c;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
            v_datatablekey:=-1;
            v_tasktype:='';
            v_key:=-1;
            v_no_of_attempts:=0;
            v_result    :=-1;
            v_error_desc:='No Rows Found';
    WHEN OTHERS THEN
              DBMS_OUTPUT.put_line ('Exception Occurred');
              v_datatablekey:=0;
              v_tasktype:='';
              v_key:=0;
              v_no_of_attempts:=0;
              v_result     := -2;
              v_error_desc := SQLERRM;
              ROLLBACK;
END;
</code>```

答:
The purpose of the FOR UPDATE syntax is to lock records we want to update at some point in the future. We want to get the records now so that we can be sure our subsequent update won't fail because another session has locked the records.

That's not what your code does. Instead it selects the record, updates it and then issues a commit. The commit ends the transaction, which releases the lock. Your process would work the same without the FOR UPDATE.

Now we have your additional requirement: if a queued record for a given workid is being processed no other record for the same workid can be processed by another session. You say that all instances  of a workid have the same values of queue status or manager. So that means the initial SELECT FOR UPDATE grabs all the records you want to lock. The snag is the SKIP LOCK allows other sessions to update any other records for that workid (only the first record is actually locked because that's the only one you've updated). Not that it matters sd the commit releases those locks.

The simplest solution would be to remove the SKIP LOCKED and the COMMIT. That would keep all the related records locked up until your processing transaction commits. But this may create further problems elsewhere.

Concurrent programming is really hard to get right. It's an architectural problem; you can't solve it at the level of an individual program unit.

Body:
For multithreaded env in our application we implemented oracle skip locked where no two threads pick up the same record in the database for processing(We add 'waiting' to 'working' flag).

Now, we have a modification where if two records in the database which are queued for processing have the same ID(workid) should not picked up the same time.(i.e - the other record status should not be updated to WORKING if already one record has a flag was 'WORKING'
Can someone help as to how this can be achieved?

Below is the procedure for the same where single record is locked without comparison.

create or replace PROCEDURE DEQUEUE_MANAGER(
    v_managerName IN Queue.manager%TYPE,
    v_workid IN VARCHAR2,
    v_key OUT NUMBER,
    v_datatablekey OUT Queue.DATA_TABLE_KEY%TYPE,
    v_tasktype OUT Queue.TASK_TYPE%TYPE,
    v_no_of_attempts OUT Queue.ATTEMPT%TYPE,
    v_result OUT NUMBER,
    v_error_desc OUT VARCHAR2)
IS
    v_recordrow Queue%ROWTYPE;
    v_qeuuestatus  VARCHAR2(255);
    v_updatedstaus VARCHAR2(255);
    CURSOR c IS
        select *
        from QUEUE
        WHERE MANAGER =v_managerName
        AND STATUS =v_qeuuestatus
        AND workid=v_workid
        AND DATE_RELEASE<=SYSDATE
    FOR UPDATE SKIP LOCKED;
BEGIN
    v_result      := -1;
    v_qeuuestatus :='WAITING';
    v_updatedstaus:='WORKING';
    v_tasktype :='';
    v_datatablekey:=-1;
    v_key:=-1;
    v_error_desc:='No Data Found';
    v_no_of_attempts:=0;
    OPEN c;
    FOR i IN 1..1 LOOP
        FETCH c INTO v_recordrow;
        EXIT WHEN c%NOTFOUND;
        select v_recordrow.key into v_key
        from QUEUE
        where key = v_recordrow.key
        for update;

        UPDATE Queue
        SET STATUS=v_updatedstaus
        WHERE KEY=v_recordrow.key;
        COMMIT;
        v_datatablekey:=v_recordrow.data_table_key;
        v_tasktype    := v_recordrow.task_type;
        v_no_of_attempts := v_recordrow.attempt;
        v_result      := 0;
        IF (v_no_of_attempts IS NULL) THEN
            v_no_of_attempts:=0;
        END IF;
    END LOOP;
    CLOSE c;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
            v_datatablekey:=-1;
            v_tasktype:='';
            v_key:=-1;
            v_no_of_attempts:=0;
            v_result    :=-1;
            v_error_desc:='No Rows Found';
    WHEN OTHERS THEN
              DBMS_OUTPUT.put_line ('Exception Occurred');
              v_datatablekey:=0;
              v_tasktype:='';
              v_key:=0;
              v_no_of_attempts:=0;
              v_result     := -2;
              v_error_desc := SQLERRM;
              ROLLBACK;
END;


问:
What's the difference between equal and identical comparison operators in PHP?

Possible Duplicate:

  How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?

I know the basic difference between == and === , but can some experienced coders tell me some practical examples for both cases?

答:
== checks if the values of the two operands are equal or not. === checks the values as well as the type of the two operands.

```<code>if("1" == 1)
   echo "true";
else
   echo "false";
</code>```

The above would output true.

```<code>if("1" === 1)
   echo "true";
else
   echo "false";
</code>```

The above would output false.

```<code>if("1" === (string)1)
   echo "true";
else
   echo "false";
</code>```

The above would output true.

Body:
== checks if the values of the two operands are equal or not. === checks the values as well as the type of the two operands.

if("1" == 1)
   echo "true";
else
   echo "false";

The above would output true.

if("1" === 1)
   echo "true";
else
   echo "false";

The above would output false.

if("1" === (string)1)
   echo "true";
else
   echo "false";

The above would output true.


问:
How can I symlink a file in Linux?
I want to make a symbolic link in Linux. I have written this Bash command where the first path is the folder I want link into and the second path is the compiled source.

```<code>ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal
</code>```

Is this correct?

答:
I find a bit confusing the terminologies "target" and "directory" in the man information.

The target is the folder that we are symlinking to and the directory the actual symlink (not the directory that you will be symlinking to), if anyone is experiencing the same confusion, don't feel alone.

This is my interpretation of creating a Symlink (in linux):

```<code>ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO NAME-OF-YOUR-SYMLINK
</code>```

You can navigate to the folder where you want to create the symlink and run the command or specify the FULL PATH for your symlink instead of NAME-OF-YOUR-SYMLINK.

```<code>cd /FULL/PATH/TO/MY-SYMLINK-PARENT-FOLDER
ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO NAME-OF-YOUR-SYMLINK
</code>```

OR

```<code>ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO /FULL/PATH/TO/MY-SYMLINK-PARENT-FOLDER/NAME-OF-YOUR-SYMLINK
</code>```

I hope this helps to those (still) slighly confused.

ContentLicense: CC BY-SA 4.0

Title: How can I symlink a file in Linux?

Body:
I want to make a symbolic link in Linux. I have written this Bash command where the first path is the folder I want link into and the second path is the compiled source.

ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal

Is this correct?

Body:
I find a bit confusing the terminologies "target" and "directory" in the man information.

The target is the folder that we are symlinking to and the directory the actual symlink (not the directory that you will be symlinking to), if anyone is experiencing the same confusion, don't feel alone.

This is my interpretation of creating a Symlink (in linux):

ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO NAME-OF-YOUR-SYMLINK

You can navigate to the folder where you want to create the symlink and run the command or specify the FULL PATH for your symlink instead of NAME-OF-YOUR-SYMLINK.

cd /FULL/PATH/TO/MY-SYMLINK-PARENT-FOLDER
ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO NAME-OF-YOUR-SYMLINK

OR

ln -s /FULL/PATH/FOLDER-OR-FILE-SYMLINKING-TO /FULL/PATH/TO/MY-SYMLINK-PARENT-FOLDER/NAME-OF-YOUR-SYMLINK

I hope this helps to those (still) slighly confused.


问:
Bootstrap Toggle Button, how change size (height and weight)
I need to change those attributes for adapting the UI to the design, but I would like to use Bootstrap as much as I can. Is there a way to do that keeping using the button and relative bootstrap classes?
It looks like it is not possible (tried to play with the inspector but didn't see any reaction...)

Sample below (original code from Bootstrap, just ignore the menu:-) )

.custom-header {
float: left;
}

.custom {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <div class="navbar-header custom-header">
      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link <span class="sr-only">(current)</span></li>
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
            <li role="separator" class="divider"></li>
            <li>One more separated link</li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

答:
Increase or decrease padding as you want like this:

```<code>.custom-header .navbar-toggle {
  padding: 7px 8px;
}
</code>```

.custom-header {
  float: left;
}
.custom-header .navbar-toggle {
  padding: 7px 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <div class="navbar-header custom-header">
      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active">Link <span class="sr-only">(current)</span></li>
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
            <li role="separator" class="divider"></li>
            <li>One more separated link</li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li>Link</li>
        <li class="dropdown">
          Dropdown <span class="caret"></span>
          <ul class="dropdown-menu">
            <li>Action</li>
            <li>Another action</li>
            <li>Something else here</li>
            <li role="separator" class="divider"></li>
            <li>Separated link</li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav></code>```

Body:
I need to change those attributes for adapting the UI to the design, but I would like to use Bootstrap as much as I can. Is there a way to do that keeping using the button and relative bootstrap classes?
It looks like it is not possible (tried to play with the inspector but didn't see any reaction...)

Sample below (original code from Bootstrap, just ignore the menu:-) )

.custom-header {
float: left;
}

.custom {

}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>

Link (current)

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

      <form class="navbar-form navbar-left">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

          Dropdown

Action

Another action

Something else here

Separated link

Body:
Increase or decrease padding as you want like this:

.custom-header .navbar-toggle {
  padding: 7px 8px;
}

.custom-header {
  float: left;
}
.custom-header .navbar-toggle {
  padding: 7px 8px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

    <div class="navbar-header custom-header">
      <button type="button" class="navbar-toggle collapsed custom" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
          </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>


问:
Python load in from another python file
I am wanting to loop through 5 questions from another .py file.

The extra file is file.py and has 5 questions -q1 = "what is...", q2 etc..
This adds a number to each time I use q but does not catch the question from the external python document:

```<code>from file import*
i = 0
for x in range(5):
    i = i+1
    question1 = str(input("q" + str(i)))
</code>```

答:
The best way is to save the questions in file.py as a list as suggested in the comments. Then the contents of file.py would be:

```<code>q = ['who is...', 'What is...']
</code>```

and the content of your program would be:

```<code>from file import q
for item in q:
    print(item)
</code>```

If you want to do it your way, do it like this:

```<code>from file import *

for x in range(5):
    exec('question = q' + str(x+1))
    print(question)
</code>```

However, this is not pythonic and not recommended.

Title: Python load in from another python file

Body:
I am wanting to loop through 5 questions from another .py file.

The extra file is file.py and has 5 questions -q1 = "what is...", q2 etc..
This adds a number to each time I use q but does not catch the question from the external python document:

from file import*
i = 0
for x in range(5):
    i = i+1
    question1 = str(input("q" + str(i)))

Body:
The best way is to save the questions in file.py as a list as suggested in the comments. Then the contents of file.py would be:

q = ['who is...', 'What is...']

and the content of your program would be:

from file import q
for item in q:
    print(item)

If you want to do it your way, do it like this:

from file import *

for x in range(5):
    exec('question = q' + str(x+1))
    print(question)

However, this is not pythonic and not recommended.


问:
Why is the input displayed after the enter key has been pressed?
```<code>#include <stdio.h>

/* copy input to output */

main()
{
    int c;

    c = getchar();

    while(c != EOF)
        {
        putchar(c);
        c = getchar();
        }

    return 0;
}
</code>```

In the given code, the program displays the input character.
It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.

When I ran the code in my IDE (Code::Blocks 16.01) and input a string,
eg: Hi! My name is C.\n

The output is displayed after '\n' and not simultaneously.
Isn't the output supposed to be as - "HHii!!  MMyy  nnaammee  iiss  CC.."?

Bold letters indicate the output.

答:
include:

```<code>#include <unistd.h>
#include <termios.h>
</code>```

before your code in main insert:

```<code>struct termios term, term_orig;
if(tcgetattr(STDIN_FILENO, &term_orig)) {
        printf("tcgetattr failed\n");
        return -1;
    }
term = term_orig;
term.c_lflag &= ~ICANON;
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) {
    printf("tcsetattr failed\n");
    return -1;
</code>```

}

after your code insert:

```<code>if (tcsetattr(STDIN_FILENO, TCSANOW, &term_orig)) {
    printf("tcsetattr failed\n");
   return -1;
}
</code>```

Body:
#include <stdio.h>

/* copy input to output */

main()
{
    int c;

    c = getchar();

    while(c != EOF)
        {
        putchar(c);
        c = getchar();
        }

    return 0;
}

In the given code, the program displays the input character.
It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.

When I ran the code in my IDE (Code::Blocks 16.01) and input a string,
eg: Hi! My name is C.\n

The output is displayed after '\n' and not simultaneously.
Isn't the output supposed to be as - "HHii!!  MMyy  nnaammee  iiss  CC.."?

Bold letters indicate the output.

Body:
include:

#include <unistd.h>
#include <termios.h>

before your code in main insert:

struct termios term, term_orig;
if(tcgetattr(STDIN_FILENO, &term_orig)) {
        printf("tcgetattr failed\n");
        return -1;
    }
term = term_orig;
term.c_lflag &= ~ICANON;
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) {
    printf("tcsetattr failed\n");
    return -1;

}

after your code insert:

if (tcsetattr(STDIN_FILENO, TCSANOW, &term_orig)) {
    printf("tcsetattr failed\n");
   return -1;
}


问:
C: Print Unsigned Int In a Binary Base
I have to make my own printf(for an exercise) and I have to add a %b flag which prints an unsigned number in a binary base. I've created the function but I'm still getting the unsigned number at the output. There you have my code. Thanks in advance!</p>

```<code>int unsignednbr(unsigned int nb)
{
    if (nb < 0)
    {
        putchar('-');
        nb = nb * -1;
    }
    if (nb >= 10)
    {
        putnumber(nb / 10);
        putnumber(nb % 10);
    }
    else
        putchar(nb + '0');
}

int unsigned_to_binary(int nb)
{
    long long binary_nbr = 0;
    int remainder;
    int i = 0;

    unsignednbr(nb);
    while (nb != 0)
    {
        remainder = nb % 2;
        nb /= 2;
        binary_nbr += remainder * i;
        i *= 10;
    }
}

void own_printf(char* format, ...)
{
    int i = 0;
    va_list args;

    va_start(args, format);
    while (format[i])
    {
        if (format[i] == '%')
        {
            switch (format[i + 1])
            {
            case 'b':
                unsigned_to_binary (va_arg( args, int));
                break;
            }
            i++;
        }
    }
    va_end(args);
}

int main()
{
    own_printf("%b", -42);
    return 0;
}
</code>```

答:
I bet you are from Epitech, did you try asking a teaching assistant ? :p

Anyway, if you only want to print a binary representation of a number, you could use a combination of the >> and & operators in a loop. You will iterate on each of the 32 bits of your int, determine if it's a 1 or a 0 and print it.

```<code>unsigned int number = 42;
for (int i = 0; i < 32; ++i) {
  if (number >> i & 0x1) putchar('1');
  else putchar('0');
}

putchar('\n');
</code>```

This method has many downsides (no buffering, slow, assuming an int is 32 bits...) but it should work.

Aside from that, a few things you may want to take a look at in your code :

In function unsignednbr you check if the unsigned int you recieve as a paremeter is less that 0. This is an always false condiftion.

You do not print anything after the while loop in the unsigned_to_binary function. So what is the purpose of this loop ? Keep in mind that the parameters passed by values are acutally copies and that the modifications you make to these copies are local to the function that recieved the copy. The call to the unsignednbr function right before the loop seems useless.

If you have time, re-write your main loop using an array of function pointers. That will make the assistants happy ! :p

Good luck ! :D

Title: C: Print Unsigned Int In a Binary Base

Body:
I have to make my own printf(for an exercise) and I have to add a %b flag which prints an unsigned number in a binary base. I've created the function but I'm still getting the unsigned number at the output. There you have my code. Thanks in advance!

int unsignednbr(unsigned int nb)
{
    if (nb < 0)
    {
        putchar('-');
        nb = nb * -1;
    }
    if (nb >= 10)
    {
        putnumber(nb / 10);
        putnumber(nb % 10);
    }
    else
        putchar(nb + '0');
}

int unsigned_to_binary(int nb)
{
    long long binary_nbr = 0;
    int remainder;
    int i = 0;

    unsignednbr(nb);
    while (nb != 0)
    {
        remainder = nb % 2;
        nb /= 2;
        binary_nbr += remainder * i;
        i *= 10;
    }
}

void own_printf(char* format, ...)
{
    int i = 0;
    va_list args;

    va_start(args, format);
    while (format[i])
    {
        if (format[i] == '%')
        {
            switch (format[i + 1])
            {
            case 'b':
                unsigned_to_binary (va_arg( args, int));
                break;
            }
            i++;
        }
    }
    va_end(args);
}

int main()
{
    own_printf("%b", -42);
    return 0;
}

Body:
I bet you are from Epitech, did you try asking a teaching assistant ? :p

Anyway, if you only want to print a binary representation of a number, you could use a combination of the >> and & operators in a loop. You will iterate on each of the 32 bits of your int, determine if it's a 1 or a 0 and print it.

unsigned int number = 42;
for (int i = 0; i < 32; ++i) {
  if (number >> i & 0x1) putchar('1');
  else putchar('0');
}

putchar('\n');

This method has many downsides (no buffering, slow, assuming an int is 32 bits...) but it should work.

Aside from that, a few things you may want to take a look at in your code :

In function unsignednbr you check if the unsigned int you recieve as a paremeter is less that 0. This is an always false condiftion.

You do not print anything after the while loop in the unsigned_to_binary function. So what is the purpose of this loop ? Keep in mind that the parameters passed by values are acutally copies and that the modifications you make to these copies are local to the function that recieved the copy. The call to the unsignednbr function right before the loop seems useless.

If you have time, re-write your main loop using an array of function pointers. That will make the assistants happy ! :p

Good luck ! :D


问:
why is collection view header loading before viewdidload?
I am trying to add a activity indicator but I am not able to do so successfully because my collection view header is loading before viewdidload so therefore I have things showing before my activity indicator even starts. Can someone please help me or point me in the right direction. I have posted my code below

viewDidLoad

```<code> override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }
</code>```

Collection view header thats being called before viewDidLoad

```<code> func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }
</code>```

view controller

```<code>class newGuestPhotoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, guestProfileHeaderDelegate, HomePostCellDelegate {

    let cellId = "cellId"
    let homePostCellId = "homePostCellId"

    @IBOutlet weak var profileCollectionView: UICollectionView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    var user: userAccount?
    var selectedUser: userAccount!
    var posts = [Post]()
    let stringID = NSUUID().uuidString
    var isGridView = true

    func didChangeToGridView() {
        isGridView = true
        profileCollectionView?.reloadData()
    }

    func didChangeToListView() {
        isGridView = false
        profileCollectionView?.reloadData()
    }

    var showDataFlag : Bool = false!

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchUser()
        profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
        profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        profileCollectionView?.register(newsfeedCollectionViewCell.self, forCellWithReuseIdentifier: homePostCellId)
    }
    func fetchUser() {
        self.activityIndicator.startAnimating()
        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName
                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

    fileprivate func fetchOrderedPosts() {
        guard let uid = selectedUser?.uid else { return }
        let ref = Database.database().reference().child("post").child(uid)
        ref.queryOrdered(byChild: "dateOfPost").observe(.childAdded, with: { (snapshot) in
            guard let dictionary = snapshot.value as? [String: Any] else { return }
            let uid = dictionary["postUserUID"] as? String

            Database.fetchUserWithUID(uid: uid!, completion: { (userSnap) in

            let post = Post(user:userSnap, dictionary: dictionary)
            self.posts.insert(post, at: 0)
            guard let uid = Auth.auth().currentUser?.uid else {return}
            Database.database().reference().child("likes").child(post.postID!).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
                print(snapshot)

                if let value = snapshot.value as? Int, value == 1 {
                    post.hasLiked = true
                } else {
                    post.hasLiked = false
                }

              DispatchQueue.main.async(execute: {
            self.profileCollectionView?.reloadData()
                })
            }, withCancel: { (err) in
                print("Failed to fetch like info for post:", err)
            })

            })
        }) { (err) in
            print("Failed to fetch ordered posts:", err)
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if(!showDataFlag){
            return 0
        }
        return posts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if isGridView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! photoViewCollectionViewCell
            cell.post = posts[indexPath.item]

            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homePostCellId, for: indexPath) as! newsfeedCollectionViewCell
            cell.post = posts[indexPath.item]
            cell.delegate = self

            return cell
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 250)
    }
</code>```

答:
As I said in mi comment, you can add a flag and after your fetchUser() you can set this flag true and your collectionView will show your data

something like this

```<code>var showDataFlag : Bool = false

override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

//In your Collection View Data Source Implementation

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if(!showDataFlag){
           return 0
        }
           return yourNeededNumberOfSections
    }
</code>```

Body:
I am trying to add a activity indicator but I am not able to do so successfully because my collection view header is loading before viewdidload so therefore I have things showing before my activity indicator even starts. Can someone please help me or point me in the right direction. I have posted my code below

viewDidLoad

 override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

Collection view header thats being called before viewDidLoad

 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }

view controller

class newGuestPhotoViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, guestProfileHeaderDelegate, HomePostCellDelegate {

    let cellId = "cellId"
    let homePostCellId = "homePostCellId"

    @IBOutlet weak var profileCollectionView: UICollectionView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    var user: userAccount?
    var selectedUser: userAccount!
    var posts = [Post]()
    let stringID = NSUUID().uuidString
    var isGridView = true

    func didChangeToGridView() {
        isGridView = true
        profileCollectionView?.reloadData()
    }

    func didChangeToListView() {
        isGridView = false
        profileCollectionView?.reloadData()
    }

    var showDataFlag : Bool = false!

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchUser()
        profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
        profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        profileCollectionView?.register(newsfeedCollectionViewCell.self, forCellWithReuseIdentifier: homePostCellId)
    }
    func fetchUser() {
        self.activityIndicator.startAnimating()
        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName
                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

    fileprivate func fetchOrderedPosts() {
        guard let uid = selectedUser?.uid else { return }
        let ref = Database.database().reference().child("post").child(uid)
        ref.queryOrdered(byChild: "dateOfPost").observe(.childAdded, with: { (snapshot) in
            guard let dictionary = snapshot.value as? [String: Any] else { return }
            let uid = dictionary["postUserUID"] as? String

            Database.fetchUserWithUID(uid: uid!, completion: { (userSnap) in

            let post = Post(user:userSnap, dictionary: dictionary)
            self.posts.insert(post, at: 0)
            guard let uid = Auth.auth().currentUser?.uid else {return}
            Database.database().reference().child("likes").child(post.postID!).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
                print(snapshot)

                if let value = snapshot.value as? Int, value == 1 {
                    post.hasLiked = true
                } else {
                    post.hasLiked = false
                }

              DispatchQueue.main.async(execute: {
            self.profileCollectionView?.reloadData()
                })
            }, withCancel: { (err) in
                print("Failed to fetch like info for post:", err)
            })

            })
        }) { (err) in
            print("Failed to fetch ordered posts:", err)
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if(!showDataFlag){
            return 0
        }
        return posts.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if isGridView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! photoViewCollectionViewCell
            cell.post = posts[indexPath.item]

            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: homePostCellId, for: indexPath) as! newsfeedCollectionViewCell
            cell.post = posts[indexPath.item]
            cell.delegate = self

            return cell
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
       let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath) as! guestHeaderCollectionViewCell

        header.user = self.selectedUser
        header.delegate = self

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 250)
    }

Body:
As I said in mi comment, you can add a flag and after your fetchUser() you can set this flag true and your collectionView will show your data

something like this

var showDataFlag : Bool = false

override func viewDidLoad() {
        super.viewDidLoad()

           fetchUser()
   profileCollectionView?.register(guestHeaderCollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

   profileCollectionView?.register(photoViewCollectionViewCell.self, forCellWithReuseIdentifier: cellId)

}

   func fetchUser() {
        self.activityIndicator.startAnimating()

        if let uid = selectedUser.uid{

            Database.fetchUserWithUID(uid: uid) { (user) in
                self.selectedUser = user
                self.navigationItem.title = self.selectedUser?.fullName

                self.showDataFlag = true;
                self.profileCollectionView?.reloadData()
                self.activityIndicator.stopAnimating()
                self.activityIndicator.isHidden = true
                self.fetchOrderedPosts()
            }
        }
    }

//In your Collection View Data Source Implementation

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if(!showDataFlag){
           return 0
        }
           return yourNeededNumberOfSections
    }


问:
Having problem dynamically invoking unmanaged VB COM dll from c#?
I have a problem calling unmanaged VB COM dll from c#. This is dynamic invocation using loadLibrary and GetProcAddress.

I can successfully loaded the dll using loadLibrary , but the GetProcAddress always return 0. It wasnt log any error msg and nothing. it just returns 0.

below the sample code

VB COM

```<code>VERSION 1.0 CLASS
BEGIN
    MultiUse = -1
    Persistable = 0
    DataBindingBehavior = 0
    DataSourceBehavior  = 0
    MTSTransactionMode  = 0
END

Attribute VB_Name = "Sample"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True

Option Explicit

Private Attribute1 As String
Private Sub Class_Initialize()
    Attribute1 = "test"
End Sub

Public Sub TestSub()

End Sub

Public Function testFunction() As String
    testFunction = "default.html"
End Function

Public Function SetData(XML As String) As String
    SetData = Date + Time
End Function
</code>```

c# code

```<code>static class UnManagedInvoker
{
    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string dllToLoad);

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procedureName);

    [DllImport("kernel32.dll")]
    private static extern bool FreeLibrary(IntPtr hModule);

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate string MethodToInvoke(string sdata);

    public static string InvokeUnmanagedDll(string dllPath, string methodName)
    {
        IntPtr DIedDll = LoadLibrary(dllPath);

        IntPtr AddressOfFunction = GetProcAddress(DIedDll, methodName);

        MethodToInvoke MI = (MethodToInvoke)Marshal.GetDelegateForFunctionPointer(AddressOfFunction, typeof(MethodToInvoke));

        string data = MI("ssdasda");

        FreeLibrary(DIedDll);
        return data;

    }
}
</code>```

And the calling code

```<code> string res = UnManagedInvoker.InvokeUnmanagedDll("xx.dll","SetData");
</code>```

Can someone help me out..

Update:

I can successfully call the methods if the component is registered. using the below code

```<code>Type Med = Type.GetTypeFromCLSID(new Guid("089DD8B0-E12B-439B-B52C-007CA72C93D0"));
object MedObj = Activator.CreateInstance(Med);
object[] parameter = new object[1];
parameter[0] = "asdasd";
var ss = Med.InvokeMember("SetData", System.Reflection.BindingFlags.InvokeMethod, null, MedObj, parameter);
</code>```

is there a way if the dll not registered.?

答:
Note that the concept of GetProcAddress and COM objects are completely different technologies. VB6 is designed to build COM objects and (to my knowledge) is not able to export code via the GetProcAddress API.

Also by design COM objects need to be registered somewhere, it is however possible to put this information in a manifest file instead of the registry. This means you can register your VB6 COM classes only for your application without using the global registry. (Note that a manifest could also embedded into the .exe instead of being a file.)

For more information search for "Registration free COM", here's a link to the corresponding MSDN article.

Body:
I have a problem calling unmanaged VB COM dll from c#. This is dynamic invocation using loadLibrary and GetProcAddress.

I can successfully loaded the dll using loadLibrary , but the GetProcAddress always return 0. It wasnt log any error msg and nothing. it just returns 0.

below the sample code

VB COM

VERSION 1.0 CLASS
BEGIN
    MultiUse = -1
    Persistable = 0
    DataBindingBehavior = 0
    DataSourceBehavior  = 0
    MTSTransactionMode  = 0
END

Attribute VB_Name = "Sample"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True

Option Explicit

Private Attribute1 As String
Private Sub Class_Initialize()
    Attribute1 = "test"
End Sub

Public Sub TestSub()

End Sub

Public Function testFunction() As String
    testFunction = "default.html"
End Function

Public Function SetData(XML As String) As String
    SetData = Date + Time
End Function

c# code

static class UnManagedInvoker
{
    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string dllToLoad);

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procedureName);

    [DllImport("kernel32.dll")]
    private static extern bool FreeLibrary(IntPtr hModule);

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate string MethodToInvoke(string sdata);

    public static string InvokeUnmanagedDll(string dllPath, string methodName)
    {
        IntPtr DIedDll = LoadLibrary(dllPath);

        IntPtr AddressOfFunction = GetProcAddress(DIedDll, methodName);

        MethodToInvoke MI = (MethodToInvoke)Marshal.GetDelegateForFunctionPointer(AddressOfFunction, typeof(MethodToInvoke));

        string data = MI("ssdasda");

        FreeLibrary(DIedDll);
        return data;

    }
}

And the calling code

 string res = UnManagedInvoker.InvokeUnmanagedDll("xx.dll","SetData");

Can someone help me out..

Update:

I can successfully call the methods if the component is registered. using the below code

Type Med = Type.GetTypeFromCLSID(new Guid("089DD8B0-E12B-439B-B52C-007CA72C93D0"));
object MedObj = Activator.CreateInstance(Med);
object[] parameter = new object[1];
parameter[0] = "asdasd";
var ss = Med.InvokeMember("SetData", System.Reflection.BindingFlags.InvokeMethod, null, MedObj, parameter);

is there a way if the dll not registered.?


问:
How do i fix this CopyPNG File error?
While reading /Users/user/Desktop/AppProject/PruebaApp/Logo  Retina.png

pngcrush caught libpng error:

Read Er Could not find file:
  /Users/user/Library/Developer/Xcode/DerivedData/PruebaApp-cblepoaxbqzyopcbcswwqjtftyon/Build/Intermediates/ArchiveIntermediates/MaderoAPP/InstallationBuildProductsLocation/Applications/MaderoAPP.app/Logo
  Retina.png

Command

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/copypng
  emitted errors but did not return a nonzero exit code to indicate
  failure

Im getting these errors while archiving project, at the end it does archive but i want to get rid of it. I had trouble with the app before and i read that i should delete the DerivedData/(myproject)folder so i did. and apparently it is trying to look for the images in that folder how do i fix this??? Help!

答:
For those who are struggling with this error while building Cordova app.
 Please keep the following point in consideration as it may lead to this error.

The images should be tagged as "resource-file" and not as "source-file" in plugin.xml of your Cordova plugin as the former includes the images in "Copy Bundle Resources" (under Build Phase) and the latter to "Compile Sources" of your equivalent xcode project of cordova app.

Title: How do i fix this CopyPNG File error?


问:
reactjs, redux and pagination
I have an api endpoint which gives an array of ingredients. Each ingredient has the following properties : id, name, measurementunit, density(kg/lt), cost/measurementunit. I have few thousands of ingredients and can keep increasing.

I am recieving a paginated api with variable page size from my backend server.

```<code>http://yoursite.com/api/ingredients?page=1&page_size=200
</code>```

On client site how to organize my state shape w.r.t to page and page_size and ingredients.

On client side i want to display only 15-20 items per page. So how to ensure that the items are displayed properly with pagination.

Similarly i have few more like ingredients. Eg: recipes, users and more.

Will redux able to handle such large data.

答:
Your ingredients response could be like this:

```<code>GET http://yoursite.com/api/ingredients?page=1&page_size=15

{
    pages_count: 50,
    page: 1,
    ingredients: [
        //first 15 ingredients
    ]
}
</code>```

Your initial application state would be:

```<code>{
    pages_count: 50,
    page: 1,
    page_size: 15,
    ingredients: [
        //first 15 ingredients
    ]
}
</code>```

When user click Page 2 button (or Next Page, or whatever), you dispatch an async action like this:

```<code>const changePage = (page) => (dispatch) => {
    doGet(`http://yoursite.com/api/ingredients?page=${page}&page_size=15`)
      .then(res => {
          dispatch(retrieveIngredients(res.ingredients, page));
      });
}
</code>```

where retrieveIngredients is an action creator:

```<code>const retrieveIngredients = (ingredients, page) => {
    return {
        type: 'retrieve_ingredients',
        ingredients,
        page
    };
}
</code>```

Then, the reducer that handles retrieve_ingredients action updates its state to:

```<code>{
    page: action.page,
    ingredients: action.ingredients
}
</code>```

In your IngredientsList component (or something similar, I guess), you will just show the list state.ingredients. Also, your PageSelector will show from 1 to state.pages_count page buttons.

Title: reactjs, redux and pagination

Body:
I have an api endpoint which gives an array of ingredients. Each ingredient has the following properties : id, name, measurementunit, density(kg/lt), cost/measurementunit. I have few thousands of ingredients and can keep increasing.

I am recieving a paginated api with variable page size from my backend server.

http://yoursite.com/api/ingredients?page=1&page_size=200

On client site how to organize my state shape w.r.t to page and page_size and ingredients.

On client side i want to display only 15-20 items per page. So how to ensure that the items are displayed properly with pagination.

Similarly i have few more like ingredients. Eg: recipes, users and more.

Will redux able to handle such large data.

Body:
Your ingredients response could be like this:

GET http://yoursite.com/api/ingredients?page=1&page_size=15

{
    pages_count: 50,
    page: 1,
    ingredients: [
        //first 15 ingredients
    ]
}

Your initial application state would be:

{
    pages_count: 50,
    page: 1,
    page_size: 15,
    ingredients: [
        //first 15 ingredients
    ]
}

When user click Page 2 button (or Next Page, or whatever), you dispatch an async action like this:

const changePage = (page) => (dispatch) => {
    doGet(`http://yoursite.com/api/ingredients?page=${page}&page_size=15`)
      .then(res => {
          dispatch(retrieveIngredients(res.ingredients, page));
      });
}

where retrieveIngredients is an action creator:

const retrieveIngredients = (ingredients, page) => {
    return {
        type: 'retrieve_ingredients',
        ingredients,
        page
    };
}

Then, the reducer that handles retrieve_ingredients action updates its state to:

{
    page: action.page,
    ingredients: action.ingredients
}

In your IngredientsList component (or something similar, I guess), you will just show the list state.ingredients. Also, your PageSelector will show from 1 to state.pages_count page buttons.


问:
How to display image on full div in html css
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="white-block all-stores">
 <div class="embed-responsive embed-responsive-4by3">
  <div class="store-logo">

    <img src="http://via.placeholder.com/350x350" class="img-responsive wp-post-image">

  </div>
 </div>
</div></code>```

thanks

答:
Add this css Style</p>

```<code>img
{
margin: auto;
position: absolute;
left: 0;
right: 0;
bottom: 0;
}
</code>```

Body:
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }

thanks

Body:
Add this css Style

img
{
margin: auto;
position: absolute;
left: 0;
right: 0;
bottom: 0;
}