问:
SiteMinder and EJB 3.0 - Reading user login id
I'm working on an application that uses EJB 3.0 and exposes its methods as web services.

SiteMinder is used to provide authentication. After successful login, the request header will contain the user's login id which can be read by

```<code>request.getHeader("sm_user");
</code>```

This information is available at the WebService end point and can be read in a Servlet Filter also.

But how do I get this information in the EJB layer without explicitly passing it as a parameter? How can I get/set the credentials using a Principal object with the help of an Interceptor?

Please provide your valuable inputs.

答:
In EJB3.0 your web application and EJB runs in a different containers and EJBs cannot access any web container data.
you will have to pass this information.</p>

Body:
I'm working on an application that uses EJB 3.0 and exposes its methods as web services.

SiteMinder is used to provide authentication. After successful login, the request header will contain the user's login id which can be read by

request.getHeader("sm_user");

This information is available at the WebService end point and can be read in a Servlet Filter also.

But how do I get this information in the EJB layer without explicitly passing it as a parameter? How can I get/set the credentials using a Principal object with the help of an Interceptor?

Please provide your valuable inputs.


来源: stackexchange

问:
Rename JProperty in json.net
I've the following property

```<code>{
  "bad":
  {
    "Login": "someLogin",
    "Street": "someStreet",
    "House": "1",
    "Flat": "0",
    "LastIndication":
    [
      "230",
      "236"
    ],
    "CurrentIndication":
    [
      "263",
      "273"
    ],
    "Photo":
    [
      null,
      null
    ]
  }
}
</code>```

and how can I rename this from 'bad' to 'good' for example. Yes, I saw the extension method by Abi Bellamkonda

```<code>public static class NewtonsoftExtensions
{
    public static void Rename(this JToken token, string newName)
    {
        var parent = token.Parent;
        if (parent == null)
            throw new InvalidOperationException("The parent is missing.");
        var newToken = new JProperty(newName, token);
        parent.Replace(newToken);
    }
}
</code>```

but it got this exeption

Can not add Newtonsoft.Json.Linq.JProperty to
  Newtonsoft.Json.Linq.JProperty.

答:
Somewhat counterintuitively, that extension method assumes that the token you are passing to it is the value of a JProperty, not the JProperty itself.  Presumably, this is to make it easy to use with the square bracket syntax:

```<code>JObject jo = JObject.Parse(json);
jo["bad"].Rename("good");
</code>```

If you have a reference to the property, you can still use that extension method if you call it on the property's Value like this:

```<code>JObject jo = JObject.Parse(json);
JProperty prop = jo.Property("bad");
prop.Value.Rename("good");
</code>```

However, that makes the code seem confusing.  It would be better to improve the the extension method so that it will work in both situations:

```<code>public static void Rename(this JToken token, string newName)
{
    if (token == null)
        throw new ArgumentNullException("token", "Cannot rename a null token");

    JProperty property;

    if (token.Type == JTokenType.Property)
    {
        if (token.Parent == null)
            throw new InvalidOperationException("Cannot rename a property with no parent");

        property = (JProperty)token;
    }
    else
    {
        if (token.Parent == null || token.Parent.Type != JTokenType.Property)
            throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename");

        property = (JProperty)token.Parent;
    }

    // Note: to avoid triggering a clone of the existing property's value,
    // we need to save a reference to it and then null out property.Value
    // before adding the value to the new JProperty.
    // Thanks to @dbc for the suggestion.

    var existingValue = property.Value;
    property.Value = null;
    var newProperty = new JProperty(newName, existingValue);
    property.Replace(newProperty);
}
</code>```

Then you can do:

```<code>JObject jo = JObject.Parse(json);
jo.Property("bad").Rename("good");  // works with property reference
jo["good"].Rename("better");        // also works with square bracket syntax
</code>```

Fiddle: https://dotnetfiddle.net/RSIdfx

ContentLicense: CC BY-SA 3.0

Title: Rename JProperty in json.net

Body:
I've the following property

{
  "bad":
  {
    "Login": "someLogin",
    "Street": "someStreet",
    "House": "1",
    "Flat": "0",
    "LastIndication":
    [
      "230",
      "236"
    ],
    "CurrentIndication":
    [
      "263",
      "273"
    ],
    "Photo":
    [
      null,
      null
    ]
  }
}

and how can I rename this from 'bad' to 'good' for example. Yes, I saw the extension method by Abi Bellamkonda

public static class NewtonsoftExtensions
{
    public static void Rename(this JToken token, string newName)
    {
        var parent = token.Parent;
        if (parent == null)
            throw new InvalidOperationException("The parent is missing.");
        var newToken = new JProperty(newName, token);
        parent.Replace(newToken);
    }
}

but it got this exeption

Can not add Newtonsoft.Json.Linq.JProperty to
  Newtonsoft.Json.Linq.JProperty.

Body:
Somewhat counterintuitively, that extension method assumes that the token you are passing to it is the value of a JProperty, not the JProperty itself.  Presumably, this is to make it easy to use with the square bracket syntax:

JObject jo = JObject.Parse(json);
jo["bad"].Rename("good");

If you have a reference to the property, you can still use that extension method if you call it on the property's Value like this:

JObject jo = JObject.Parse(json);
JProperty prop = jo.Property("bad");
prop.Value.Rename("good");

However, that makes the code seem confusing.  It would be better to improve the the extension method so that it will work in both situations:

public static void Rename(this JToken token, string newName)
{
    if (token == null)
        throw new ArgumentNullException("token", "Cannot rename a null token");

    JProperty property;

    if (token.Type == JTokenType.Property)
    {
        if (token.Parent == null)
            throw new InvalidOperationException("Cannot rename a property with no parent");

        property = (JProperty)token;
    }
    else
    {
        if (token.Parent == null || token.Parent.Type != JTokenType.Property)
            throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename");

        property = (JProperty)token.Parent;
    }

    // Note: to avoid triggering a clone of the existing property's value,
    // we need to save a reference to it and then null out property.Value
    // before adding the value to the new JProperty.
    // Thanks to @dbc for the suggestion.

    var existingValue = property.Value;
    property.Value = null;
    var newProperty = new JProperty(newName, existingValue);
    property.Replace(newProperty);
}

Then you can do:

JObject jo = JObject.Parse(json);
jo.Property("bad").Rename("good");  // works with property reference
jo["good"].Rename("better");        // also works with square bracket syntax

Fiddle: https://dotnetfiddle.net/RSIdfx

ContentLicense: CC BY-SA 4.0


问:
Multiline text box
I  have a text box and a regular expression for the string(path of a file) i.e:

```<code> "(((https)[:]{1}[//]{2}[a-z0-9]*.xyz[/]{1}([A-Za-z]*[/]{1}[A-Za-z]*.json(/n)?))?)+";
</code>```

to be entered in the text box. Now I want to enter multiple strings in the text box separated by /n.

How can it be done?

答:
You can add [\r\n]+ to you're regex , that will match multiple consecutive new-lines.

You can add examples of the string you're trying to match .

Hope that'll help you

Title: Multiline text box

Body:
I  have a text box and a regular expression for the string(path of a file) i.e:

 "(((https)[:]{1}[//]{2}[a-z0-9]*.xyz[/]{1}([A-Za-z]*[/]{1}[A-Za-z]*.json(/n)?))?)+";

to be entered in the text box. Now I want to enter multiple strings in the text box separated by /n.

How can it be done?


问:
Parse nested XML from URL
I'm currently working on a .NET 4.6 console application. I need to parse a nested XML from an URL and transform the XML into an object list.

The URL for the sample XML is the following:

https://www.w3schools.com/xml/cd_catalog.xml

The XML looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>
</code>```

My corresponding C# classes look like this:

```<code>[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    List<Cd> Cds { get; set; }
}

[XmlRoot(ElementName = "CD")]
public class Cd
{
    [XmlElement("TITLE")]
    public string Title { get; set; }
    [XmlElement("ARTIST")]
    public string Artist { get; set; }
    [XmlElement("COUNTRY")]
    public string Country { get; set; }
    [XmlElement("COMPANY")]
    public string Company { get; set; }
    [XmlElement("PRICE")]
    public double Price { get; set; }
    [XmlElement("YEAR")]
    public int Year { get; set; }
}
</code>```

My program class looks like this:

```<code>class Program
{
    static void Main(string[] args)
    {
        Init();
    }

    public static void Init() {

        var url = "https://www.w3schools.com/xml/cd_catalog.xml";

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load(url);

        var catalog = myXmlDocument.InnerXml.ToString();

        var result = Deserialize<Catalog>(catalog);
        // result is null :(

        Console.ReadKey();
    }

    public static T Deserialize<T>(string xmlText)
    {
        try
        {
            var stringReader = new StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

So far so good, my variable catalog consists out of an XML string, but somehow the XML doesn't get parsed correctly. I always get null as a return result. Perhaps it's because of my class definitions.

What do you think, do you have an idea on how to solve this issue? To retrieve an List<Cd> instead of null.

答:
```<code>List<Cd> Cds { get; set; }
</code>```

<p>Change this line to </p>

```<code>Public List<Cd> Cds { get; set; }
</code>```

Title: Parse nested XML from URL

Body:
I'm currently working on a .NET 4.6 console application. I need to parse a nested XML from an URL and transform the XML into an object list.

The URL for the sample XML is the following:

https://www.w3schools.com/xml/cd_catalog.xml

The XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
    <CD>
        <TITLE>Empire Burlesque</TITLE>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <TITLE>Hide your heart</TITLE>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

My corresponding C# classes look like this:

[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
    [XmlElement("CD")]
    List<Cd> Cds { get; set; }
}

[XmlRoot(ElementName = "CD")]
public class Cd
{
    [XmlElement("TITLE")]
    public string Title { get; set; }
    [XmlElement("ARTIST")]
    public string Artist { get; set; }
    [XmlElement("COUNTRY")]
    public string Country { get; set; }
    [XmlElement("COMPANY")]
    public string Company { get; set; }
    [XmlElement("PRICE")]
    public double Price { get; set; }
    [XmlElement("YEAR")]
    public int Year { get; set; }
}

My program class looks like this:

class Program
{
    static void Main(string[] args)
    {
        Init();
    }

    public static void Init() {

        var url = "https://www.w3schools.com/xml/cd_catalog.xml";

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load(url);

        var catalog = myXmlDocument.InnerXml.ToString();

        var result = Deserialize<Catalog>(catalog);
        // result is null :(

        Console.ReadKey();
    }

    public static T Deserialize<T>(string xmlText)
    {
        try
        {
            var stringReader = new StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

So far so good, my variable catalog consists out of an XML string, but somehow the XML doesn't get parsed correctly. I always get null as a return result. Perhaps it's because of my class definitions.

What do you think, do you have an idea on how to solve this issue? To retrieve an List<Cd> instead of null.

Body:
List<Cd> Cds { get; set; }

Change this line to

Public List<Cd> Cds { get; set; }


问:
Using linked Resources in Custom REST Controller with Spring REST JPA
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

```<code>@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}
</code>```

and users Own Projects:

```<code>@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}
</code>```

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

```<code>@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}
</code>```

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

```<code>{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}
</code>```

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

答:
If you want to stick with the url params you could change the @RequestParam User userResource to @RequestParam String userId

And then in your createProject code have something along the lines of

```<code>User user = userRepo.findOne(userId);
project.user = user;
....
projectRepo.save(project);
</code>```

If it was me I'd define a CreateProjectRequest object which you pass in, e.g.

```<code>{
   "userId" : "1",
   "formField1" : "whatever",
   "formField2" : "whatever"
}
</code>```

And change your createProject to

```<code>createProject(@RequestBody CreateProjectRequest createProjectRequest)
    ...
    project.setField1(createProjectRequest.getFormField1());
    ...

    User user = userRepo.findOne(createProjectRequest.getUserId());
    project.user = user;
    ....
    projectRepo.save(project);
</code>```

Body:
I am developing a set of rest resources over a database and exposing the core CRUD functionality using Spring Data Rest to directly interact with the Repositories.

In my simplified sample I have Users:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}

and users Own Projects:

@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}

Directly interacting with the repositories is fine, so for creating Users (other other simple entities), the problem comes with creating Projects.  Projects have a large number of server derived fields based on the users form input, so I wrote a custom controller to generate them and persist the result.
In order to persist the result, I need to associate the Project with it's owning User.  I want my client to be able to use the user Link for this, just as when creating a new entity by going direct to the repository (going direct to the repository just works):

@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}

When I call:

http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

I get:

{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}

If I change userResource to type Resource then I get a different error:

"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

I can't find any reference to using repository URI's in custom controllers in the docs, the closest I found was Resolving entity URI in custom controller (Spring HATEOAS) but the API's have changed since that was written and I have not been able to get it to work.

Body:
If you want to stick with the url params you could change the @RequestParam User userResource to @RequestParam String userId

And then in your createProject code have something along the lines of

User user = userRepo.findOne(userId);
project.user = user;
....
projectRepo.save(project);

If it was me I'd define a CreateProjectRequest object which you pass in, e.g.

{
   "userId" : "1",
   "formField1" : "whatever",
   "formField2" : "whatever"
}

And change your createProject to

createProject(@RequestBody CreateProjectRequest createProjectRequest)
    ...
    project.setField1(createProjectRequest.getFormField1());
    ...

    User user = userRepo.findOne(createProjectRequest.getUserId());
    project.user = user;
    ....
    projectRepo.save(project);


问:
Android first time animation is not smooth
I am trying one animation to slide up imageView from bottom of screen to center of screen but when I do this animation for very first time it's not smooth but when do animation for second time it's normal and smooth. I have tried almost everything but I couldn't solve my issue.

This is my anim file

```<code><?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">
    <alpha
        android:duration="2000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
    <scale xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="700"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.5"
        android:toYScale="1.5"/>
    <translate
        android:fromXDelta="0%"
        android:toXDelta="0%"
        android:fromYDelta="300%"
        android:toYDelta="0%"
        android:duration="2000"
        android:zAdjustment="top" />
</set>
</code>```

and this how I am displaying on my fragment

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    private Animation anim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startAnimations();
    }

    private void startAnimations() {
        anim = AnimationUtils.loadAnimation(this, R.anim.slide_up_animation);
        ImageView imageView = (ImageView) findViewById(R.id.splash);
        imageView.startAnimation(anim);
    }
}
</code>```

答:
the reason is because you are doing this at the very beginning,

use:

```<code>try {
    Thread.sleep(400);
} catch (InterruptedException e) {
    e.printStackTrace();
}
startAnimations();
</code>```

Body:
I am trying one animation to slide up imageView from bottom of screen to center of screen but when I do this animation for very first time it's not smooth but when do animation for second time it's normal and smooth. I have tried almost everything but I couldn't solve my issue.

This is my anim file

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">
    <alpha
        android:duration="2000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0" />
    <scale xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="700"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="1.5"
        android:toYScale="1.5"/>
    <translate
        android:fromXDelta="0%"
        android:toXDelta="0%"
        android:fromYDelta="300%"
        android:toYDelta="0%"
        android:duration="2000"
        android:zAdjustment="top" />
</set>

and this how I am displaying on my fragment

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
    private Animation anim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startAnimations();
    }

    private void startAnimations() {
        anim = AnimationUtils.loadAnimation(this, R.anim.slide_up_animation);
        ImageView imageView = (ImageView) findViewById(R.id.splash);
        imageView.startAnimation(anim);
    }
}

Body:
the reason is because you are doing this at the very beginning,

use:

try {
    Thread.sleep(400);
} catch (InterruptedException e) {
    e.printStackTrace();
}
startAnimations();


问:
How can I implement the PropertyChange event?
I wish to get the details of what has been changed in a MailItem.

I have been able to get ItemChange to trigger based upon Application.Session.Folders("TargetFolder") to a variable as such:
Private Sub olInvMbxItems_ItemChange(ByVal X As Object).

I would like to know the property changed in X. If I pass X to an global variable for Private Sub X_PropertyChange(ByVal x As Object), it will miss the first iteration as X was not initialized on the first pass of ItemChange.

How can I monitor a folder of MailItems to detect Category changes. Whilst ItemChange does this, it gives duplication of action, if I look for specific categories, as many changes trigger ItemChange as mentioned here:

Handle ItemChange event when outlook appointments are dismissed

and here:

Outlook Macro that will copy an email I flag and put it in a folder

The binary flag for the UserProperties in the second item will not function as it is not a one-off event.

Outlook Events VBA says to use PropertyChange but doesn't provide a technique for implementation.

答:
Here is a method that works for a single selection. Refinement yet needed, but this is a starting point:

```<code>Private WithEvents olExplorer As Outlook.Explorer
Private olCurSel As Selection
Private WithEvents olCurSelItem As Outlook.MailItem

Private Sub olExplorer_SelectionChange()
  Set olCurSel = olExplorer.Selection
  Set olCurSelItem = Nothing
  Dim i As Long
  For i = 1 To olCurSel.Count
    If TypeName(olCurSel.Item(i)) = "MailItem" Then
      Set olCurSelItem = olCurSel.Item(i)
    End If
  Next i
End Sub

Private Sub olCurSelItem_PropertyChange(ByVal Name As String)
  Debug.Print Name; " is what changed!"
End Sub
</code>```

Using Outlook.Explorer.Selection we can know that an item has been selected. We can then assign that item to and Outlook.MailItem conditionally and use the PropertyChange event of that Outlook.MailItem trigger the action we wish to take.

Problems:

Does not handle multiple selections

SelectionChange is triggered by the Reading Pane on each selection as well. Thus it is fired twice if the reading pane is open. As written above, olCurSelItem is set twice each SelectionChange.

This is only triggered by local changes. Other systems with access to the mailbox may change the item and it will not trigger the action.

Body:
Here is a method that works for a single selection. Refinement yet needed, but this is a starting point:

Private WithEvents olExplorer As Outlook.Explorer
Private olCurSel As Selection
Private WithEvents olCurSelItem As Outlook.MailItem

Private Sub olExplorer_SelectionChange()
  Set olCurSel = olExplorer.Selection
  Set olCurSelItem = Nothing
  Dim i As Long
  For i = 1 To olCurSel.Count
    If TypeName(olCurSel.Item(i)) = "MailItem" Then
      Set olCurSelItem = olCurSel.Item(i)
    End If
  Next i
End Sub

Private Sub olCurSelItem_PropertyChange(ByVal Name As String)
  Debug.Print Name; " is what changed!"
End Sub

Using Outlook.Explorer.Selection we can know that an item has been selected. We can then assign that item to and Outlook.MailItem conditionally and use the PropertyChange event of that Outlook.MailItem trigger the action we wish to take.

Problems:

Does not handle multiple selections

SelectionChange is triggered by the Reading Pane on each selection as well. Thus it is fired twice if the reading pane is open. As written above, olCurSelItem is set twice each SelectionChange.

This is only triggered by local changes. Other systems with access to the mailbox may change the item and it will not trigger the action.


问:
How to send a notification to another PC?
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that?

Thanks,

kampi

答: Make your application a Growl client</p>

ContentLicense: CC BY-SA 2.5

Body: Make your application a Growl client


问:
build drupal 8 custom classes for shared functionality between modules (shared library of php classes for drupal)
Background:

I built multiple custom modules in Drupal 7, that use shared classes from a base collection.  Originally I designed the base collection as a single module with an empty form (which is never displayed), and each form module referenced the needed class(es) and related member method(s) within that shared base module.  I am looking at upgrading the modules to Drupal 8 and am wondering if there is a more logical way to implement the needed "shared" module, rather than using a form module containing no form.

Question:

Is it possible to create a shared library (of classes) in drupal 8 that custom modules can reference?

To illustrate the question:
There is a "Category Manager" module which allows the user to manage a categories for a document collection.  That Category Manager implements a class that provides member methods for adding/updating/deleting/getting category data.  There is also a "Document Manager" module which allows management of documents in the same way.  Because the documents are associated with categories, The Document Manager Module references the same "category" class.  Obviously, this "category" class is defined within the base module (which both manager modules refer to).  There are several other examples of shared classes.

答:
I think you can use two approaches in here.

I would recommend to package your share library as a composer dependency and include this into your Drupal, below is a link with more information about it

https://www.drupal.org/node/2514612

A second approach is to create and enable a module which has all the share functionality

Drupal 8 PSR-4, so as long as you follow it, the classes of your active module will be available for other, here is more info

https://www.drupal.org/docs/develop/coding-standards/psr-4-namespaces-and-autoloading-in-drupal-8


问:
How do I set GIT_SSL_NO_VERIFY for specific repos only?
I have to use a git server without proper certificates, but I don't want to have to do

```<code>env GIT_SSL_NO_VERIFY=true git command
</code>```

every single time I do a git operation. But I would also like to leave SSL enabled for other git repositories. Is there a way to make this local to a single repo?

答:
There is an easy way of configuring GIT to handle your server the right way.
Just add an specific http section for your git server and specify which certificate (Base64 encoded) to trust:

~/.gitconfig

```<code>[http "https://repo.your-server.com"]
# windows path use double back slashes
#  sslCaInfo = C:\\Users\\<user>\\repo.your-server.com.cer
# unix path to certificate (Base64 encoded)
sslCaInfo = /home/<user>/repo.your-server.com.cer
</code>```

This way you will have no more SSL errors and validate the (usually) self-signed certificate. This is the best way to go, as it protects you from man-in-the-middle attacks. When you just disable ssl verification you are vulnerable to these kind of attacks.

https://git-scm.com/docs/git-config#git-config-httplturlgt

Body:
I have to use a git server without proper certificates, but I don't want to have to do

env GIT_SSL_NO_VERIFY=true git command

every single time I do a git operation. But I would also like to leave SSL enabled for other git repositories. Is there a way to make this local to a single repo?

Body:
There is an easy way of configuring GIT to handle your server the right way.
Just add an specific http section for your git server and specify which certificate (Base64 encoded) to trust:

~/.gitconfig

[http "https://repo.your-server.com"]
# windows path use double back slashes
#  sslCaInfo = C:\\Users\\<user>\\repo.your-server.com.cer
# unix path to certificate (Base64 encoded)
sslCaInfo = /home/<user>/repo.your-server.com.cer

This way you will have no more SSL errors and validate the (usually) self-signed certificate. This is the best way to go, as it protects you from man-in-the-middle attacks. When you just disable ssl verification you are vulnerable to these kind of attacks.

https://git-scm.com/docs/git-config#git-config-httplturlgt


问:
filemanager plugin - TinyMCE - the server response wasn't JSON format
recently we updated a server from php 5.3 to php 7, actually I don't know if the update causes this issue, but when I go to insert a file on TinyMCE javascirpt I receive this error message:

The server response wasn't JSON format

I haven't found anything on internet about it.

here is Json_data:

```<code>{"method":"fm.insertFiles","params":[{"path0":"{0}/Sage.JPG"}],"id":"c0"}
</code>```

here is TinyMCE configuration:

```<code>    tinyMCE.init({
    // General options
        mode : "exact",
        elements : "msg_body",
    theme : "advanced",
    theme_advanced_resizing_max_width : 530,
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,spellchecker,filemanager",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,|,styleselect,formatselect,|,forecolor,backcolor,<?if ($staff[perm][msg_replies]==1) {?>|,insertfile,link,<?}?>|,spellchecker",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    //External
    extended_valid_elements : "iframe[src|width|height|name|align]",

    // Example content CSS (should be your site CSS)
    content_css : "../style-bijou.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "cms-image_list.php",
    media_external_list_url : "lists/media_list.js",

    // Style formats
    style_formats : [
        {title : 'Bijou Weddings styles'},
        {title : 'Bijou copy', block : 'p', classes : 'copy'},
        {title : 'Bijou copy bold', inline : 'span', classes : 'title'},
        {title : 'Corporate Event styles'},
        {title : 'Event bullets small', block : 'p', classes : 'corpbodybull'},
        {title : 'Event bullets big', block : 'p', classes : 'corpbull'},
        {title : 'Table styles'},
        {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
    ],

    // Replace values for the template plugin
    template_replace_values : {
        username : "Some User",
        staffid : "991234"
    }

});
</code>```

Do you have any idea please?
thanks

答:
Try to send the response with

$data = {"method":"fm.insertFiles","params":[{"path0":"{0}/Sage.JPG"}],"id":"c0"};
json_encode($data);

intead of json_data

Body:
recently we updated a server from php 5.3 to php 7, actually I don't know if the update causes this issue, but when I go to insert a file on TinyMCE javascirpt I receive this error message:

The server response wasn't JSON format

I haven't found anything on internet about it.

here is Json_data:

{"method":"fm.insertFiles","params":[{"path0":"{0}/Sage.JPG"}],"id":"c0"}

here is TinyMCE configuration:

    tinyMCE.init({
    // General options
        mode : "exact",
        elements : "msg_body",
    theme : "advanced",
    theme_advanced_resizing_max_width : 530,
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave,spellchecker,filemanager",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,|,styleselect,formatselect,|,forecolor,backcolor,<?if ($staff[perm][msg_replies]==1) {?>|,insertfile,link,<?}?>|,spellchecker",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    //External
    extended_valid_elements : "iframe[src|width|height|name|align]",

    // Example content CSS (should be your site CSS)
    content_css : "../style-bijou.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "cms-image_list.php",
    media_external_list_url : "lists/media_list.js",

    // Style formats
    style_formats : [
        {title : 'Bijou Weddings styles'},
        {title : 'Bijou copy', block : 'p', classes : 'copy'},
        {title : 'Bijou copy bold', inline : 'span', classes : 'title'},
        {title : 'Corporate Event styles'},
        {title : 'Event bullets small', block : 'p', classes : 'corpbodybull'},
        {title : 'Event bullets big', block : 'p', classes : 'corpbull'},
        {title : 'Table styles'},
        {title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
    ],

    // Replace values for the template plugin
    template_replace_values : {
        username : "Some User",
        staffid : "991234"
    }

});

Do you have any idea please?
thanks


问:
Calculating the length of a segment in a logarithmic scale
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});```
</div>
</div>
</p>

<p>This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present. </p>

<p>I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)</p>

<p>How should I modify lineLen to use a logarithmic scale?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});</code>```

答:
You can take log(x+1) instead of log(x), that doesn't change the value too much and the ratios are maintained for smaller numbers.

var maxLineLength = 20;
var lineLen = (x, max) => maxLineLength * Math.log(x+1)/Math.log(max+1);
var events = [ 0.1, 1, 5, 20, 50];
var visualizer = function(events){
    var max = Math.max.apply(null, events);
    return events.reduce((y, x) => {
         y.push(lineLen(x, max));
         return y;
    }, []);
};

console.log(visualizer(events));```

Body:
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});

This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present.

I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)

How should I modify lineLen to use a logarithmic scale?

var maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});


问:
javascript - missing array
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}
</code>```

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));
</code>```

My output is:

```<code>charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
</code>```

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

答:
Your else clause means you only push to that array if includes() returns true.

Therefore, you never actually push anything.

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012


问:
How to databind a gridview from an other aspx file that is opened as a pop up window in asp.net?
My problem is the following. I have an aspx webform(ErrorList.aspx). This webform has a gridview control and a sqldatasource control. The sqldatasource control has the select statement from the table and the gridview displays the result. The last column contains an imagebutton. Imagebutton's code has this :
OnClientClick="addFileWindow(this);"
You can see there is an onclientclick part and a javascript function is called here. Function's code is here :

```<code>function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");

            return false;
        }
</code>```

So if you click on the imagebutton a pop up window will be opened.
It contains a fileupload manager control and an upload button and an error label. Error label will be displayed if there is no selected file. Error label will be on hide status if there is a selected file. If everything is alright and there is a selected file the program will update the database cell with the name of the file and the file will be uploaded to the server into the uploaded files folder in the project. Its working. So this is not problem for me. Here is the code of the addNewFile.aspx:
Client side :

```<code><title>File upload</title>

<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        if (window.opener != null && !window.opener.closed) {

            var parent = $(window.opener.document).contents();
            $("#myDiv1").html("<u>Here is the ID of the record of the new file: </u>");
            $("#myDiv2").html(parent.find("#Azon_row_lbl").html());

        }
    });
</script>
</code>```

```<code><form id="form1" runat="server">

    <div id="myDiv1" runat="server" style="color: white;"></div>
    <div id="myDiv2" runat="server" style="color: white;"></div>

    <asp:Label ID="lbl_id" runat="server"></asp:Label>
    <br /><br />

    <asp:FileUpload ID="fu_ter_ell_update_attch" runat="server"></asp:FileUpload>

    <br /><br />

    <asp:Button ID="Upload_file_bttn" runat="server" Text="Upload" OnClick="Upload_file_bttn_Click" Height="33px" style="font-weight: 700; color: #FFFFFF; background-color: #000000;" Width="77px" />

    <br /><br />

    <asp:Label ID="Error_label" runat="server" Visible="false" Text="There is no selected file!" style="font-weight: 700; color: #FF0000"></asp:Label>

</form>

 <script type="text/javascript">

     $("#<%= Upload_file_bttn.ClientID %>").click(function () {

         var ID = $('#myDiv2').text();
         var filename = $('#<%= fu_ter_ell_update_attch.ClientID %>').val();

         if (filename != "")
         {
             var res = filename.split("\\");
             //   res[res.length-1]   this reference contains the name of the file . extension for example apple.jpg
             var file_exist = "";

             $.ajax({
                 type: 'POST',
                 contentType: "application/json; charset=utf-8",
                 url: 'addNewFile.aspx/DataBase_Has_This_FileName_Or_Not',
                 data: "{'FileName':'" + res[res.length - 1] + "'}",
                 async: false,
                 success: function (response) {
                     file_exist = response.d;
                 },
                 error: function () {
                     alert("Error");
                     return false;
                 }
             });

             if (file_exist == true)
             {
                 alert("Database has this filename already. Change it and try to upload again.");
                 return false;
             }
             else
             {
                 $.ajax({
                     type: 'POST',
                     contentType: "application/json; charset=utf-8",
                     url: 'addNewFile.aspx/Attach_FileName_Into_Row',
                     data: "{'ID':'" + ID + "','FileName':'" + res[res.length - 1] + "'}",
                     async: false,
                     success: function (response) {

                     },
                     error: function () {
                         alert("Error");
                         return false;
                     }
                 });
             }

         }

     });

</script>
</code>```

Server side :

```<code>protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static bool DataBase_Has_This_FileName_Or_Not(string FileName)
{
    bool retvalue = false;

    string selectStatement = "SELECT * FROM [DNTShiftReport].[dbo].[ter_ell_hiany_DNT] WHERE [Filename] = @Filename";

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comm = new SqlCommand(selectStatement, conn))
        {
            try
            {
                comm.Parameters.Add("@Filename", SqlDbType.NVarChar).Value = FileName;

                conn.Open();

                using (SqlDataReader dr = comm.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        retvalue = true;
                    }
                }
            }
            catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
            if (conn.State == System.Data.ConnectionState.Open) conn.Close();
        }
    }

    return retvalue;
}

[WebMethod]
public static void Attach_FileName_Into_Row(string ID, string FileName)
{
    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(connectionString))
    {

        con.Open();

        using (SqlCommand comm = con.CreateCommand())
        {
            comm.CommandText = "UPDATE [ter_ell_hiany_DNT] SET [Filename] = @filename WHERE [ID] = @upd_id";
            comm.Parameters.Add("@filename", SqlDbType.NVarChar).Value = FileName;
            comm.Parameters.Add("@upd_id", SqlDbType.Int).Value = Convert.ToInt32(ID);
            comm.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void Upload_file_bttn_Click(object sender, EventArgs e)
{
    if (fu_ter_ell_update_attch.HasFile)
    {

        Error_label.Visible = false;

        string filename = Path.GetFileName(fu_ter_ell_update_attch.FileName);
        string saveDir = @"\DNTShiftReport\Uploaded_files\";
        string appPath = Server.MapPath(saveDir);
        string fullpath = appPath + filename;
        fu_ter_ell_update_attch.SaveAs(fullpath);

        Session["POP_UP_CLOSED"] = "CLOSED";
        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true); // close the pop up window.

    }
    else
    {
        Error_label.Visible = true;
    }
}
</code>```

So my problem is that, database is updated, file is uploaded, but the gridview should be databinded automatically when the pop up window is closed by the button. I cant databind the gridview on the addNewFile.aspx because the gridview's location is the ErrorList.aspx. I tried every solution that I find in the google in the last 3 days but nothing is working.

答:
You can use the following approach to automatically bind the gridview to data when the popup closes. (NOTE: I suggest not to reload page using JavaScript on closing of popup, since then you may receive a browser message asking if you want to post data and this might not be the desired behavior your users would like to see. So, I think the hidden button approach would be the best approach.)

Add a hidden button to the parent page as in markup below.

We will programatically click this button when the popup is closed
using JavaScript and this clicking will automatically post the page
and fire the button click event on server-side.

In this server-side click event, we can databind the gridview.

Please change your onclientclick to this: OnClientClick="return addFileWindow(this);", else the button will post back causing undesirable behavior.

Hidden button on parent page

```<code><div style="display: none">
    <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
</div>
</code>```

JavaScript on parent page for subscribing to close event of popup

```<code><script type="text/javascript">
var wnd = null;

function onPopupClosing() {
            var hiddenButton = wnd.opener.document.getElementById("<%=btnPost.ClientID%>");
            if (hiddenButton) {
                hiddenButton.click();
            }
        }
function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            //get center coordinates for popup
            var x = screen.width / 2 - 600 / 2;
            var y = screen.height / 2 - 300 / 2;
            //open popup
            wnd = window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300, left="+ x + ", top="+ y);
            wnd.onbeforeunload = onPopupClosing;
            wnd.focus();
            return false;
        }
</script>
</code>```

Code-behind for databinding gridview  when popup closes

```<code>protected void btnPost_Click(object sender, EventArgs e)
{
    //bind the grid view
    GridView1.DataBind();
}
</code>```

NOTE: If you are using UpdatePanel i.e. your gridview is within an UpdatePanel. If yes, then you need to make sure that the settings on UpdatePanel are as given in below markup and also the hidden button is within the UpdatePanel. The property settings ChildrenAsTriggers="true"  and UpdateMode="Always" are important else this may not work.

When UpdatePanel is used

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
    <ContentTemplate>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" AllowPaging="True">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
                <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
                <asp:TemplateField HeaderText="CheckBox Column">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CheckBox Column">
                    <ItemTemplate>
                        <asp:ImageButton ID="ibtnPopup" runat="server" OnClientClick="return addFileWindow(this)" ImageUrl="~/images/logo.png" />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
           </asp:GridView>
        <div style="display: none;">
            <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
        </div>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

Body:
My problem is the following. I have an aspx webform(ErrorList.aspx). This webform has a gridview control and a sqldatasource control. The sqldatasource control has the select statement from the table and the gridview displays the result. The last column contains an imagebutton. Imagebutton's code has this :
OnClientClick="addFileWindow(this);"
You can see there is an onclientclick part and a javascript function is called here. Function's code is here :

function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");

            return false;
        }

So if you click on the imagebutton a pop up window will be opened.
It contains a fileupload manager control and an upload button and an error label. Error label will be displayed if there is no selected file. Error label will be on hide status if there is a selected file. If everything is alright and there is a selected file the program will update the database cell with the name of the file and the file will be uploaded to the server into the uploaded files folder in the project. Its working. So this is not problem for me. Here is the code of the addNewFile.aspx:
Client side :

<title>File upload</title>

<form id="form1" runat="server">

    <asp:Label ID="lbl_id" runat="server"></asp:Label>

    <asp:FileUpload ID="fu_ter_ell_update_attch" runat="server"></asp:FileUpload>

    <asp:Button ID="Upload_file_bttn" runat="server" Text="Upload" OnClick="Upload_file_bttn_Click" Height="33px" style="font-weight: 700; color: #FFFFFF; background-color: #000000;" Width="77px" />

    <asp:Label ID="Error_label" runat="server" Visible="false" Text="There is no selected file!" style="font-weight: 700; color: #FF0000"></asp:Label>

</form>

Server side :

protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static bool DataBase_Has_This_FileName_Or_Not(string FileName)
{
    bool retvalue = false;

    string selectStatement = "SELECT * FROM [DNTShiftReport].[dbo].[ter_ell_hiany_DNT] WHERE [Filename] = @Filename";

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comm = new SqlCommand(selectStatement, conn))
        {
            try
            {
                comm.Parameters.Add("@Filename", SqlDbType.NVarChar).Value = FileName;

                conn.Open();

                using (SqlDataReader dr = comm.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        retvalue = true;
                    }
                }
            }
            catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
            if (conn.State == System.Data.ConnectionState.Open) conn.Close();
        }
    }

    return retvalue;
}

[WebMethod]
public static void Attach_FileName_Into_Row(string ID, string FileName)
{
    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(connectionString))
    {

        con.Open();

        using (SqlCommand comm = con.CreateCommand())
        {
            comm.CommandText = "UPDATE [ter_ell_hiany_DNT] SET [Filename] = @filename WHERE [ID] = @upd_id";
            comm.Parameters.Add("@filename", SqlDbType.NVarChar).Value = FileName;
            comm.Parameters.Add("@upd_id", SqlDbType.Int).Value = Convert.ToInt32(ID);
            comm.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void Upload_file_bttn_Click(object sender, EventArgs e)
{
    if (fu_ter_ell_update_attch.HasFile)
    {

        Error_label.Visible = false;

        string filename = Path.GetFileName(fu_ter_ell_update_attch.FileName);
        string saveDir = @"\DNTShiftReport\Uploaded_files\";
        string appPath = Server.MapPath(saveDir);
        string fullpath = appPath + filename;
        fu_ter_ell_update_attch.SaveAs(fullpath);

        Session["POP_UP_CLOSED"] = "CLOSED";
        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true); // close the pop up window.

    }
    else
    {
        Error_label.Visible = true;
    }
}

So my problem is that, database is updated, file is uploaded, but the gridview should be databinded automatically when the pop up window is closed by the button. I cant databind the gridview on the addNewFile.aspx because the gridview's location is the ErrorList.aspx. I tried every solution that I find in the google in the last 3 days but nothing is working.

Body:
You can use the following approach to automatically bind the gridview to data when the popup closes. (NOTE: I suggest not to reload page using JavaScript on closing of popup, since then you may receive a browser message asking if you want to post data and this might not be the desired behavior your users would like to see. So, I think the hidden button approach would be the best approach.)

Add a hidden button to the parent page as in markup below.

We will programatically click this button when the popup is closed
using JavaScript and this clicking will automatically post the page
and fire the button click event on server-side.

In this server-side click event, we can databind the gridview.

Please change your onclientclick to this: OnClientClick="return addFileWindow(this);", else the button will post back causing undesirable behavior.

Hidden button on parent page

<div style="display: none">
    <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
</div>

JavaScript on parent page for subscribing to close event of popup

<script type="text/javascript">
var wnd = null;

function onPopupClosing() {
            var hiddenButton = wnd.opener.document.getElementById("<%=btnPost.ClientID%>");
            if (hiddenButton) {
                hiddenButton.click();
            }
        }
function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            //get center coordinates for popup
            var x = screen.width / 2 - 600 / 2;
            var y = screen.height / 2 - 300 / 2;
            //open popup
            wnd = window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300, left="+ x + ", top="+ y);
            wnd.onbeforeunload = onPopupClosing;
            wnd.focus();
            return false;
        }
</script>

Code-behind for databinding gridview  when popup closes

protected void btnPost_Click(object sender, EventArgs e)
{
    //bind the grid view
    GridView1.DataBind();
}

NOTE: If you are using UpdatePanel i.e. your gridview is within an UpdatePanel. If yes, then you need to make sure that the settings on UpdatePanel are as given in below markup and also the hidden button is within the UpdatePanel. The property settings ChildrenAsTriggers="true"  and UpdateMode="Always" are important else this may not work.

When UpdatePanel is used

<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
    <ContentTemplate>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" AllowPaging="True">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
                <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
                <asp:TemplateField HeaderText="CheckBox Column">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("Discontinued") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CheckBox Column">
                    <ItemTemplate>
                        <asp:ImageButton ID="ibtnPopup" runat="server" OnClientClick="return addFileWindow(this)" ImageUrl="~/images/logo.png" />
                    </ItemTemplate>
                </asp:TemplateField>

            </Columns>
           </asp:GridView>
        <div style="display: none;">
            <asp:Button ID="btnPost" runat="server" Text="Post" OnClick="btnPost_Click" />
        </div>
    </ContentTemplate>
</asp:UpdatePanel>


问:
one key with multiple values Python
```<code>bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')
</code>```

What should I do to make this input as below?

```<code>dic1 = {1: {'Q', 'Z', 'X', 'K', 'J'}, 2: {'F', '_', 'P', 'C', 'M', 'W', 'Y', 'B',   'V', 'H'}, 3: {'G'}, 4: {'U', 'D', 'L', 'S'}, 6: {'N', 'R', 'T'}, 8: {'O'}, 9: {'I', 'A'}, 12: {'E'}}
</code>```

(occurrences as a key and correspond letters as a value)

What i have done so far is this

```<code>freq = {i:bag.count(i) for i in set(bag)}
 {'U': 4, '_': 2, 'C': 2, 'K': 1, 'D': 4, 'T': 6, 'Q': 1, 'V': 2, 'A': 9, 'F': 2, 'O': 8, 'J': 1, 'I': 9, 'N': 6, 'P': 2, 'S': 4, 'M': 2, 'W': 2, 'E': 12, 'Z': 1, 'G': 3, 'Y': 2, 'B': 2, 'L': 4, 'R': 6, 'X': 1, 'H': 2}
</code>```

I'm not sure about the next step

Thanks

答:
collections.Counter will give you a mapping from a item to a count.  Your requested data structure is a reverse of that mapping.  Here I use a collections.defaultdict to accomplish that reversal, grouping items with identical counts into sets:

```<code>from collections import defaultdict, Counter

s = 'IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__'

d = defaultdict(set)
for k, n in Counter(s).items():
    d[n].add(k)
</code>```

Title: one key with multiple values Python

Body:
bag =('IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__')

What should I do to make this input as below?

dic1 = {1: {'Q', 'Z', 'X', 'K', 'J'}, 2: {'F', '_', 'P', 'C', 'M', 'W', 'Y', 'B',   'V', 'H'}, 3: {'G'}, 4: {'U', 'D', 'L', 'S'}, 6: {'N', 'R', 'T'}, 8: {'O'}, 9: {'I', 'A'}, 12: {'E'}}

(occurrences as a key and correspond letters as a value)

What i have done so far is this

freq = {i:bag.count(i) for i in set(bag)}
 {'U': 4, '_': 2, 'C': 2, 'K': 1, 'D': 4, 'T': 6, 'Q': 1, 'V': 2, 'A': 9, 'F': 2, 'O': 8, 'J': 1, 'I': 9, 'N': 6, 'P': 2, 'S': 4, 'M': 2, 'W': 2, 'E': 12, 'Z': 1, 'G': 3, 'Y': 2, 'B': 2, 'L': 4, 'R': 6, 'X': 1, 'H': 2}

I'm not sure about the next step

Thanks

Body:
collections.Counter will give you a mapping from a item to a count.  Your requested data structure is a reverse of that mapping.  Here I use a collections.defaultdict to accomplish that reversal, grouping items with identical counts into sets:

from collections import defaultdict, Counter

s = 'IAMDIETINGIEATQUINCEJELLYLOTSOFGROUNDMAIZEGIVESVARIETYICOOKRHUBARBANDSODAWEEPANEWORPUTONEXTRAFLESH__'

d = defaultdict(set)
for k, n in Counter(s).items():
    d[n].add(k)


问:
INSTALL_FAILED_NO_MATCHING_ABIS while installing app on real device
I was trying to install my app on a real android device (Xiaomi note 4 and Nexus 7), but it shows the error as -

```<code>Failure [INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]
</code>```

Now this problem is discussed in many questions Like this one
but all of them are talking about facing this problem on Emulators, so one can make emulator of appropriate CPU image (ARM or x86)

How can one fix that for a real device?

答:
You need make sure if jniLibs folder are put correctly. Also make sure you have armeabi-v7a folder that contains .so files. armeabi-v7a has larger cpu set.

|--app:

|--|--src:

|--|--|--main

|--|--|--|--libs (careful here, its the folder that we include later)

|--|--|--|--|--armeabi-v7a

|--|--|--|--|--|--.so Files

|--|--|--|--|--x86

|--|--|--|--|--|--.so Files

Secondly, add this line if does not exist in your app build.gradle

```<code>compile fileTree(dir: 'libs', include: ['.jar','.so'])
</code>```

Do your homework and research the cpu architecture of your real device. So you can get whats missing.

Body:
I was trying to install my app on a real android device (Xiaomi note 4 and Nexus 7), but it shows the error as -

Failure [INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Now this problem is discussed in many questions Like this one
but all of them are talking about facing this problem on Emulators, so one can make emulator of appropriate CPU image (ARM or x86)

How can one fix that for a real device?

Body:
You need make sure if jniLibs folder are put correctly. Also make sure you have armeabi-v7a folder that contains .so files. armeabi-v7a has larger cpu set.

|--app:

|--|--src:

|--|--|--main

|--|--|--|--libs (careful here, its the folder that we include later)

|--|--|--|--|--armeabi-v7a

|--|--|--|--|--|--.so Files

|--|--|--|--|--x86

|--|--|--|--|--|--.so Files

Secondly, add this line if does not exist in your app build.gradle

compile fileTree(dir: 'libs', include: ['.jar','.so'])

Do your homework and research the cpu architecture of your real device. So you can get whats missing.


问:
c# phone format extension method
I'm writing an extension method that takes a string of digits (ie. 4083239382) and converts it to a phone number according to the country code:

```<code>public static string ToPhoneFormat(this string ThePhone, int CountryCode)
{
 string ThisFormat = null;
 if (CountryCode == 1) { ThisFormat = string.Format("{0:###-###-####}",ThePhone); }
 return ThisFormat;
}
</code>```

For some reason, I'm not getting the result I'm looking for. Any suggestions?

Thanks.

答:
It might have something to do with you passing in the phone number as a string. Parse it to a long first.</p>

```<code>string ThisFormat = null;
if (CountryCode == 1) { ThisFormat = string.Format("{0:###-###-####}", long.Parse(ThePhone)); }
return ThisFormat;
</code>```

Title: c# phone format extension method

Body:
I'm writing an extension method that takes a string of digits (ie. 4083239382) and converts it to a phone number according to the country code:

public static string ToPhoneFormat(this string ThePhone, int CountryCode)
{
 string ThisFormat = null;
 if (CountryCode == 1) { ThisFormat = string.Format("{0:###-###-####}",ThePhone); }
 return ThisFormat;
}

For some reason, I'm not getting the result I'm looking for. Any suggestions?

Thanks.

Body:
It might have something to do with you passing in the phone number as a string. Parse it to a long first.

string ThisFormat = null;
if (CountryCode == 1) { ThisFormat = string.Format("{0:###-###-####}", long.Parse(ThePhone)); }
return ThisFormat;


问:
EnumTranslator bean is not injected (is null)
RepositoryRestMvcConfiguration class of Spring Data REST has method enumTranslator():

@Bean
public EnumTranslator enumTranslator() {
  return new EnumTranslator(resourceDescriptionMessageSourceAccessor());
}
```

<p>that (I expect) registers an '<strong>enumTranslator</strong>' Bean.</p>

<p>But when I try to use it in my component then it isn't injected and always is <code>null</code>:</p>

<pre class="lang-java prettyprint-override"><code>@Component
public class MyComponent {

    private final EnumTranslator enumTranslator;

    public MyComponent(EnumTranslator enumTranslator) {
        this.enumTranslator = enumTranslator;
    }

    public void someMethod() {
        // enumTranslator -> null
    }
}
</code>```

Could somebody explain why does this happens and how to correct inject such beans?

UPDATE

I've figured out - I tried to implement a class (Spring converter) that isn't managed by Spring ))

Thanks everybody who tried to help me!

答:
It looks like the RepositoryRestMvcConfiguration  bean was not loaded in the Spring container.

Try for example to import it with @Import(RepositoryRestMvcConfiguration.class) from a Configuration class.

According to the documentation :

2.4 Configuring Spring Data REST

...

You can either import this class into your existing configuration
using an @Import annotation or you can subclass it and override any of
the configureXXX methods to add your own configuration to that of
Spring Data REST.

Body:
RepositoryRestMvcConfiguration class of Spring Data REST has method enumTranslator():

@Bean
public EnumTranslator enumTranslator() {
  return new EnumTranslator(resourceDescriptionMessageSourceAccessor());
}

that (I expect) registers an 'enumTranslator' Bean.

But when I try to use it in my component then it isn't injected and always is null:

@Component
public class MyComponent {

    private final EnumTranslator enumTranslator;

    public MyComponent(EnumTranslator enumTranslator) {
        this.enumTranslator = enumTranslator;
    }

    public void someMethod() {
        // enumTranslator -> null
    }
}

Could somebody explain why does this happens and how to correct inject such beans?

UPDATE

I've figured out - I tried to implement a class (Spring converter) that isn't managed by Spring ))

Thanks everybody who tried to help me!


问:
How to append textbox value to the nearest span?
I'm using jQuery datatables and want to apply calculation on it, it is hard to do so i want to append value of textbox to invisible span. How can i do this? with this following code it is only working on 1 textbox of same id i want to apply on all textbox of same id.

$('td').each(function() {
  $("input").keyup(function() {
    var txtvalue = $('#curr_sales').val();
    $("#curr").closest('span').text(txtvalue);
    console.log(txtvalue);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
</tr></table></code>```

答:
Ids have to be unique, they cannot recycle an already existing Id. Use classes instead

Also, to output the result to the closest  go up to the parent and find the  child from the
.

Also, you can bind more than one event to the <input> if needed by using the on() function.

Output

Code Snippet

$('td').each(function() {
  $("input").on("keyup blur", function() {
    var txtvalue = $(this).val();
    $(this).parent().find('span').text(txtvalue);
    console.log(txtvalue);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
  </tr>
</table></code>```

Body:
I'm using jQuery datatables and want to apply calculation on it, it is hard to do so i want to append value of textbox to invisible span. How can i do this? with this following code it is only working on 1 textbox of same id i want to apply on all textbox of same id.

$('td').each(function() {
  $("input").keyup(function() {
    var txtvalue = $('#curr_sales').val();
    $("#curr").closest('span').text(txtvalue);
    console.log(txtvalue);
  });
});

<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>
<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>
<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>

Body:
Ids have to be unique, they cannot recycle an already existing Id. Use classes instead

Also, to output the result to the closest <span> go up to the parent and find the <span> child from the <tr>.

Also, you can bind more than one event to the <input> if needed by using the on() function.

Output

Code Snippet

$('td').each(function() {
  $("input").on("keyup blur", function() {
    var txtvalue = $(this).val();
    $(this).parent().find('span').text(txtvalue);
    console.log(txtvalue);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
    <td><input type="number" class="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span class="curr"></span></td>
  </tr>
</table>


问:
How can i make my each database field into a public variable in php?
I got my all database field by doing this query

```<code>"SHOW  COLUMNS FROM admin"
</code>```

but i am wondering how could i make each of them into a public variable!
and yes these variables will be in a class as i am doing OO PHP.

First, i need to take all field name from my database. Then I need to put them into a variable of a class.

答:
You don't need to predefine the column names like this in order to access your database rows as objects.

Assuming you have established a PDO connection $pdo, you can execute a select query against a table and return your results as objects with public property names that correspond to the column names in your table.

```<code>$stmt = $pdo->query('SELECT * FROM admin');
while ($row = $stmt->fetchObject()) {
    // each $row is an object with public properties matching the column names
    // so you can do things with $row->column_a, etc.
    // (obviously I don't know your actual column names)
}
</code>```

It is very similar with mysqli:

```<code>$result = $mysqli->query('SELECT * FROM admin');
while ($row = $result->fetch_object()) { // ... }
</code>```

Body:
I got my all database field by doing this query

"SHOW  COLUMNS FROM admin"

but i am wondering how could i make each of them into a public variable!
and yes these variables will be in a class as i am doing OO PHP.

First, i need to take all field name from my database. Then I need to put them into a variable of a class.

Body:
You don't need to predefine the column names like this in order to access your database rows as objects.

Assuming you have established a PDO connection $pdo, you can execute a select query against a table and return your results as objects with public property names that correspond to the column names in your table.

$stmt = $pdo->query('SELECT * FROM admin');
while ($row = $stmt->fetchObject()) {
    // each $row is an object with public properties matching the column names
    // so you can do things with $row->column_a, etc.
    // (obviously I don't know your actual column names)
}

It is very similar with mysqli:

$result = $mysqli->query('SELECT * FROM admin');
while ($row = $result->fetch_object()) { // ... }


问:
No suitable driver found -SQLException JDBC
I just started to learn JDBC. I'm trying to connect to my MySQL database.
This is my code:

```<code>    import java.io.*;
        import javax.swing.*;
        import java.awt.*;
        import java.awt.event.*;
        import java.sql.*;
        public class Test2{
                public static void main(String[] args){
                        try{
                                Class.forName("com.mysql.jdbc.Driver");
                                Connection con = DriverManager.getConnection("jbdc:mysql://localhost:3306/data","root","
****");
                                Statement stmt = con.createStatement();
                                ResultSet rs = stmt.executeQuery("SELECT * FROM details");
                                while(rs.next()){
                                        System.out.println(rs.getString(1)+" "+rs.getString(2));
                                }
                                con.close();
                        }
                        catch (Exception e){
                                System.out.println(e);
                        }

    }
    }
</code>```

I've checked other stackoverflow answers but they don't seem to resolve the problem. I've added the jar file correctly.I've also registered the drive.These were the answers I got when I searched the web.

答:
Looks like you have misprint in database URL. Should be

```<code>jdbc
</code>```

instead of

```<code>jbdc
</code>```

Body:
I just started to learn JDBC. I'm trying to connect to my MySQL database.
This is my code:

    import java.io.*;
        import javax.swing.*;
        import java.awt.*;
        import java.awt.event.*;
        import java.sql.*;
        public class Test2{
                public static void main(String[] args){
                        try{
                                Class.forName("com.mysql.jdbc.Driver");
                                Connection con = DriverManager.getConnection("jbdc:mysql://localhost:3306/data","root","
****");
                                Statement stmt = con.createStatement();
                                ResultSet rs = stmt.executeQuery("SELECT * FROM details");
                                while(rs.next()){
                                        System.out.println(rs.getString(1)+" "+rs.getString(2));
                                }
                                con.close();
                        }
                        catch (Exception e){
                                System.out.println(e);
                        }

    }
    }

I've checked other stackoverflow answers but they don't seem to resolve the problem. I've added the jar file correctly.I've also registered the drive.These were the answers I got when I searched the web.

Body:
Looks like you have misprint in database URL. Should be

jdbc

instead of

jbdc


问:
How to fix unhandled exception access violation
I have written a logic to find out common elements from two arrays. But the program breaks at the if condition giving an exception saying Access violation reading location 0x00000002.

```<code>#include<stdio.h>
void intersect(int[2][2],int[2][2],int,int);
int main()
{
    int arr1[2][2]={{2,5},{6,8}};
    int arr2[2][2]={{1,2},{8,8}};
row = (sizeof(arr1)/sizeof(arr1[0]));
     col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
intersect(arr1,arr2,row,col);
}

void intersect(int **ptr1, int **ptr2,int row, int col)
{
    int i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
                for(x = 0; x < row ; x++)
                {
                    for(y = 0; y < col ; y++)
                    {
                        if(ptr1[i][j] == ptr2[x][y])
                            printf("%d\t",ptr1[i][j]);

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

This is what it says in detail: First-chance exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002. Unhandled exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002.

答:
Instead of using ptrN as double pointers, you can tell the array size like:

```<code>void intersect(size_t row, size_t col, int a1[][col], int a2[][col])
{
    size_t i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
            for(x = 0; x < row ; x++)
            {
                for(y = 0; y < col ; y++)
                {
                    if(a1[i][j] == a2[x][y])
                        printf("%d\t",a1[i][j]);
                }
            }
        }
    }
}
</code>```

Body:
I have written a logic to find out common elements from two arrays. But the program breaks at the if condition giving an exception saying Access violation reading location 0x00000002.

#include<stdio.h>
void intersect(int[2][2],int[2][2],int,int);
int main()
{
    int arr1[2][2]={{2,5},{6,8}};
    int arr2[2][2]={{1,2},{8,8}};
row = (sizeof(arr1)/sizeof(arr1[0]));
     col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
intersect(arr1,arr2,row,col);
}

void intersect(int **ptr1, int **ptr2,int row, int col)
{
    int i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
                for(x = 0; x < row ; x++)
                {
                    for(y = 0; y < col ; y++)
                    {
                        if(ptr1[i][j] == ptr2[x][y])
                            printf("%d\t",ptr1[i][j]);

                    }
                }
        }
    }
}

This is what it says in detail: First-chance exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002. Unhandled exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002.

Body:
Instead of using ptrN as double pointers, you can tell the array size like:

void intersect(size_t row, size_t col, int a1[][col], int a2[][col])
{
    size_t i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
            for(x = 0; x < row ; x++)
            {
                for(y = 0; y < col ; y++)
                {
                    if(a1[i][j] == a2[x][y])
                        printf("%d\t",a1[i][j]);
                }
            }
        }
    }
}


问:
Storing files as list and reading data from them in python
I was wondering if I had a directory full of similar .txt files, if there was a way to store these as a list of lists in python, iterate through the list to open the files, and then iterate through the objects in the file to achieve something. For example:

```<code>ls /Path/to/directory/
1.txt 2.txt 3.txt 4.txt
</code>```

the contents of each file would be like:

```<code>more 1.txt
1
2
3
4
</code>```

For the python script something like:

```<code>import os
pathname = os.path.join("directory",filenames)
for i in pathname:
    file_open = open(pathname[i])
    for j in file_open:
        file_sum = sum(int[j])
    return file_sum
</code>```

or would it just be better to do this with a shell script to run the python command for each file individually and write output to file? I just wanted to see if there was a cool pythonic way to do this.

```<code>#!/bin/bash

RUN_PATH=$1; shift
cd $RUN_PATH

for file in $RUN_PATH*
do
    MONEY=`basename $file`
    BAG=`python my_script.py $file`
    echo $MONEY "      " $BAG >> money_bag.txt
done;
</code>```

thanks for the help

答:
Yes. We can use a combination of glob (to get all of the text files), a short function and a dictionary comprehension:

```<code>import glob

def sum_file(file_path):
    total = 0
    with open(file_path, 'r') as f:
        for line in f:
            try:
                total += int(line)
            except ValueError:
                continue
    return total

folder_location = r'path\to\directory\*.txt'

file_sums = {p: sum_file(p)
             for p in glob.glob(folder_location)}
</code>```

file_sums will be a dictionary where the keys are the paths to each file, and the values the total of all lines that can be interpreted as integers in those files.

Body:
I was wondering if I had a directory full of similar .txt files, if there was a way to store these as a list of lists in python, iterate through the list to open the files, and then iterate through the objects in the file to achieve something. For example:

ls /Path/to/directory/
1.txt 2.txt 3.txt 4.txt

the contents of each file would be like:

more 1.txt
1
2
3
4

For the python script something like:

import os
pathname = os.path.join("directory",filenames)
for i in pathname:
    file_open = open(pathname[i])
    for j in file_open:
        file_sum = sum(int[j])
    return file_sum

or would it just be better to do this with a shell script to run the python command for each file individually and write output to file? I just wanted to see if there was a cool pythonic way to do this.

#!/bin/bash

RUN_PATH=$1; shift
cd $RUN_PATH

for file in $RUN_PATH*
do
    MONEY=`basename $file`
    BAG=`python my_script.py $file`
    echo $MONEY "      " $BAG >> money_bag.txt
done;

thanks for the help

Body:
Yes. We can use a combination of glob (to get all of the text files), a short function and a dictionary comprehension:

import glob

def sum_file(file_path):
    total = 0
    with open(file_path, 'r') as f:
        for line in f:
            try:
                total += int(line)
            except ValueError:
                continue
    return total

folder_location = r'path\to\directory\*.txt'

file_sums = {p: sum_file(p)
             for p in glob.glob(folder_location)}

file_sums will be a dictionary where the keys are the paths to each file, and the values the total of all lines that can be interpreted as integers in those files.


问:
running headless chrome in an microsoft azure web app
I am currently using phantomjs to generate screenshots of web pages.
Due to various issues including web fonts, and video tag support, I would like to try switching to headless chrome.

Has anyone had success running headless chrome in an azure web app?
I cannot find a .net api, and assume I need to run node.js with puppeteer If I want a javascript api similar to phantomjs.

答:
Right now most of the big libraries are made for NodeJS. It's possible to run Chrome headless without it, but you'll need a library for your .NET API to effectively communicate with Chrome. If none exist, then the protocol itself is documented here, and you could build one for .NET.

If you're struggling to get Chrome running on Azure I have a service that offers Docker images, which could be as simple as a few commands to have up and running (located here). Other than that there's a few open-source options out there, but they have differing issues and uses-cases.


问:
public static void main(String[] args) throws Exception
What is the meaning of this?

```<code>public static void main(String[] args) throws Exception?
</code>```

I don't know it. If someone know please help me.
I really want to know about  "throws Exception".

答:
Public: it is an access specifier which can be access throughout the program.
Static: it is a keyword which can be used for single copy of that variable.
Void: it is an empty return type.</p>

Body:
What is the meaning of this?

public static void main(String[] args) throws Exception?

I don't know it. If someone know please help me.
I really want to know about  "throws Exception".


答:
Your else clause isn't reachable at all since you didn't pushed the element in the right place, you could add a console.log() inside the loop to see that the array still empty through all the iterations.

Instead, the element should be pushed in the if condition like :

```<code>for (var i = 0; i < charsArr.length; i++) {
    if (!alreadyInArr.includes(charsArr[i])) {
        charsObj[charsArr[i]] = 0;
        alreadyInArr.push(charsArr[i]);
    }
}
</code>```

Hope this helps.

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!alreadyInArr.includes(charsArr[i])) {
      charsObj[charsArr[i]] = 0;
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));```

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

Body:
Your else clause isn't reachable at all since you didn't pushed the element in the right place, you could add a console.log() inside the loop to see that the array still empty through all the iterations.

Instead, the element should be pushed in the if condition like :

for (var i = 0; i < charsArr.length; i++) {
    if (!alreadyInArr.includes(charsArr[i])) {
        charsObj[charsArr[i]] = 0;
        alreadyInArr.push(charsArr[i]);
    }
}

Hope this helps.

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!alreadyInArr.includes(charsArr[i])) {
      charsObj[charsArr[i]] = 0;
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));