问:
In Postgresql how to get base64 decoded values as string instead of hex representation?
In Python I encoded one string,

```<code>>>> base64.b64encode('1111')
'MTExMQ=='
</code>```

Now when I try to decode it in Postgresql I got Hex values instead of the original string.

```<code>=# select decode('MTExMQ==', 'base64');

   decode
------------
 \x31313131
</code>```

How can I get the original string without any change in Postgresql?

答:
decode() returns a byte array (bytea) not a "hex string".

The format you see is the default textual representation of a bytea which is e.g. used by psql when displaying bytea values. Other SQL clients might display that differently.

To convert a byte array to a readable string, you need to use encode()

```<code>select encode('\x31313131', 'base64');
</code>```

If you change bytea_output to escape and then cast the result to text you can achieve the same thing:

```<code>set bytea_output to 'escape';
select decode('MTExMQ==', 'base64')::text;
</code>```

If you are using psql you don't need the cast.

Body:
In Python I encoded one string,

>>> base64.b64encode('1111')
'MTExMQ=='

Now when I try to decode it in Postgresql I got Hex values instead of the original string.

=# select decode('MTExMQ==', 'base64');

   decode
------------
 \x31313131

How can I get the original string without any change in Postgresql?

Body:
decode() returns a byte array (bytea) not a "hex string".

The format you see is the default textual representation of a bytea which is e.g. used by psql when displaying bytea values. Other SQL clients might display that differently.

To convert a byte array to a readable string, you need to use encode()

select encode('\x31313131', 'base64');

If you change bytea_output to escape and then cast the result to text you can achieve the same thing:

set bytea_output to 'escape';
select decode('MTExMQ==', 'base64')::text;

If you are using psql you don't need the cast.


来源: stackexchange

问:
How can I have the same javascript variable on the same page?
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

```<code><script type="text/javascript">
  var ttp_number = "1Z8E26R80281495993"; // Tracking number

  var ttp_key="123456";
  (function(){
    document.write('<div id="ttp"></div>');
    s=document.createElement('script');
    s.type="text/javascript";
    s.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp').appendChild(s);",1);
  })()
</script>
</code>```

Then if they wanted to be able to embed that again, I'd have to change all variable names:

```<code><script type="text/javascript">
  var ttp_number_001 = "446888240962"; // Tracking number

  var ttp_key_001="123456";
  (function(){
    document.write('<div id="ttp_001"></div>');
    s_001=document.createElement('script');
    s_001.type="text/javascript";
    s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
    setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
  })()
</script>
</code>```

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?

答:
Why not declare the variables in the function body. Then they're only scoped to that function. You can still set them to different values when you dump the script into the HTML.

I know you mention/imply that the user can edit the function (for some reason) but that just seems like a world of hurt to me, so I'm hoping that that's not actually the case.

ContentLicense: CC BY-SA 2.5

Body:
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.

The problem right now is that I can't include the same variables names on the page.

For instance:

Then if they wanted to be able to embed that again, I'd have to change all variable names:

I'm okay with having them change the contents of the function() block, but the ttp_number and ttp_key need to stay the same variable name.

Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.

So, the ultimate question here...how do I fix that?


问:
How to know when 2 persons cross in the street ? (Geofences...)
I want to create an Android app with a simple concept : if 2 persons who have downloaded my app are crossing in the street, I want to send them a notification (immediately).

I started to use the geofences concept, but I don't know if it is the most appropriate. So my questions are the following :

Using the geofences (every user have his own geofence, so you are notified when entering an other user geofence), how can I make the geofence following the user when he is moving ? (with enough precision but without too much power consumption)

Is there another concept that is more appropriate to my problem than the geofences ?

Thank you :)

答:
if you want use geofences with server side will be more easy for app(in android u only can register 100 geofences) you can check in server the nearest users from you.

but if you need check user very close to you i think is better use Bluetooth, you can emulate ibeacons and the app can register beacon region and monitoring it. dont care gps signal and battery drain. In android you can use altbeacon open source lib for ibeacons/eddystone.

contact me if need more help and sorry my english ;)

ContentLicense: CC BY-SA 3.0


问:
Single Spring repository to produce different objects or entities
I have repository in my spring project:

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    boolean existsById(long id);

    List<User> findAllByEmail(String email);

}
</code>```

It works fine but appeared necessary to use LightUser

```<code>public class LightUser implements Identifiable<Long>, Auditable {

    @Id
    @Column
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, updatable = false)
    private UserType userType;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String domain;

    // get/set methods/ equals/hashcode
}
</code>```

LightUser entity contains a few fields I need in general (all fields precent in User entity), and I want do request to DB using repository mapping results into LightUser (it would be really good to map into dto).

Is it possible add special method into UserRepository to cover my needs or i should create similar one for same table but for LightUser? If it possible, provide example please or core idea.

答:
UserRepository is a JPA repository that manages a User entity as mentioned in its definition UserRepository extends JpaRepository<User, Long>.

For a new entity LightUser its better to create a seperate repository LightUserRepository like so

```<code>@Repository
public interface LightUserRepository extends JpaRepository<LightUser, Long> {

    ....

}
</code>```

Body:
I have repository in my spring project:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    boolean existsById(long id);

    List<User> findAllByEmail(String email);

}

It works fine but appeared necessary to use LightUser

public class LightUser implements Identifiable<Long>, Auditable {

    @Id
    @Column
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, updatable = false)
    private UserType userType;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String domain;

    // get/set methods/ equals/hashcode
}

LightUser entity contains a few fields I need in general (all fields precent in User entity), and I want do request to DB using repository mapping results into LightUser (it would be really good to map into dto).

Is it possible add special method into UserRepository to cover my needs or i should create similar one for same table but for LightUser? If it possible, provide example please or core idea.

Body:
UserRepository is a JPA repository that manages a User entity as mentioned in its definition UserRepository extends JpaRepository<User, Long>.

For a new entity LightUser its better to create a seperate repository LightUserRepository like so

@Repository
public interface LightUserRepository extends JpaRepository<LightUser, Long> {

    ....

}


问:
Validation for digit only in an EditText
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?</p>

```<code>public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}
</code>```

答:
Try this use android:inputType="number"
 property of Editext which allows only numbers to enter as input in Editext

```<code><EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"/>
</code>```

for more information read android:inputType

and also bind your Controls in onCreate()

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

    addDataToDisplay();
}
</code>```

Body:
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?

public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}

Body:
Try this use android:inputType="number"
 property of Editext which allows only numbers to enter as input in Editext

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"/>

for more information read android:inputType

and also bind your Controls in onCreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

    addDataToDisplay();
}


问:
How do I identify a loop in LLVM bitcode?
I have a LLVM bitcode file and I'm running a loop pass on it. Every time I arrive at a loop ("runOnLoop"), I extract several pieces of information about the loop body (i.e. the number of instructions in the body) and print it. However, I need a way to associate this information with a specific loop - in other words, I need to print the "name" of the loop the information was extracted from.</p>

答:
I'm not sure what you mean by "name", but one way is to print debugging information (line number/column) associated with the loop latch block or something similar.

Another way is to use metadata to uniquely identify each loop and associate the extracted information with that identifier.

I had a similar need too, so I created a pass for that. Please note that this approach is sensitive to compiler optimizations and it does not preserve the ID when that happens (e.g. if a function that contains a loop is inlined). For best results (closer to the source) use it over IR that has been compiled with -O0. Further, optimizations can be applied afterwards, when you're done with your information gathering.

However, for something simple, I'd go with the first approach.


答:
You can use convert_from to turn binary data into a varchar:

```<code>select convert_from(decode('MTExMQ==', 'base64'), 'UTF8')
</code>```

But note that this can be lossy (or fail) if the input is really binary data (and not some text), such as an image file.

There should be no need to store Base64-encoded data in Postgresql. You can use one of the binary column types and store the data directly (and more compactly).

Title: In Postgresql how to get base64 decoded values as string instead of hex representation?

Body:
You can use convert_from to turn binary data into a varchar:

select convert_from(decode('MTExMQ==', 'base64'), 'UTF8')

But note that this can be lossy (or fail) if the input is really binary data (and not some text), such as an image file.

There should be no need to store Base64-encoded data in Postgresql. You can use one of the binary column types and store the data directly (and more compactly).


问:
How to set the RowStyle of a GridView row depending on a property of the Object that the row is being bound to
I'm currently using a GridView and I want to set the CssClass for the Row depending on a property of the object that the row is being bound to.

I tried the following but it does not work (see comments):

```<code><asp:GridView id="searchResultsGrid" runat="server" AllowPaging="true" PageSize="20" AutoGenerateColumns="false">

<!-- The following line doesn't work because apparently "Code blocks
aren't allowed in this context: -->
  <RowStyle CssClass="<%#IIF(DataBinder.Eval(Container.DataItem,"NeedsAttention","red","") %>

  <Columns>
<!--............-->
  </Columns>
</asp:GridView>
</code>```

Now I could simply handle the GridView's RowDataBound event and change the css class of the row there...but I'm trying to keep a clear separation between the UI and the page/business logic layers.

I have no idea how to accomplish this and I'm looking forward to hearing any suggestions.

Thanks,

-Frinny

答:
I know it has been almost a year, but if anyone else is trying this, try to subclass the GridView.

```<code>public class GridViewCSSRowBindable : GridView
{
  public string DataFieldRowCSSClass { get; set; }
  protected override void OnRowDataBound(GridViewRowEventArgs e)
  {
    base.OnRowDataBound(e);
    if (!string.IsNullOrEmpty(DataFieldRowCSSClass))
    {
      //This will throw an exception if the property does not exist on the data item:
      string cssClassString = DataBinder.Eval(e.Row.DataItem, DataFieldRowCSSClass) as string;
      if (!string.IsNullOrEmpty(cssClassString))
      {
        string sep = string.IsNullOrEmpty(e.Row.CssClass) ? string.Empty : " ";
        e.Row.CssClass += sep + cssClassString;
      }
    }
  }
}
</code>```

And then in your Page:

```<code><custom:GridViewCSSRowBindable ID="gvExample" runat="server" DataFieldRowCSSClass="RowCSS">
</custom:GridViewCSSRowBindable>
</code>```

The objects being bound to this example GridView should have a public string RowCSS property.

If you haven't used inherited controls before, you might have to look up how to set that up in your project.

Body:
I'm currently using a GridView and I want to set the CssClass for the Row depending on a property of the object that the row is being bound to.

I tried the following but it does not work (see comments):

<asp:GridView id="searchResultsGrid" runat="server" AllowPaging="true" PageSize="20" AutoGenerateColumns="false">

  <RowStyle CssClass="<%#IIF(DataBinder.Eval(Container.DataItem,"NeedsAttention","red","") %>

  <Columns>

  </Columns>
</asp:GridView>

Now I could simply handle the GridView's RowDataBound event and change the css class of the row there...but I'm trying to keep a clear separation between the UI and the page/business logic layers.

I have no idea how to accomplish this and I'm looking forward to hearing any suggestions.

Thanks,

-Frinny

Body:
I know it has been almost a year, but if anyone else is trying this, try to subclass the GridView.

public class GridViewCSSRowBindable : GridView
{
  public string DataFieldRowCSSClass { get; set; }
  protected override void OnRowDataBound(GridViewRowEventArgs e)
  {
    base.OnRowDataBound(e);
    if (!string.IsNullOrEmpty(DataFieldRowCSSClass))
    {
      //This will throw an exception if the property does not exist on the data item:
      string cssClassString = DataBinder.Eval(e.Row.DataItem, DataFieldRowCSSClass) as string;
      if (!string.IsNullOrEmpty(cssClassString))
      {
        string sep = string.IsNullOrEmpty(e.Row.CssClass) ? string.Empty : " ";
        e.Row.CssClass += sep + cssClassString;
      }
    }
  }
}

And then in your Page:

<custom:GridViewCSSRowBindable ID="gvExample" runat="server" DataFieldRowCSSClass="RowCSS">
</custom:GridViewCSSRowBindable>

The objects being bound to this example GridView should have a public string RowCSS property.

If you haven't used inherited controls before, you might have to look up how to set that up in your project.


问:
Issues in handling JsonArray while masking PI data
I have email data of about a PB in size and the structure of my json is as follows:

```<code>[{
"EmailID": 1234567,
"category": "Email",
"tsubject": "Regarding Complain no. XXXXXX",
"tto": "Email (abc@abc.com)",
"tCc": "", "tBcc": null,
"tfrom": "abc\abc@abc.in",
"Email": "",
"customer_emailID": "abc@abc.in",
"Customer_name": "abc",
"mail_time": "2016-11-08 12:26:54.0"
},{
"EmailID": 1234567,
"category": "Chat",
"tsubject": "Regarding Complain no. XXXXXX",
"tto": "Email (abc@abc.com)",
"tCc": "", "tBcc": null,
"tfrom": "abc\abc@abc.in",
"Email": "",
"customer_emailID": "abc@abc.in",
"Customer_name": "abc",
"mail_time": "2016-11-08 12:26:54.0"
},...]
</code>```

I am using the following code to mask the personal information for my json files (Email data):

```<code>    public class CUST_EMAIL{
    public static void main(String[] args) throws IOException {

            File dir = new File("D:\\CUst\\CUsto");
            File [] files  = dir.listFiles();
            Arrays.sort(files, new Comparator<Object>(){
            public int compare(Object o1, Object o2) {
                    return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                    long result = f2.lastModified() - f1.lastModified();
                    if( result > 0 ){
                    return 1;
                    } else if( result < 0 ){
                    return -1;
                    } else {
                    return 0;
                    }
            }
            });
            try {
            System.out.println( Arrays.asList(files ));
            System.out.println(files[0]);
            }
            catch (ArrayIndexOutOfBoundsException exception) {
            System.out.println(exception);
            }
            FileInputStream inputStream = null;

    String dd = files[0].getName();
            System.out.println(dd);
            FileOutputStream fout=new FileOutputStream("D:\\CUst\\custmask"+dd);

            Scanner sc = null;
            try {
                inputStream = new FileInputStream(files[0]);
                sc = new Scanner(inputStream, "UTF-8");
                while (sc.hasNextLine()) {
                   String line = sc.nextLine();
                   System.out.println(line);

                   JSONObject obj=new JSONObject(line);

                   List<String> fieldNames = Arrays.asList("tto","tCc", "tBcc","customer_emailID", "Customer_name");

                    byte[] content= mask(obj, fieldNames, "777777").getBytes();
                    fout.write(content);
                    fout.write("\n".getBytes());
                    // System.out.println(mask(obj, fieldNames, "0000000"));
                }
                // note that Scanner suppresses exceptions
                if (sc.ioException() != null) {
                    throw sc.ioException();
                }
            }

            finally {
                    fout.close();
                if (inputStream != null) {
                    inputStream.close();
                }
                if (sc != null) {
                    sc.close();
                }
            }
     if (files[0].exists()){
                    files[0].delete();
             } else {
                    System.out.println("no file to delete");
            }

    }

    public static String mask(JSONObject object, List<String> fieldNames, String mask) {

            Set<String> columns=object.keySet();
            //Field[] fields = object.getClass().getDeclaredFields();
       for(String i:columns) {
               if(fieldNames.contains(i)) {
                       object.put(i, mask);
               }
       }
       return object.toString();
    }

}
</code>```

When i run the program i get the following error:

```<code>Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:196)
at org.json.JSONObject.<init>(JSONObject.java:320)
at com.TALISMA_EMAIL.main(TALISMA_EMAIL.java:58)
</code>```

I think because of [ and ] at the beginning and end respectively, it is not able to understand jsonobject ;it needs jsonarray, but i need an advice as to how can i handle this email json structure using the code I have.

**Note:**Request you to suggest any changes if needed to the question

答:
remove the while loop and replace it by this: </p>

```<code>   StringBuilder sb = new StringBuilder();
     // loop over the lines to construct a stringbuilder
     //containing the input
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        System.out.println(line);

        sb.append(line);

    }
       // then perform your processing
    List<String> fieldNames = Arrays.asList("tto", "tCc", "tBcc", "customer_emailID", "Customer_name");
    try {
        JSONArray arr = new JSONArray(sb.toString());

        for (int i = 0; i < arr.length(); i++) {

            JSONObject obj = arr.getJSONObject(i);

            byte[] content = mask(obj, fieldNames, "777777").getBytes();
            fout.write(content);
            fout.write("\n".getBytes());

        }
    } catch (JSONException e) {
        // handle the exception
    }
</code>```

Body:
I have email data of about a PB in size and the structure of my json is as follows:

[{
"EmailID": 1234567,
"category": "Email",
"tsubject": "Regarding Complain no. XXXXXX",
"tto": "Email (abc@abc.com)",
"tCc": "", "tBcc": null,
"tfrom": "abc\abc@abc.in",
"Email": "",
"customer_emailID": "abc@abc.in",
"Customer_name": "abc",
"mail_time": "2016-11-08 12:26:54.0"
},{
"EmailID": 1234567,
"category": "Chat",
"tsubject": "Regarding Complain no. XXXXXX",
"tto": "Email (abc@abc.com)",
"tCc": "", "tBcc": null,
"tfrom": "abc\abc@abc.in",
"Email": "",
"customer_emailID": "abc@abc.in",
"Customer_name": "abc",
"mail_time": "2016-11-08 12:26:54.0"
},...]

I am using the following code to mask the personal information for my json files (Email data):

    public class CUST_EMAIL{
    public static void main(String[] args) throws IOException {

            File dir = new File("D:\\CUst\\CUsto");
            File [] files  = dir.listFiles();
            Arrays.sort(files, new Comparator<Object>(){
            public int compare(Object o1, Object o2) {
                    return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                    long result = f2.lastModified() - f1.lastModified();
                    if( result > 0 ){
                    return 1;
                    } else if( result < 0 ){
                    return -1;
                    } else {
                    return 0;
                    }
            }
            });
            try {
            System.out.println( Arrays.asList(files ));
            System.out.println(files[0]);
            }
            catch (ArrayIndexOutOfBoundsException exception) {
            System.out.println(exception);
            }
            FileInputStream inputStream = null;

    String dd = files[0].getName();
            System.out.println(dd);
            FileOutputStream fout=new FileOutputStream("D:\\CUst\\custmask"+dd);

            Scanner sc = null;
            try {
                inputStream = new FileInputStream(files[0]);
                sc = new Scanner(inputStream, "UTF-8");
                while (sc.hasNextLine()) {
                   String line = sc.nextLine();
                   System.out.println(line);

                   JSONObject obj=new JSONObject(line);

                   List<String> fieldNames = Arrays.asList("tto","tCc", "tBcc","customer_emailID", "Customer_name");

                    byte[] content= mask(obj, fieldNames, "777777").getBytes();
                    fout.write(content);
                    fout.write("\n".getBytes());
                    // System.out.println(mask(obj, fieldNames, "0000000"));
                }
                // note that Scanner suppresses exceptions
                if (sc.ioException() != null) {
                    throw sc.ioException();
                }
            }

            finally {
                    fout.close();
                if (inputStream != null) {
                    inputStream.close();
                }
                if (sc != null) {
                    sc.close();
                }
            }
     if (files[0].exists()){
                    files[0].delete();
             } else {
                    System.out.println("no file to delete");
            }

    }

    public static String mask(JSONObject object, List<String> fieldNames, String mask) {

            Set<String> columns=object.keySet();
            //Field[] fields = object.getClass().getDeclaredFields();
       for(String i:columns) {
               if(fieldNames.contains(i)) {
                       object.put(i, mask);
               }
       }
       return object.toString();
    }

}

When i run the program i get the following error:

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
at org.json.JSONObject.<init>(JSONObject.java:196)
at org.json.JSONObject.<init>(JSONObject.java:320)
at com.TALISMA_EMAIL.main(TALISMA_EMAIL.java:58)

I think because of [ and ] at the beginning and end respectively, it is not able to understand jsonobject ;it needs jsonarray, but i need an advice as to how can i handle this email json structure using the code I have.

**Note:**Request you to suggest any changes if needed to the question

Body:
remove the while loop and replace it by this:

   StringBuilder sb = new StringBuilder();
     // loop over the lines to construct a stringbuilder
     //containing the input
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        System.out.println(line);

        sb.append(line);

    }
       // then perform your processing
    List<String> fieldNames = Arrays.asList("tto", "tCc", "tBcc", "customer_emailID", "Customer_name");
    try {
        JSONArray arr = new JSONArray(sb.toString());

        for (int i = 0; i < arr.length(); i++) {

            JSONObject obj = arr.getJSONObject(i);

            byte[] content = mask(obj, fieldNames, "777777").getBytes();
            fout.write(content);
            fout.write("\n".getBytes());

        }
    } catch (JSONException e) {
        // handle the exception
    }


问:
How to mock a function call while initializing a variable in @Tested testObject in junit
I have a class A which has a private integer member b. Here is the structure of the class:

```<code>public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}
</code>```

I am testing some method of this class using jmockit with junit4 `

```<code>public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}
</code>```

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.

答: Problem solved. Just needed to add static to the setUp() method in @BeforeClass and mocked the call. Not the right way to do it but I was only allowed to change the test class.</p>

Body:
I have a class A which has a private integer member b. Here is the structure of the class:

public class A {

    private int b= Integer.parseInt(C.getValue(anyString));

    public int getB() {
       return b;
    }

    public void setB(int b) {
       this.b= b;
    }

}

I am testing some method of this class using jmockit with junit4 `

public class ATest {

    @Tested
    A a;

    @BeforeClass
    public void setUp() {
       //mock C.getValue
    }

    @Test public void test1() {
       //some test code
    }
}

but I am unable to mock the call (C.getValue(anyString)) thus the test fails while building the project. I have tried using @Before and @BeforeClass but none of those executed even once. Please suggest a way out.
Considering I can't change the main class A.


问:
keyboard appear and view scroll to top
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

```<code>   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }
</code>```

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

答:
When you tap inside a UITextView it becomes the first responder and if you read the documentation it clearly states:

... Some system views, like table views, help you by scrolling the first responder into view automatically. ...

This is a built-in feature.

Anyhow, you can try to remove the keyboard observer from the UITableView.

```<code>NotificationCenter.default.removeObserver(tableView, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
</code>```

UITextView

Title: keyboard appear and view scroll to top

Body:
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

Body:
When you tap inside a UITextView it becomes the first responder and if you read the documentation it clearly states:

... Some system views, like table views, help you by scrolling the first responder into view automatically. ...

This is a built-in feature.

Anyhow, you can try to remove the keyboard observer from the UITableView.

NotificationCenter.default.removeObserver(tableView, name: NSNotification.Name.UIKeyboardWillShow, object: nil)

UITextView


问:
How do I allow cross origin request
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

```<code> @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }
</code>```

But still he gets the error.What may be the cause.Any help is appreciated

```<code>OPTIONS https:my.domain/url 401 (Unauthorized)
</code>```

when it is a POST request.

Controller code:

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

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}
</code>```

答:
You can create your own CorsConfiguration

```<code>@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:63342");
        corsConfiguration.addAllowedHeader("Authorization");
        corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
};
</code>```

And add it to configuration.

```<code>.and().cors().configurationSource(corsConfigurationSource);
</code>```

And try using this annotation

```<code>@CrossOrigin
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I allow cross origin request

Body:
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }

But still he gets the error.What may be the cause.Any help is appreciated

OPTIONS https:my.domain/url 401 (Unauthorized)

when it is a POST request.

Controller code:

@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}

Body:
You can create your own CorsConfiguration

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:63342");
        corsConfiguration.addAllowedHeader("Authorization");
        corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
};

And add it to configuration.

.and().cors().configurationSource(corsConfigurationSource);

And try using this annotation

@CrossOrigin


问:
Node-RED function and multiple outputs
at the moment I've a little problem with one function. I'll create a function as switch. But I can't see that I route the msg block to the right output.

```<code>payloadJSON = JSON.parse(msg.payload, (key, value)=> {
  if(key == "changeType") {
    if (value === "create" ) {
        node.error('In: ' + value);
        return [ msg, null, null, null ];
    }else if(value === "update" ) {
        node.error('In: ' + value);
        return [ null, msg, null, null ];
    }else if(value === "delete" ) {
        node.error('In: ' + value);
        return [ null, null, msg, null ];
    }else{
        node.error('In: ' + "otherwise");
        return [ null, null, null, msg ];
    }
  }
});
</code>```

Yes I configure 4 Outputs in the function

I can see the node.error message in the log, but I can't see any Output from the attached Debug Output .

答:
Your return statements are inside the function you've passed to the JSON.parse call - so they are not returning anything to Node-RED.

You need to use node.send([msg,null ... ]); in place of those return statements.

Title: Node-RED function and multiple outputs

Body:
at the moment I've a little problem with one function. I'll create a function as switch. But I can't see that I route the msg block to the right output.

payloadJSON = JSON.parse(msg.payload, (key, value)=> {
  if(key == "changeType") {
    if (value === "create" ) {
        node.error('In: ' + value);
        return [ msg, null, null, null ];
    }else if(value === "update" ) {
        node.error('In: ' + value);
        return [ null, msg, null, null ];
    }else if(value === "delete" ) {
        node.error('In: ' + value);
        return [ null, null, msg, null ];
    }else{
        node.error('In: ' + "otherwise");
        return [ null, null, null, msg ];
    }
  }
});

Yes I configure 4 Outputs in the function

I can see the node.error message in the log, but I can't see any Output from the attached Debug Output .


问:
Php send to mail
I've been code my own web and currently stuck on making forms. I can't receive any email that I have input on my own website eventhought my php code is already Success.
Here's my form code in HTML

```<code><form action="booking-process.php" method="post">
        <div class="container fluid">
           <h2 class="midtext">Booking Service</h2>
           <h5 class="ff2 note">* Harap Melakukan Booking 1 hari sebelumnya.</h5>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="nama">Nama</label>
                <input type="text" name="nama" class="form-control">

                <label for="telp">Telepon/HP</label>
                <input type="text" name="telp" class="form-control">
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="plat">Nomor Polisi/Plat</label>
                <input type="text" name="plat" class="form-control">

                <label for="jam">Jam</label>
                <input type="text" name="jam" class="form-control" placeholder="HH:MM">
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="tanggal">Tanggal</label>
                <input type="text" name="tanggal" class="form-control" placeholder="DD/MM/YYYY">

                <label for="jenis" class="bookingdate">Jenis</label> <br>
                <select name="jenis" id="jenis" class="form-control">
                    <option value="BookingShowroom">Booking Showroom</option>
                    <option value="ToyotaHomeService">Toyota Home Service</option>
                </select>
            </div>
        </div>
        <div class="col-md-12">
            <button type="submit" class="mybtn ff2">BOOK</button>
        </div>
    </form>
</code>```

and here's my php code

```<code><?php

$to = "elmokun17@gmail.com";
$nama = $_REQUEST['nama'];
$telp = $_REQUEST['telp'];
$plat = $_REQUEST['plat'];
$jam = $_REQUEST['jam'];
$tanggal = $_REQUEST['tanggal'];
$jenis = $_REQUEST['jenis'];
$headers = "From: $from";

$fields = array();
$fields{"nama"} = $nama;
$fields{"telp"} = $telp;
$fields{"plat"} = $plat;
$fields{"jam"} = $jam;
$fields{"tanggal"} = $tanggal;
$fields{"jenis"} = $jenis;

$body = "FORM BOOKING\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$send = mail($to, $subject, $body, $headers);
echo 'SUCCESS'
?>
</code>```

答:
```<code>    <?php

    $to = "elmokun17@gmail.com";
    $nama = $_REQUEST['nama'];
    $telp = $_REQUEST['telp'];
    $plat = $_REQUEST['plat'];
    $jam = $_REQUEST['jam'];
    $tanggal = $_REQUEST['tanggal'];
    $jenis = $_REQUEST['jenis'];
    /*$headers = "From: $from";*/

    $fields = array();
    $fields{"nama"} = $nama;
    $fields{"telp"} = $telp;
    $fields{"plat"} = $plat;
    $fields{"jam"} = $jam;
    $fields{"tanggal"} = $tanggal;
    $fields{"jenis"} = $jenis;

    $subject = "Testing";
    $body = "FORM BOOKING\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

    $headers = "MIME-Version: 1.0" . "\n";
    $headers .= "Content-type: text/html; charset=utf-8" . "\n";
    $headers .= "From: $from" . "\n";

    if( mail($to, $subject, $body, $headers) )
    echo 'SUCCESS';
    else
    echo 'FAILURE';

    ?>
</code>```

Title: Php send to mail

Body:
I've been code my own web and currently stuck on making forms. I can't receive any email that I have input on my own website eventhought my php code is already Success.
Here's my form code in HTML

<form action="booking-process.php" method="post">

Booking Service

* Harap Melakukan Booking 1 hari sebelumnya.

                Nama
                <input type="text" name="nama" class="form-control">

                Telepon/HP
                <input type="text" name="telp" class="form-control">

                Nomor Polisi/Plat
                <input type="text" name="plat" class="form-control">

                Jam
                <input type="text" name="jam" class="form-control" placeholder="HH:MM">

                Tanggal
                <input type="text" name="tanggal" class="form-control" placeholder="DD/MM/YYYY">

                Jenis

                <select name="jenis" id="jenis" class="form-control">
                    <option value="BookingShowroom">Booking Showroom</option>
                    <option value="ToyotaHomeService">Toyota Home Service</option>
                </select>

            <button type="submit" class="mybtn ff2">BOOK</button>

    </form>

and here's my php code

<?php

$to = "elmokun17@gmail.com";
$nama = $_REQUEST['nama'];
$telp = $_REQUEST['telp'];
$plat = $_REQUEST['plat'];
$jam = $_REQUEST['jam'];
$tanggal = $_REQUEST['tanggal'];
$jenis = $_REQUEST['jenis'];
$headers = "From: $from";

$fields = array();
$fields{"nama"} = $nama;
$fields{"telp"} = $telp;
$fields{"plat"} = $plat;
$fields{"jam"} = $jam;
$fields{"tanggal"} = $tanggal;
$fields{"jenis"} = $jenis;

$body = "FORM BOOKING\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$send = mail($to, $subject, $body, $headers);
echo 'SUCCESS'
?>


问:
Consider the following code
```<code>import sys
n = input()
a = []
for i in range(n):
    temp = input()
    a[i].append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]
</code>```

code is running without any error but is giving error after the input

```<code>2
2 2
Traceback (most recent call last):
  File "1.py", line 5, in ?
    temp = input()
  File "<string>", line 1
    2 2
     ^
SyntaxError: unexpected EOF while parsing
</code>```

why is it not working and giving EOF error?

答:
a[i] doesn't work because the list a is only one array. If the array had lists inside of it, then a[i] would work.

As long as there are enough lists inside of the array to allow the for loop to run.

So, before you run the first for loop, you need to append n arrays ([]) to a

Title: Consider the following code

Body:
import sys
n = input()
a = []
for i in range(n):
    temp = input()
    a[i].append(temp)
for i in range(n):
    a[i] = a[i] - 1
    if a[i] ==0 and a[i+1] != 0 or a[i-1] != 0:
        print "NO"
        break
print "YES"
for i in range(n):
    print a[i]

code is running without any error but is giving error after the input

2
2 2
Traceback (most recent call last):
  File "1.py", line 5, in ?
    temp = input()
  File "<string>", line 1
    2 2
     ^
SyntaxError: unexpected EOF while parsing

why is it not working and giving EOF error?


问:
Modifying the javascript array and pushing it into array is copying to every element in array
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

```<code>var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));
</code>```

Output of the above code returns -

```<code>Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]
</code>```

答:
Complex values (i.e objects) are passed by reference.

In each iteration, you're simply working with the same object.
When you modify it, the modification reflects to all the passed references already present in your arr

var foo = { foo: 'bar' }

// you assume we are gonna copy the value of `foo` to `foo2`
var foo2 = foo

// change the value of the original object
foo.foo = 'baz'

// the change reflects to the other object,
// since it refers back to the original object
console.log(foo2)

// ..so we didn't copy, we just referred to it```

Body:
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

Output of the above code returns -

Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]


问:
Multiple primary key constraints?
I have a table like this:

```<code>CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)
</code>```

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

答:
Use following query to create new Unique Index on your table

```<code>CREATE UNIQUE INDEX IDX_Composite_index  ON BACAEN (CAET_KEY,BUUN_KEY);
</code>```

the above query works even if the table is populated but there should not be duplicates.

Title: Multiple primary key constraints?

Body:
I have a table like this:

CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

Body:
Use following query to create new Unique Index on your table

CREATE UNIQUE INDEX IDX_Composite_index  ON BACAEN (CAET_KEY,BUUN_KEY);

the above query works even if the table is populated but there should not be duplicates.


问:
Microsoft Bot Framework webcomponent is not working
Since this midmorning (11am uk time - 18th of July) we are having an important issues trying to open a Bot inside the webcomponent offered by the Bot Framework. Is it any know issue in the Bot Framework?

When we try to open the URL associated with the webcomponent (https://webchat.botframework.com/embed/[name_of_the_bot]?s=[key]) the response is:

"The service is unavailable."

It's an intermittent issue. It fails 1 out 2 times about.

答:
I have talked to Microsoft folks and they have fixed that issue. You can activate bot analytics to check the bot health via dashboard.

Analytics are not available until Application Insights has been enabled and configured. Application Insights will begin collecting data as soon as it is enabled. For example, if Application Insights was enabled a week ago for a six-month-old bot, it will have collected one week of data.

Note:Analytics requires both an Azure subscription and Application Insights resource. To access Application Insights, open the bot in the Bot Framework Portal and click Settings.

Create an Application Insights resource.

Open the bot in the dashboard. Click Settings and scroll down to the Analytics section.

Enter the information to connect the bot to Application Insights.
All fields are required.

AppInsights Instrumentation Key

To find this value, open Application Insights and navigate to Configure > Properties.
AppInsights API key

Provide an Azure App Insights API key. Learn how to generate a new API key. Only Read permission is required.
AppInsights Application ID

To find this value, open Application Insights and navigate to Configure > API Access.


问:
How do I add a piece of string from one df column to another in python/pandas?
I'm working in a pandas dataframe consisting of 10.000+ links to newspaper-article.  I would like to use the part of the string in my links displaying the subject/editorial of the articles, e.g /media/ or /sport/, to another column.

Example:
Col 1 contains these links:
www.theguardian.com/us-news/wikileaks-during-final-stages-of-election
www.theguardian.com/politics/parliament-to-have-final-

I.e. I want to make a def which iterates over the strings in Col 1 and if a string contains "/us-news/" then "US News" is added Col 2, just as if a string contains /politics/ then "Politics" is added ti Col 2.

Does anyone know how to do this?

答:
Use numpy.select with conditions by str.contains:

```<code>m1 = df['col1'].str.contains('/us-news/')
m2 = df['col1'].str.contains('/politics/')

df['col2'] = np.select([m1,m2], ['US News','Politics'], default='no match')
</code>```

Body:
Use numpy.select with conditions by str.contains:

m1 = df['col1'].str.contains('/us-news/')
m2 = df['col1'].str.contains('/politics/')

df['col2'] = np.select([m1,m2], ['US News','Politics'], default='no match')


问:
Rename files to increment filenumber using PowerShell?
I've got a bunch of files named

```<code>attachment.023940
attachment.024039
attachment.024041
attachment.024103
</code>```

etc...

I need to rename the files by incrementing the filenumber by a given number. (So that they match the right ID in a database)

I guess I could write a C# application that uses RegEx to parse the filename, but I assume this is a task that could be accomplished in PowerShell as well?

I've found several other threads on SO about using PowerShell to rename files, but none of them handled incrementing a filenumber.

I'm on Win7, so PowerShell 2.0 is available.

答:
```<code>Get-ChildItem attachment.* | Move-Item -Destination {
  "attachment.{0}" -f (([int]($_.Name -replace '.*\.(\d+)','$1')) + $increment)
}
</code>```

Body:
I've got a bunch of files named

attachment.023940
attachment.024039
attachment.024041
attachment.024103

etc...

I need to rename the files by incrementing the filenumber by a given number. (So that they match the right ID in a database)

I guess I could write a C# application that uses RegEx to parse the filename, but I assume this is a task that could be accomplished in PowerShell as well?

I've found several other threads on SO about using PowerShell to rename files, but none of them handled incrementing a filenumber.

I'm on Win7, so PowerShell 2.0 is available.


问:
Is there any way to change value of variable set by t-set in template odoo?
I need to change value of a variable set by t-set in a template by inherit that template, change value of variable and add some fields based on condition of that variable but can't find how can I do that without overwrite whole codes of template

Example I want to change zip_city in below template:

```<code> <template id="address" name="Address Management">
    <t t-call="website.layout">
       ...........
       <t t-set='zip_city' t-value='country and [x for x in country.get_address_fields() if x in ["zip", "city"]] or ["city", "zip"]'/>
       <t t-if="'zip' in zip_city and zip_city.index('zip') < zip_city.index('city')">
</code>```

答:
<?xml version="1.0" encoding="UTF-8"?>

<templates id="template">

    <t t-name="name of your template" t-extend="name of parent template">
        <t t-jquery="field name" t-operation="replace">
            // customization
        </t>
    </t>

</templates>
```

Try by this way..

Body:
I need to change value of a variable set by t-set in a template by inherit that template, change value of variable and add some fields based on condition of that variable but can't find how can I do that without overwrite whole codes of template

Example I want to change zip_city in below template:

 <template id="address" name="Address Management">
    <t t-call="website.layout">
       ...........
       <t t-set='zip_city' t-value='country and [x for x in country.get_address_fields() if x in ["zip", "city"]] or ["city", "zip"]'/>
       <t t-if="'zip' in zip_city and zip_city.index('zip') < zip_city.index('city')">

Body:
<?xml version="1.0" encoding="UTF-8"?>

<templates id="template">

    <t t-name="name of your template" t-extend="name of parent template">
        <t t-jquery="field name" t-operation="replace">
            // customization
        </t>
    </t>

</templates>

Try by this way..


问:
Split string in a column into three columns in the same table and insert it into new table
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

```<code>No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |
</code>```

I'd like to convert that table into like this :

```<code>No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |
</code>```

and save that to table try

I used this query :

```<code>Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade
</code>```

but it couldn't work...
Any advice or help?
Thanks in advance

答:
You try to Insert 4 columns with SELECT which select 5 columns :

```<code>Insert Into try (No, Unixdatetime1, Unixdatetime2,Unixdatetime3)
--               1       2             3            4
SELECT
   `No`, -- <--------1
   `Unixdatetime`, -- <--------2
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 )
    AS Unixdatetime1, -- <--------3
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1)
    AS Unixdatetime2,-- <--------4
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 )
    AS Unixdatetime3 -- <--------5
FROM tspade
</code>```

and this is not possible

Body:
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |

I'd like to convert that table into like this :

No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |

and save that to table try

I used this query :

Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade

but it couldn't work...
Any advice or help?
Thanks in advance

Body:
You try to Insert 4 columns with SELECT which select 5 columns :

Insert Into try (No, Unixdatetime1, Unixdatetime2,Unixdatetime3)
--               1       2             3            4
SELECT
   `No`, -- <--------1
   `Unixdatetime`, -- <--------2
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 )
    AS Unixdatetime1, -- <--------3
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1)
    AS Unixdatetime2,-- <--------4
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 )
    AS Unixdatetime3 -- <--------5
FROM tspade

and this is not possible


问:
DocumentReference.set(Object o) changes boolean field names
When using DocumentReference.set(object), boolean fields are changed. Fields with 'is' prefix get changed to normal field value

```<code>class Invitation {
    private boolean isRequested;
    private boolean isValid;
    private boolean isAccepted;
    private String lastName,firstName;
    private long sentOn;
}
</code>```

And when I push this object to the database using set() method the boolean values are changed in this way:

答:
This is an automatic translation so the getter can be named isBoolean rather than getBoolean.

In Android, you can use the @PropertyName annotation to rename a property, which will allow you to specify a different name (in this instance, the exact name), which Firebase should use as is:

```<code>class Invitation {
    private boolean isRequested;

    @PropertyName(value="isRequested")
    public boolean isRequested() {
        return this.isRequested;
    }

    @PropertyName(value="isRequested")
    public void setRequested(boolean value) {
        this.isRequested = value;
    }

    // ...
}
</code>```

However, I would suggest dropping the is prefix on the field names and instead only using it for the getter, like:

```<code>public boolean isRequested() {
    return this.requested;
}
</code>```

Body:
When using DocumentReference.set(object), boolean fields are changed. Fields with 'is' prefix get changed to normal field value

class Invitation {
    private boolean isRequested;
    private boolean isValid;
    private boolean isAccepted;
    private String lastName,firstName;
    private long sentOn;
}

And when I push this object to the database using set() method the boolean values are changed in this way:

Body:
This is an automatic translation so the getter can be named isBoolean rather than getBoolean.

In Android, you can use the @PropertyName annotation to rename a property, which will allow you to specify a different name (in this instance, the exact name), which Firebase should use as is:

class Invitation {
    private boolean isRequested;

    @PropertyName(value="isRequested")
    public boolean isRequested() {
        return this.isRequested;
    }

    @PropertyName(value="isRequested")
    public void setRequested(boolean value) {
        this.isRequested = value;
    }

    // ...
}

However, I would suggest dropping the is prefix on the field names and instead only using it for the getter, like:

public boolean isRequested() {
    return this.requested;
}


问:
Nav menu walker for sub sub menu
I want to add a unique class to the sub sub menu.
I am currently using this walker it only makes all submenu classes the same. Can someone help me to modify this to add a different class to the sub sub menu?

the sub menu class should be .wsmenu-submenu-sub

Thanks!

```<code>class CSS_Menu_Maker_Walker extends Walker {

  var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );

  function start_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=wsmenu-submenu>\n";
  }

  function end_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul>\n";
  }

  function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;

    /* Add active class */
    if(in_array('current-menu-item', $classes)) {
      $classes[] = 'active';
      unset($classes['current-menu-item']);
    }

    /* Check for children */
    $children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
    if (!empty($children)) {
      $classes[] = 'has-sub';
    }

    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

    $output .= $indent . '<li' . $id . $value . $class_names .'>';

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'><span>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    $item_output .= '</span></a>';
    $item_output .= $args->after;

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }

  function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
  }
}
</code>```

答:
Try this</p>

```<code>class CSS_Menu_Maker_Walker extends Walker {

  var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );

  function start_lvl( &$output, $depth = 0, $args = array() ) {

    $indent = str_repeat( "\t", $depth );
    if( $depth===0){
        $output .= "\n$indent<ul role=\"menu\" class=\"wsmenu\">\n";
    }else if( $depth===1){
        $output .= "\n$indent<ul role=\"menu\" class=\" wsmenu-submenu\">\n";
    }else if( $depth===2){
        $output .= "\n$indent<ul role=\"menu\" class=\"wsmenu-submenu-sub\">\n";
    }else{
        $output .= "\n$indent<ul role=\"menu\" class=\" wsmenutest\">\n";
    }

  }

  function end_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul>\n";
  }

  function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;

    /* Add active class */
    if(in_array('current-menu-item', $classes)) {
      $classes[] = 'active';
      unset($classes['current-menu-item']);
    }

    /* Check for children */
    $children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
    if (!empty($children)) {
      $classes[] = 'has-sub';
    }

    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

    $output .= $indent . '<li' . $id . $value . $class_names .'>';

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'><span>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    $item_output .= '</span></a>';
    $item_output .= $args->after;

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }

  function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
  }
}
</code>```

Title: Nav menu walker for sub sub menu

Body:
I want to add a unique class to the sub sub menu.
I am currently using this walker it only makes all submenu classes the same. Can someone help me to modify this to add a different class to the sub sub menu?

the sub menu class should be .wsmenu-submenu-sub

Thanks!

class CSS_Menu_Maker_Walker extends Walker {

  var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );

  function start_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent
\n";
  }

  function end_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent
\n";
  }

  function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;

    /* Add active class */
    if(in_array('current-menu-item', $classes)) {
      $classes[] = 'active';
      unset($classes['current-menu-item']);
    }

    /* Check for children */
    $children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
    if (!empty($children)) {
      $classes[] = 'has-sub';
    }

    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

    $output .= $indent . '
';

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    $item_output = $args->before;
    $item_output .= '';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    $item_output .= '';
    $item_output .= $args->after;

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }

  function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "
\n";
  }
}

Body:
Try this

class CSS_Menu_Maker_Walker extends Walker {

  var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' );

  function start_lvl( &$output, $depth = 0, $args = array() ) {

    $indent = str_repeat( "\t", $depth );
    if( $depth===0){
        $output .= "\n$indent<ul role=\"menu\" class=\"wsmenu\">\n";
    }else if( $depth===1){
        $output .= "\n$indent<ul role=\"menu\" class=\" wsmenu-submenu\">\n";
    }else if( $depth===2){
        $output .= "\n$indent<ul role=\"menu\" class=\"wsmenu-submenu-sub\">\n";
    }else{
        $output .= "\n$indent<ul role=\"menu\" class=\" wsmenutest\">\n";
    }

  }

  function end_lvl( &$output, $depth = 0, $args = array() ) {
    $indent = str_repeat("\t", $depth);
    $output .= "$indent</ul>\n";
  }

  function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    $class_names = $value = '';
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;

    /* Add active class */
    if(in_array('current-menu-item', $classes)) {
      $classes[] = 'active';
      unset($classes['current-menu-item']);
    }

    /* Check for children */
    $children = get_posts(array('post_type' => 'nav_menu_item', 'nopaging' => true, 'numberposts' => 1, 'meta_key' => '_menu_item_menu_item_parent', 'meta_value' => $item->ID));
    if (!empty($children)) {
      $classes[] = 'has-sub';
    }

    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

    $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
    $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

    $output .= $indent . '<li' . $id . $value . $class_names .'>';

    $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'><span>';
    $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    $item_output .= '</span></a>';
    $item_output .= $args->after;

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
  }

  function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
  }
}


问:
Rounding time to nearest quarter hour
I have a vector of POSIXct values and I would like to round them to the nearest quarter hour. I don't care about the day. How do I convert the values to hours and minutes?

For example, I would like the value

```<code>"2012-05-30 20:41:21 UTC"
</code>```

to be

```<code>"20:45"
</code>```

答:
Indeed, an old question with some helpful answers so far. The last one by giraffhere seems to be the most elegant. however, ist not floor_date but round_date which will do the trick:</p>

```<code>lubridate::round_date(x, "15 minutes")
</code>```

Title: Rounding time to nearest quarter hour

Body:
I have a vector of POSIXct values and I would like to round them to the nearest quarter hour. I don't care about the day. How do I convert the values to hours and minutes?

For example, I would like the value

"2012-05-30 20:41:21 UTC"

to be

"20:45"

Body:
Indeed, an old question with some helpful answers so far. The last one by giraffhere seems to be the most elegant. however, ist not floor_date but round_date which will do the trick:

lubridate::round_date(x, "15 minutes")


问:
Python phpserialize unexpected behaviour
Whilst trying to do a natas challange online, I wanted to convert the php code into python, but I do not get the expected result. Might be that I'm missing something from phpserialize

Why is it giving a different output?

Python code

```<code>import base64
from phpserialize import serialize

payload = {'initMsg': "", 'exitMsg': "<?php include('/etc/natas_webpass/natas27');?>", 'logFile': "img/code.php"}
new_ser = base64.encodestring(serialize(payload))
print(new_ser)
</code>```

PHP code

```<code><?php
class Logger{
        private $logFile;
        private $initMsg;
        private $exitMsg;

        function __construct(){
            $this->initMsg = "";
            $this->exitMsg = "<?php include('/etc/natas_webpass/natas27');?>";
            $this->logFile = "img/code.php";
        }
    }

$obj = new Logger();
echo base64_encode(serialize($obj));
?>
</code>```

The PHP code yields: Tzo2OiJMb2dnZXIiOjM6e3M6MTU6IgBMb2dnZXIAbG9nRmlsZSI7czoxMjoiaW1nL2NvZGUucGhwIjtzOjE1OiIATG9nZ2VyAGluaXRNc2ciO3M6MDoiIjtzOjE1OiIATG9nZ2VyAGV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1ZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO30=

The python code yields:

```<code>b'YTozOntzOjc6ImluaXRNc2ciO3M6MDoiIjtzOjc6ImV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1\nZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO3M6NzoibG9nRmlsZSI7czoxMjoi\naW1nL2NvZGUucGhwIjt9\n'
</code>```

答:
After reviewing the docs, I came up with a solution to convert the data to an object first and make serialize it afterwards.

@Maxim made the PHP code like python,

The below code makes the Python code like PHP

It feels like a tough way to do this, unsure if this could be made simpler.

```<code>class Logger():
    def __init__(self,initMsg,exitMsg,logFile):
        self.initMsg = initMsg
        self.exitMsg = exitMsg
        self.logFile = logFile

def object_hook(obj):
    if isinstance(obj, Logger):
        return phpobject('Logger', {b'\x00Logger\x00initMsg': obj.initMsg, b'\x00Logger\x00exitMsg': obj.exitMsg, b'\x00Logger\x00logFile': obj.logFile})

logger = Logger("", "<?php include('/etc/natas_webpass/natas27');?>", "img/code.php")
new_ser = base64.encodestring(serialize(logger, object_hook=object_hook)).replace(b'\n', b'').decode('ascii')
</code>```

Body:
Whilst trying to do a natas challange online, I wanted to convert the php code into python, but I do not get the expected result. Might be that I'm missing something from phpserialize

Why is it giving a different output?

Python code

import base64
from phpserialize import serialize

payload = {'initMsg': "", 'exitMsg': "<?php include('/etc/natas_webpass/natas27');?>", 'logFile': "img/code.php"}
new_ser = base64.encodestring(serialize(payload))
print(new_ser)

PHP code

<?php
class Logger{
        private $logFile;
        private $initMsg;
        private $exitMsg;

        function __construct(){
            $this->initMsg = "";
            $this->exitMsg = "<?php include('/etc/natas_webpass/natas27');?>";
            $this->logFile = "img/code.php";
        }
    }

$obj = new Logger();
echo base64_encode(serialize($obj));
?>

The PHP code yields: Tzo2OiJMb2dnZXIiOjM6e3M6MTU6IgBMb2dnZXIAbG9nRmlsZSI7czoxMjoiaW1nL2NvZGUucGhwIjtzOjE1OiIATG9nZ2VyAGluaXRNc2ciO3M6MDoiIjtzOjE1OiIATG9nZ2VyAGV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1ZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO30=

The python code yields:

b'YTozOntzOjc6ImluaXRNc2ciO3M6MDoiIjtzOjc6ImV4aXRNc2ciO3M6NDY6Ijw/cGhwIGluY2x1\nZGUoJy9ldGMvbmF0YXNfd2VicGFzcy9uYXRhczI3Jyk7Pz4iO3M6NzoibG9nRmlsZSI7czoxMjoi\naW1nL2NvZGUucGhwIjt9\n'

Body:
After reviewing the docs, I came up with a solution to convert the data to an object first and make serialize it afterwards.

@Maxim made the PHP code like python,

The below code makes the Python code like PHP

It feels like a tough way to do this, unsure if this could be made simpler.

class Logger():
    def __init__(self,initMsg,exitMsg,logFile):
        self.initMsg = initMsg
        self.exitMsg = exitMsg
        self.logFile = logFile

def object_hook(obj):
    if isinstance(obj, Logger):
        return phpobject('Logger', {b'\x00Logger\x00initMsg': obj.initMsg, b'\x00Logger\x00exitMsg': obj.exitMsg, b'\x00Logger\x00logFile': obj.logFile})

logger = Logger("", "<?php include('/etc/natas_webpass/natas27');?>", "img/code.php")
new_ser = base64.encodestring(serialize(logger, object_hook=object_hook)).replace(b'\n', b'').decode('ascii')


问:
How do you set the cout locale to insert commas as thousands separators?
Given the following code:

```<code>cout << 1000;
</code>```

I would like the following output:

```<code>1,000
</code>```

This can be done using std::locale, and the cout.imbue() function, but I fear I may be missing a step here.  Can you spot it?  I'm currently copying the current locale, and adding a thousands separator facet, but the comma never appears in my output.

```<code>template<typename T> class ThousandsSeparator : public numpunct<T> {
public:
    ThousandsSeparator(T Separator) : m_Separator(Separator) {}

protected:
    T do_thousands_sep() const  {
        return m_Separator;
    }

private:
    T m_Separator;
}

main() {
    cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));
    cout << 1000;
}
</code>```

答:
The default implementation of do_thousands_sep already returns ','. It looks like you should override do_grouping instead. do_grouping returns an empty string by default, which means no grouping. This means groups of three digits each:

```<code>string do_grouping() const
{
    return "\03";
}
</code>```

Body:
Given the following code:

cout << 1000;

I would like the following output:

1,000

This can be done using std::locale, and the cout.imbue() function, but I fear I may be missing a step here.  Can you spot it?  I'm currently copying the current locale, and adding a thousands separator facet, but the comma never appears in my output.

template<typename T> class ThousandsSeparator : public numpunct<T> {
public:
    ThousandsSeparator(T Separator) : m_Separator(Separator) {}

protected:
    T do_thousands_sep() const  {
        return m_Separator;
    }

private:
    T m_Separator;
}

main() {
    cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));
    cout << 1000;
}

Body:
The default implementation of do_thousands_sep already returns ','. It looks like you should override do_grouping instead. do_grouping returns an empty string by default, which means no grouping. This means groups of three digits each:

string do_grouping() const
{
    return "\03";
}


问:
keyboard appear and view scroll to top
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

```<code>   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }
</code>```

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

答:
I have encountered similar issues. when you scroll up and down then automatically call scrollViewWillBeginDragging method.

iOS use the UIScrollViewDelegate to determine the direction of the user's pan gesture.

Might be helpful to you following method.

Swift 4

```<code>func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    let translation: CGPoint = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if translation.y > 0 {
        // react to dragging down
    }
    else {
        // react to dragging up
        view.endEditing(true)
    }
}
</code>```

Objective C

```<code>- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];

    if(translation.y > 0)
    {
         // react to dragging down

    } else
    {
         // react to dragging up
          [self.view endEditing:YES];
    }
}
</code>```

Title: keyboard appear and view scroll to top

Body:
I have a problem in my code: when I tap on the UITextView and the keyboard is showing, there is a scroll to top (and I really don't know why !)
I have to scroll down myself to go back to the UITextView.

I'm in a tableView, and my cells have dynamic heights.

Here is a little demo of my problem:

I made some research and I tried this:

   @objc func keyboardWillShow(_ notification: NSNotification) {
      print("show")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
         }
      }
   }

   @objc func keyboardWillHide(_ notification: NSNotification) {
      print("hide")
      if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
         if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
         }
      }
   }

It sitll doesn't work. That's really weird because that's the only view where I have this problem.

Body:
I have encountered similar issues. when you scroll up and down then automatically call scrollViewWillBeginDragging method.

iOS use the UIScrollViewDelegate to determine the direction of the user's pan gesture.

Might be helpful to you following method.

Swift 4

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    let translation: CGPoint = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if translation.y > 0 {
        // react to dragging down
    }
    else {
        // react to dragging up
        view.endEditing(true)
    }
}

Objective C

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];

    if(translation.y > 0)
    {
         // react to dragging down

    } else
    {
         // react to dragging up
          [self.view endEditing:YES];
    }
}


问:
Assigning a class to the
 parent of an image
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

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

<p><strong>For items without images :</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-item" style="width: 157.4px; margin-right: 2px;">
  <li>

      <span>Day 1</span>

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

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};
```

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

答:
You could something like this, find an element within the children of an element and if it exist then then change the class of the parent</p>

```<code>$(document).ready(function(){
 var hasImg=$("div.carousel-item").find("img");

  if(hasImg.lenght>0)
    {
        $("div.carousel-item").removeClass("noImg");
    }
})
</code>```

Title: Assigning a class to the <div> parent of an image

Body:
ETA - Solution found. Nice work Stack Overflow beauties!! What would I do without you ;) ;)

I'm building a carousel, some items have images, others don't. I need to be able to target the items without images for styling, so I'm trying to add a class to the div that wraps the image if that makes sense?

What I have is this :
For items with images:

      Day 1

For items without images :

      Day 1

And what I'm trying to do using jquery is add the class 'noImg' to the div 'carousel-item' what I've tried is many variations of this sort of thing :

$("div.carousel-item").addClass("noImg");
if ($(this).hasClass('.img-responsive')) {
  ("div.carousel-item").removeClass("noImg")
};

I've tried variations of .children .parent I've tried doing it the other way around and doing .find on image-responsive and adding classes that way.

Any suggestions of the 'you dope, you're missing this obvious thing' would very much be appreciated, Thanks very much in advance.

Body:
You could something like this, find an element within the children of an element and if it exist then then change the class of the parent

$(document).ready(function(){
 var hasImg=$("div.carousel-item").find("img");

  if(hasImg.lenght>0)
    {
        $("div.carousel-item").removeClass("noImg");
    }
})


问:
Validation for digit only in an EditText
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?</p>

```<code>public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}
</code>```

答:
Add digits and inputType properties in your EditText. digits property will allow user to enter specific character into your EditText so you don't need to add filter.

```<code>     <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:digits="0123456789"/>
</code>```

And you need to initialize your EditText before you use,

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

    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

    addDataToDisplay();
}
</code>```

Body:
I am trying to make a simple functionality which the user inserts 2 numbers and a toast present the sum...
First, in order to do so, I would like to verify the user insert only digits. If not, I would like to set toast message (error) explains that only digits allow here. I use a boolean isdigit (EditText input) method.
However, I get an error -maybe because the for loop cannot accept null?

public class MainActivity extends AppCompatActivity {
private EditText firstIntCB, secundIntCB;
private Button getProductCB;

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

    addDataToDisplay();
}

public void addDataToDisplay() {
   if (isdigit(firstIntCB)==true && isdigit(secundIntCB)==true){
        firstIntCB = (EditText)findViewById(R.id.firstNumber);
        secundIntCB = (EditText)findViewById(R.id.secundNumber);
        getProductCB =(Button)findViewById(R.id.GetProduct);

        getProductCB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer intFirst = Integer.parseInt(firstIntCB.getText().toString());
                Integer intSec = Integer.parseInt(secundIntCB.getText().toString());
                String product = Integer.toString((int)Math.pow(intFirst,intSec));
                Toast.makeText
                        (getApplicationContext(),String.valueOf(product), Toast.LENGTH_LONG).show();
            }
        });
    }
}

public boolean isdigit(EditText input) {
    String data=input.getText().toString().trim();
    for(int i=0;i<data.length();i++)
    {
        if (!Character.isDigit(data.charAt(i)))
            return false;

    }
    return true;
}

Body:
Add digits and inputType properties in your EditText. digits property will allow user to enter specific character into your EditText so you don't need to add filter.

     <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:digits="0123456789"/>

And you need to initialize your EditText before you use,

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

    firstIntCB = (EditText)findViewById(R.id.firstNumber);
    secundIntCB = (EditText)findViewById(R.id.secundNumber);
    getProductCB =(Button)findViewById(R.id.GetProduct);

    addDataToDisplay();
}


问:
AnyLogic: Calculating the sum of all values in a collection
I have an agent-based simulation where I have a collection called collection_dailyInfection which has the numbers of new infections that arise on a daily basis. The collection looks a bit like this:

Day 1: 0

Day 2: 3

Day 4: 3

Day 5: 6

Day 6: 1

.  .  .

I'm now trying to write a function that adds up the total number of infections on any particular day. For example: on Day 6- total infections = 0+3+3+6+1 = 13.

The syntax for calculating the sum is:
double sum( collection, value ) - Returns the sum of values in the given collection.

For my particular example, this would be double sum( collection_dailyInfection, *value*), but I'm not sure what I should put in the 'value' argument. Could some help me out please?

答:
These functions (methods) provided by AnyLogic for calculating statistics on collections use a fairly advanced feature of Java: the functional programming stuff added in Java 8. So the required syntax is not at all obvious. The main help page (AnyLogic Help --> Parameters, Variables, Collections --> Collections --> Functions to collect statistics on a collection) has a link to the UtilitiesCollection class where these methods are defined.

You have a collection collection_dailyInfection of daily infection counts; let's assume you specified this in AnyLogic as being of collection class  ArrayList with elements class as int, and you used a cyclic event to add the count each simulated day.

Your sum expression should therefore be

sum( collection_dailyInfection, c -> c.doubleValue())

The c is just an arbitrary identifier for the current element that the sum is on (effectively this sum method is looping through your collection) and the -> is a special Java 8 functional programming operator. When you specify type int in AnyLogic for your collection contents, they are actually stored as Integer objects which are object versions of the int primitives. (See any Java textbook to understand this.)

Thus, each entry (Integer object) has a method doubleValue which returns the value of the integer as a double. (AnyLogic's sum function needs the 'value' bit to be a double; i.e., a real (floating point) number.)

(anupam691997's answer is a 'pure Java' solution ignoring the AnyLogic context.)