问:
Use-case actor with many behaviors
I'm trying to imagine how a use-case actor with multiple behaviors actually shows up in the application.

Take the following real world but oversimplified case:

An environmental consulting organization has a project manager responsible for: creating and managing clients; projects; facilities and buildings, and equipment and supplies. A lot of this is just CRUD, but there's quite a bit more.

Does it make sense to have a ProjectManager class with all the behaviors implied? Just looking at the use-case diagram, I can see 20+ methods that would be required.

Project Management Use-Case

答:
Instead of putting all the eggs into a one basket, why don't you group responsibilities in different "roles" and then assign these roles to PM?

What I mean by that is, please bear with me and imagine:

Interface: CustomerRelations
Responsibilities: customer related ops (e.g. create customer, keep good relations with them etc)

Interface: OfficeManagement
Responsibilities: acquire necessary equipment to do business, and provide necessary supply to use them etc.

Interface: ProjectManagement
Responsibilities: monitor and supervise projects etc

And them

Class: ProjectManager implements CustomerRelations, OfficeManagement and ProjectManagement.

This way, you can easily re-shuffle responsibilities around if need be.

Title: Use-case actor with many behaviors


来源: stackexchange

问:
Installing Sbt on Ubuntu
I am trying to install SBT on ubuntu for the 1st time, have referred below link for the installation, but getting errors, please help me to fix it.

I need sbt for the Spark and scala projects.

sudo apt-get update

```<code>W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/wily-backports/multiverse/binary-i386/Packages  404  Not Found [IP: 91.189.91.26 80]

E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

答:
You can manually download and install the sbt package like in the following:

```<code>curl -OL https://github.com/sbt/sbt/releases/download/v1.0.3/sbt-1.0.3.tgz
tar xzf sbt-1.0.3.tgz

sudo mv sbt /usr/local/
sudo update-alternatives --install /usr/bin/sbt sbt /usr/local/sbt/sbt-1.0.3/bin/sbt 100
</code>```

ContentLicense: CC BY-SA 3.0

Title: Installing Sbt on Ubuntu

Body:
I am trying to install SBT on ubuntu for the 1st time, have referred below link for the installation, but getting errors, please help me to fix it.

I need sbt for the Spark and scala projects.

sudo apt-get update

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/wily-backports/multiverse/binary-i386/Packages  404  Not Found [IP: 91.189.91.26 80]

E: Some index files failed to download. They have been ignored, or old ones used instead.

Body:
You can manually download and install the sbt package like in the following:

curl -OL https://github.com/sbt/sbt/releases/download/v1.0.3/sbt-1.0.3.tgz
tar xzf sbt-1.0.3.tgz

sudo mv sbt /usr/local/
sudo update-alternatives --install /usr/bin/sbt sbt /usr/local/sbt/sbt-1.0.3/bin/sbt 100


问:
Javascript Div Html contains many input
I have a DIV in Html that contains several input The idea is to create the Div dynamically with a loop for if I click on the show button it takes a little time to display it is normal since we have 300 input in the DIV but my question is what is possible to display for example the first 10 input then the other 10 and etc ... so that do not wait a time to afichher at the same time</p>

```<code><!DOCTYPE html>
<html>
<body>

<h2>Div </h2>
<input id="ButtonShow" type="button" value="Show" onclick="show();"/>
<div id="p1"></div>

<script>

function show()
{
    for (i=0 ;i<350; i++)
    {
        document.getElementById("p1").innerHTML +=
               "<input type='checkbox' value='Callback' checked='checked'/><br>";
    }
}
</script>

</body>
</html>
</code>```

答:
I would use jQuery.

```<code>$("#p_id").append("<input type='checkbox' value='Callback' checked='checked'/><br>");
</code>```

If there are still problems with slow, then you can use setTimeout:

```<code>function addCheckBox(offset)
{
    $("#p_id").append("<input type='checkbox' value='Callback' checked='checked'/><br>");
    if (offset < 290)
        window.setTimeout(()=> addCheckBox(offset + 10), 50);
}

addCheckBox(0);
</code>```

Title: Javascript Div Html contains many input

Body:
I have a DIV in Html that contains several input The idea is to create the Div dynamically with a loop for if I click on the show button it takes a little time to display it is normal since we have 300 input in the DIV but my question is what is possible to display for example the first 10 input then the other 10 and etc ... so that do not wait a time to afichher at the same time

<!DOCTYPE html>

Div

<input id="ButtonShow" type="button" value="Show" onclick="show();"/>

Body:
I would use jQuery.

$("#p_id").append("<input type='checkbox' value='Callback' checked='checked'/><br>");

If there are still problems with slow, then you can use setTimeout:

function addCheckBox(offset)
{
    $("#p_id").append("<input type='checkbox' value='Callback' checked='checked'/><br>");
    if (offset < 290)
        window.setTimeout(()=> addCheckBox(offset + 10), 50);
}

addCheckBox(0);


问:
Wordpress - redirecting to product sub-category on separate page
I have a wordpress website and I have shown product categories on my home page using [product_categories columns="2"] shortcode. What I want is when somebody clicks on one of the product categories, it takes them to the product sub-category may be on separate page and I want the sub-categories to be shown exactly like the parent-categories shown on my homepage.

I have already created the sub-categories in my wordpress admin panel but unable to show them on separate page when somebody clicks on parent category. How to achieve that result ?

答:
you can create a taxonomy-product_cat.php file. and where you can get the current category id and use below function to get its clid category

```<code>get_term_children( $current_term_id, $taxonomy );
</code>```

after that you can use clild product category ids to display them

you can use below function to get current product category id

```<code>$queried_object = get_queried_object();
</code>```

Body:
you can create a taxonomy-product_cat.php file. and where you can get the current category id and use below function to get its clid category

get_term_children( $current_term_id, $taxonomy );

after that you can use clild product category ids to display them

you can use below function to get current product category id

$queried_object = get_queried_object();


问:
Why does OpenEntityManagerInViewFilter change @Transactional propagation REQUIRES_NEW behavior?
Using Spring 4.3.12, Spring Data JPA 1.11.8 and Hibernate 5.2.12.

We use the OpenEntityManagerInViewFilter to ensure our entity relationships do not throw LazyInitializationException after an entity has been loaded. Often in our controllers we use a @ModelAttribute annotated method to load an entity by id and make that loaded entity available to a controller's request mapping handler method.

In some cases like auditing we have entity modifications that we want to commit even when some other transaction may error and rollback.  Therefore we annotate our audit work with @Transactional(propagation = Propagation.REQUIRES_NEW) to ensure this transaction will commit successfully regardless of any other (if any) transactions which may or may not complete successfully.

What I've seen in practice using the OpenEntityManagerInviewFilter, is that when Propagation.REQUIRES_NEW transactions attempt to commit changes which occurred outside the scope of the new transaction causing work which should always result in successful commits to the database to instead rollback.

Example

Given this Spring Data JPA powered repository (the EmployeeRepository is similarly defined):

```<code>import org.springframework.data.jpa.repository.JpaRepository;

public interface MethodAuditRepository extends JpaRepository<MethodAudit,Long> {
}
</code>```

This service:

```<code>@Service
public class MethodAuditorImpl implements MethodAuditor {
  private final MethodAuditRepository methodAuditRepository;

  public MethodAuditorImpl(MethodAuditRepository methodAuditRepository) {
    this.methodAuditRepository = methodAuditRepository;
  }

  @Override @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void auditMethod(String methodName) {
    MethodAudit audit = new MethodAudit();
    audit.setMethodName(methodName);
    audit.setInvocationTime(LocalDateTime.now());
    methodAuditRepository.save(audit);
  }
}
</code>```

And this controller:

```<code>@Controller
public class StackOverflowQuestionController {
  private final EmployeeRepository employeeRepository;
  private final MethodAuditor methodAuditor;

  public StackOverflowQuestionController(EmployeeRepository employeeRepository, MethodAuditor methodAuditor) {
    this.employeeRepository = employeeRepository;
    this.methodAuditor = methodAuditor;
  }

  @ModelAttribute
  public Employee loadEmployee(@RequestParam Long id) {
    return employeeRepository.findOne(id);
  }

  @GetMapping("/updateEmployee")
  // @Transactional // <-- When uncommented, transactions work as expected (using OpenEntityManagerInViewFilter or not)
  public String updateEmployee(@ModelAttribute Employee employee, RedirectAttributes ra) {
    // method auditor performs work in new transaction
    methodAuditor.auditMethod("updateEmployee"); // <-- at close of this method, employee update occurrs trigging rollback

    // No code after this point executes

    System.out.println(employee.getPin());
    employeeRepository.save(employee);

    return "redirect:/";
  }
}
</code>```

When the updateEmployee method is exercised with an invalid pin number updateEmployee?id=1&pin=12345 (pin number is limited in the database to 4 characters), then no audit is inserted into the database.

Why is this?  Shouldn't the current transaction be suspended when the MethodAuditor is invoked?  Why is the modified employee flushing when this Propagation.REQUIRES_NEW transaction commits?

If I wrap the updateEmployee method in a transaction by annotating it as @Transactional, however, audits will persist as desired.  And this will work as expected whether or not the OpenEntityManagerInViewFilter is used.

答: While your application (server) tries to make two separate transactions you are still using a single EntityManager and single Datasource so at any given time JPA and the database see just one transaction. So if you want those things to be separated you need to setup two Datasources and two EntityManagers

Body:
Using Spring 4.3.12, Spring Data JPA 1.11.8 and Hibernate 5.2.12.

We use the OpenEntityManagerInViewFilter to ensure our entity relationships do not throw LazyInitializationException after an entity has been loaded. Often in our controllers we use a @ModelAttribute annotated method to load an entity by id and make that loaded entity available to a controller's request mapping handler method.

In some cases like auditing we have entity modifications that we want to commit even when some other transaction may error and rollback.  Therefore we annotate our audit work with @Transactional(propagation = Propagation.REQUIRES_NEW) to ensure this transaction will commit successfully regardless of any other (if any) transactions which may or may not complete successfully.

What I've seen in practice using the OpenEntityManagerInviewFilter, is that when Propagation.REQUIRES_NEW transactions attempt to commit changes which occurred outside the scope of the new transaction causing work which should always result in successful commits to the database to instead rollback.

Example

Given this Spring Data JPA powered repository (the EmployeeRepository is similarly defined):

import org.springframework.data.jpa.repository.JpaRepository;

public interface MethodAuditRepository extends JpaRepository<MethodAudit,Long> {
}

This service:

@Service
public class MethodAuditorImpl implements MethodAuditor {
  private final MethodAuditRepository methodAuditRepository;

  public MethodAuditorImpl(MethodAuditRepository methodAuditRepository) {
    this.methodAuditRepository = methodAuditRepository;
  }

  @Override @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void auditMethod(String methodName) {
    MethodAudit audit = new MethodAudit();
    audit.setMethodName(methodName);
    audit.setInvocationTime(LocalDateTime.now());
    methodAuditRepository.save(audit);
  }
}

And this controller:

@Controller
public class StackOverflowQuestionController {
  private final EmployeeRepository employeeRepository;
  private final MethodAuditor methodAuditor;

  public StackOverflowQuestionController(EmployeeRepository employeeRepository, MethodAuditor methodAuditor) {
    this.employeeRepository = employeeRepository;
    this.methodAuditor = methodAuditor;
  }

  @ModelAttribute
  public Employee loadEmployee(@RequestParam Long id) {
    return employeeRepository.findOne(id);
  }

  @GetMapping("/updateEmployee")
  // @Transactional // <-- When uncommented, transactions work as expected (using OpenEntityManagerInViewFilter or not)
  public String updateEmployee(@ModelAttribute Employee employee, RedirectAttributes ra) {
    // method auditor performs work in new transaction
    methodAuditor.auditMethod("updateEmployee"); // <-- at close of this method, employee update occurrs trigging rollback

    // No code after this point executes

    System.out.println(employee.getPin());
    employeeRepository.save(employee);

    return "redirect:/";
  }
}

When the updateEmployee method is exercised with an invalid pin number updateEmployee?id=1&pin=12345 (pin number is limited in the database to 4 characters), then no audit is inserted into the database.

Why is this?  Shouldn't the current transaction be suspended when the MethodAuditor is invoked?  Why is the modified employee flushing when this Propagation.REQUIRES_NEW transaction commits?

If I wrap the updateEmployee method in a transaction by annotating it as @Transactional, however, audits will persist as desired.  And this will work as expected whether or not the OpenEntityManagerInViewFilter is used.


问:
StackExchange.Redis.StrongName is refrenced but not included as package
I'm starting a new project using StackExchange.Redis and .Net Core 2.0.
But I get a conflict:

The type 'ConnectionMultiplexer' exists in both 'StackExchange.Redis.StrongName, Version=1.2.4.0, Culture=neutral, PublicKeyToken=c219ff1ca8c2ce46' and 'StackExchange.Redis, Version=1.2.6.0, Culture=neutral, PublicKeyToken=null'

Why is this showing even thou I'm not referencing StackExchange.Redis.StrongName and it's not even the same assembly version?

答: It is possible to use Strongname in your entire application, 1.2.6 is newer and will be used. The problem is when you add Redis.Stackexchange you will have the same namespace from two different dll's. .Net compiler doesn't know which one to use. If you need 1.2.6, use the StrongName version throughout your application and no more problems ....</p>


问:
Can You Get a Transparent Gradient using PHP ImageMagick?
Something to the tune of:

```<code>$gradient->newPseudoImage($width, $height, "gradient:transparent-transparent");
</code>```

Basically I'm looking to create a wet floor effect for uploaded images. So far, it seems you can only create a gradient into a solid color.

答:
It turns out if the image you are cloning does not have an alpha channel set you can't create a gradient from an image to a transparent background (at least, I was unable to find a way) What you can do is test for the alpha channel and set it if need be. Here's the working code if you're interested:

```<code>$im = new Imagick('image.jpg');

if (!$im->getImageAlphaChannel()) {
    $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
}

$refl = $im->clone();
$refl->flipImage();

$gradient = new Imagick();

$gradient->newPseudoImage($refl->getImageWidth() + 10, $refl->getImageHeight() + 10, "gradient:transparent-black");

$refl->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, 0);

$canvas = new Imagick();

$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;

$canvas->newImage($width, $height, 'none');
$canvas->setImageFormat('png');

$canvas->compositeImage($im, imagick::COMPOSITE_SRCOVER, 20, 10);
$canvas->compositeImage($refl, imagick::COMPOSITE_SRCOVER, 20, $im->getImageHeight() + 10);
</code>```

This will take a run of the mill jpg and convert it into a png with a reflection fading into a transparent background.

```<code>$canvas->writeImages("new.png", true);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Something to the tune of:

$gradient->newPseudoImage($width, $height, "gradient:transparent-transparent");

Basically I'm looking to create a wet floor effect for uploaded images. So far, it seems you can only create a gradient into a solid color.

Body:
It turns out if the image you are cloning does not have an alpha channel set you can't create a gradient from an image to a transparent background (at least, I was unable to find a way) What you can do is test for the alpha channel and set it if need be. Here's the working code if you're interested:

$im = new Imagick('image.jpg');

if (!$im->getImageAlphaChannel()) {
    $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_SET);
}

$refl = $im->clone();
$refl->flipImage();

$gradient = new Imagick();

$gradient->newPseudoImage($refl->getImageWidth() + 10, $refl->getImageHeight() + 10, "gradient:transparent-black");

$refl->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, 0);

$canvas = new Imagick();

$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;

$canvas->newImage($width, $height, 'none');
$canvas->setImageFormat('png');

$canvas->compositeImage($im, imagick::COMPOSITE_SRCOVER, 20, 10);
$canvas->compositeImage($refl, imagick::COMPOSITE_SRCOVER, 20, $im->getImageHeight() + 10);

This will take a run of the mill jpg and convert it into a png with a reflection fading into a transparent background.

$canvas->writeImages("new.png", true);


问:
Python - replace commas in string
I have the following string:

string = "[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],,,,[11801 14001],[11801 14001],[14001],[14001],[14001]"

For putting the string into a list later, I want to remove 3 of the 4 commas in the middle of the string. I don't want a solution like string.replace(",,,,",",") because in other cases there are 7 or more commas in a row and then this doesn't work. Do you have a solution? Thanks.

答:
You can use a regular expression to search for two or more comma's and replace them with one comma.

```<code>result = re.sub(",,+", ",", string, 0, re.IGNORECASE | re.VERBOSE | re.MULTILINE)
</code>```

,,+

Options: Case insensitive; Free-spacing; Dot doesn't match line breaks; ^$ match at line breaks; Regex syntax only

Match the character “,” literally «,»

Match the character “,” literally «,+»

Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

Title: Python - replace commas in string

Body:
You can use a regular expression to search for two or more comma's and replace them with one comma.

result = re.sub(",,+", ",", string, 0, re.IGNORECASE | re.VERBOSE | re.MULTILINE)

,,+

Options: Case insensitive; Free-spacing; Dot doesn't match line breaks; ^$ match at line breaks; Regex syntax only

Match the character “,” literally «,»

Match the character “,” literally «,+»

Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»


问:
List all files with specific extension beneath a directory in Scala
I am trying to get a List of all files with a given extension from within a given directory (and it's sub-directories).
So far what I have done :

```<code>var pipelineList: List[File] = Nil

  private def getPipelines(dir: File): Unit =
    {
      val tmp = dir.listFiles();
      for (f <- tmp) {
        if (f.isDirectory())
          getPipelines(f)
        else if (f.isFile() && (f.getName.endsWith(".pipeline"))) {
          pipelineList = pipelineList ::: List(f)
        }
      }
    }
</code>```

This is working as I'm getting all fies with ".pipeline" extension but I want the function to return a list of File objects (List,Array anything) instead of modifying an outside list. I tried declaring the list inside but the recursive calls re-initialize the list everytime, also tried passing the result list as a parameter but Scala throws error when I try to add anything to it saying it cannot re-assign to val.

Also tried another way :

```<code>def getListOfFiles(dir: File): Array[File] = {
    val filesList= dir.listFiles
    filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)
    filesList.filter(_.getName.endsWith(".pipeline"))
}
</code>```

This is successfully getting all the files beneath the directory but the filter is not working as it's not returning anything even though the predicate gets satisfied.

Any help is appreciated.

答:
```<code>filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)
</code>```

is returning a new Immutable Array without changing the filesList. so you need to:

```<code>val res = filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)
res.filter(_.getName.endsWith(".pipeline"))
</code>```

Body:
I am trying to get a List of all files with a given extension from within a given directory (and it's sub-directories).
So far what I have done :

var pipelineList: List[File] = Nil

  private def getPipelines(dir: File): Unit =
    {
      val tmp = dir.listFiles();
      for (f <- tmp) {
        if (f.isDirectory())
          getPipelines(f)
        else if (f.isFile() && (f.getName.endsWith(".pipeline"))) {
          pipelineList = pipelineList ::: List(f)
        }
      }
    }

This is working as I'm getting all fies with ".pipeline" extension but I want the function to return a list of File objects (List,Array anything) instead of modifying an outside list. I tried declaring the list inside but the recursive calls re-initialize the list everytime, also tried passing the result list as a parameter but Scala throws error when I try to add anything to it saying it cannot re-assign to val.

Also tried another way :

def getListOfFiles(dir: File): Array[File] = {
    val filesList= dir.listFiles
    filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)
    filesList.filter(_.getName.endsWith(".pipeline"))
}

This is successfully getting all the files beneath the directory but the filter is not working as it's not returning anything even though the predicate gets satisfied.

Any help is appreciated.

Body:
filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)

is returning a new Immutable Array without changing the filesList. so you need to:

val res = filesList ++ filesList.filter(_.isDirectory).flatMap(getListOfFiles)
res.filter(_.getName.endsWith(".pipeline"))


问:
How to get value from JSON array in Swift3
I'm new in Swift3 and I'm confused how to get value from this JSON array.

This is my coding:

```<code>let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
       return
    }else{
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

            if let allEntry = json?[“allentry"] as? [NSArray] {
                 print("All Entry: \(allEntry)")
             }
        }catch{
            print(error.localizedDescription)
        }
    }
}.resume()
</code>```

This is JSON:

```<code>"allentry": [
              [
                "Month",
                "Entry"
              ],
              [
                "Jan",
                109.52380952380953
              ],
              [
                "Feb",
                105.26315789473684
              ],
              [
                "Mar",
                104.54545454545455
              ],
              [
                "Apr",
                100
              ],
              [
                "May",
                105
              ],
              [
                "Jun",
                106.66666666666667
              ],
              [
                "Jul",
                100
              ],
              [
                "Aug",
                100
              ],
              [
                "Sep",
                100
              ],
              [
                "Oct",
                72.727272727272734
              ],
              [
                "Nov",
                0
              ],
              [
                "Dec",
                0
              ]
            ]
</code>```

The output I got was this:

All Entry:

[<__NSArrayI 0x170029e60>( Month, Entry ) , <__NSArrayI 0x17002a0a0>(
Jan,
109.5238095238095 ) , <__NSArrayI 0x170029fc0>( Feb,
105.2631578947368 ) , <__NSArrayI 0x17002a100>( Mar,
104.5454545454545 ) , <__NSArrayI 0x17002a2e0>( Apr, 100 ) , <__NSArrayI 0x17002a3a0>( May, 105 ) , <__NSArrayI 0x17002a740>( Jun,
106.6666666666667 ) , <__NSArrayI 0x17002a920>( Jul, 100 ) , <__NSArrayI 0x17002a860>( Aug, 100 ) , <__NSArrayI 0x17002ade0>( Sep,
100 ) , <__NSArrayI 0x17002a8c0>( Oct,
72.72727272727273 ) , <__NSArrayI 0x17002a980>( Nov, 0 ) , <__NSArrayI 0x17002a9e0>( Dec, 0 ) ]

答:
The JSON is an array of arrays, when you are printing it in the console, the console is printing the arrays inside the surrounding array.

As to how can you access the individual arrays and the values in them, you can use loops like this:

```<code>var months = [Any]()
var values = [Any]()
for entry in allEntry {
    months.append(entry[0])
    values.append(entry[1])
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in Swift3 and I'm confused how to get value from this JSON array.

This is my coding:

let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
       return
    }else{
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

            if let allEntry = json?[“allentry"] as? [NSArray] {
                 print("All Entry: \(allEntry)")
             }
        }catch{
            print(error.localizedDescription)
        }
    }
}.resume()

This is JSON:

"allentry": [
              [
                "Month",
                "Entry"
              ],
              [
                "Jan",
                109.52380952380953
              ],
              [
                "Feb",
                105.26315789473684
              ],
              [
                "Mar",
                104.54545454545455
              ],
              [
                "Apr",
                100
              ],
              [
                "May",
                105
              ],
              [
                "Jun",
                106.66666666666667
              ],
              [
                "Jul",
                100
              ],
              [
                "Aug",
                100
              ],
              [
                "Sep",
                100
              ],
              [
                "Oct",
                72.727272727272734
              ],
              [
                "Nov",
                0
              ],
              [
                "Dec",
                0
              ]
            ]

The output I got was this:

All Entry:

[<__NSArrayI 0x170029e60>( Month, Entry ) , <__NSArrayI 0x17002a0a0>(
Jan,
109.5238095238095 ) , <__NSArrayI 0x170029fc0>( Feb,
105.2631578947368 ) , <__NSArrayI 0x17002a100>( Mar,
104.5454545454545 ) , <__NSArrayI 0x17002a2e0>( Apr, 100 ) , <__NSArrayI 0x17002a3a0>( May, 105 ) , <__NSArrayI 0x17002a740>( Jun,
106.6666666666667 ) , <__NSArrayI 0x17002a920>( Jul, 100 ) , <__NSArrayI 0x17002a860>( Aug, 100 ) , <__NSArrayI 0x17002ade0>( Sep,
100 ) , <__NSArrayI 0x17002a8c0>( Oct,
72.72727272727273 ) , <__NSArrayI 0x17002a980>( Nov, 0 ) , <__NSArrayI 0x17002a9e0>( Dec, 0 ) ]

Body:
The JSON is an array of arrays, when you are printing it in the console, the console is printing the arrays inside the surrounding array.

As to how can you access the individual arrays and the values in them, you can use loops like this:

var months = [Any]()
var values = [Any]()
for entry in allEntry {
    months.append(entry[0])
    values.append(entry[1])
}


问:
In AWS Java SDK, can I run more than one handler in a single package?

I tried to create multiple handler in a single package. But when I tried to run on AWS through Eclipse, I can only add one handler to one function. How to handle this scenario?

答:
Upload your code artifacts to s3, then go to aws lambda console create multiple lambda functions with the uploaded artifacts from s3, providing different handlers for different functions, As shown in the picture.

Handlers like

```<code>Javalambda.example.GetPriceHandler
Javalambda.example.LambdaFunctionHandler
Javalambda.example.SampleHandler
</code>```

Body:
Upload your code artifacts to s3, then go to aws lambda console create multiple lambda functions with the uploaded artifacts from s3, providing different handlers for different functions, As shown in the picture.

Handlers like

Javalambda.example.GetPriceHandler
Javalambda.example.LambdaFunctionHandler
Javalambda.example.SampleHandler


问:
How can I mock Moose objects?
What strategies have Perl people used when mocking Moose objects that they will inject into other Moose objects as type-constrained attributes?

Test::MockObject::Extends doesn't seem to play well with Moose. I need the object to blessed as a specific package though so a vanilla Test::MockObject won't work. I'm sure other folks have had similar difficulty. How did you resolve it?

Extra Points for Solutions that are already on CPAN.

答:
bit of a self plug, but I wrote http://search.cpan.org/~cycles/Test-Magpie-0.05/lib/Test/Magpie.pm, maybe you'll find this useful. A mock created with this acts as any class, and does every role possible. It doesn't mock a specific object or class at all. Sadly CPAN's search is a bit rubbish, so searching for "test mock" doesn't show it in the results.

I should also mention that the documentation doesn't contain a huge amount of motivation or example code, so you may wish to check some of the tests:

http://cpansearch.perl.org/src/CYCLES/Test-Magpie-0.05/t/mockito_tutorial.t

http://cpansearch.perl.org/src/CYCLES/Test-Magpie-0.05/t/basic.t

Title: How can I mock Moose objects?


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
There you go...

```<code>#include <iostream>
using namespace std;

int main()
{
    int firstvalue = 5, secondvalue = 15;
    int * p1, *p2;

    p1 = &firstvalue;
    p2 = &secondvalue;
    cout << "firstvalue address: ," << &firstvalue << "p1 address: ," << p1 << "p1 Value " << *p1 << endl;
    *p1 = 10;    //line 1
    *p2 = *p1;  //line 2
    cout <<  "p1 Value " << *p1 << "p2 Value " << *p2 << endl;
    p1 = p2;   //line 3
    cout << "p1 address: ," << p1 << "p2 address: ," << p2 << endl;
    *p1 = 20;
    cout << "p1 value: " << *p1 << endl;

    return 0;
}
</code>```

output:

firstvalue address: 0115FA74,p1 address: 0115FA74,p1 Value 5

p1 Value 10, p2 Value 10

p1 address: 0115FA68,p2 address: 0115FA68

p1 value: 20

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

Body:
There you go...

#include <iostream>
using namespace std;

int main()
{
    int firstvalue = 5, secondvalue = 15;
    int * p1, *p2;

    p1 = &firstvalue;
    p2 = &secondvalue;
    cout << "firstvalue address: ," << &firstvalue << "p1 address: ," << p1 << "p1 Value " << *p1 << endl;
    *p1 = 10;    //line 1
    *p2 = *p1;  //line 2
    cout <<  "p1 Value " << *p1 << "p2 Value " << *p2 << endl;
    p1 = p2;   //line 3
    cout << "p1 address: ," << p1 << "p2 address: ," << p2 << endl;
    *p1 = 20;
    cout << "p1 value: " << *p1 << endl;

    return 0;
}

output:

firstvalue address: 0115FA74,p1 address: 0115FA74,p1 Value 5

p1 Value 10, p2 Value 10

p1 address: 0115FA68,p2 address: 0115FA68

p1 value: 20


问:
Combining two image into one new image in react native
I have two separate images one is the main image that clicks from the camera and another image I am picking from gallery its a logo, I need to combine these two images and make new image so that I can save that image into gallery and share on social media I need to do this with react native thanks for the help

```<code><Image
    style={{width: width, height: height*.7}}
    source={{ uri: imageAdress }} />
<Image
   source={this.state.avatarSource}
   style={{width: 80, height: 80, position:'absolute', top: 20, left: 20}} />
</code>```

Here are the two images now i need to combine them.

答:
i have fount the answer of my question. You can take a snapshot of you View its simple you can put both images in one View and snapshot that View. i use this plugin.

react-native-view-shot

https://github.com/gre/react-native-view-shot

this will allow you to take a snapshot of particular View
Thanks

Body:
I have two separate images one is the main image that clicks from the camera and another image I am picking from gallery its a logo, I need to combine these two images and make new image so that I can save that image into gallery and share on social media I need to do this with react native thanks for the help

<Image
    style={{width: width, height: height*.7}}
    source={{ uri: imageAdress }} />
<Image
   source={this.state.avatarSource}
   style={{width: 80, height: 80, position:'absolute', top: 20, left: 20}} />

Here are the two images now i need to combine them.


问:
HAProxy config for subdomain redirection
We have a HAProxy in front of a tomcat cluster in our environment. Right now, we are directing all the traffic on ports 80 and 443 to the tomcat-https backend. The issue is that some of our subdomain names need to be processed before it hits the https, with the current setup we are running into the insecure certificate issue. So, now we need to direct these subdomains to 8080 on tomcat. These subdomains are not fixed names, we need to just check if there is a subdomain and direct it to 8080 or else to 443.</p>

答:
You can use acl to check for the presence of a subdomain name in the URL. It can be done like this.

acl subdomain_not_present hdr_beg(host) -i www

And then depending on the value of subdomain_not_present, you can use the appropriate backend to redirect to.


问:
What's the ugliest code you were forced to write by outside limitations?
What is the ugliest code that you wrote - not because you didn't know better, but because of limitations of the software, the hardware or the company policy?

Because of unusual choices in database layouts and programming languages, I once built a C program that read in a SQL database structure and generated another C program that'd read that database and back it up into a file, or copy it into a second database that shared more or less the same columns. It was a monster clunky code generator.

答:
Once upon a time, I was working for a small programming house with a client who had a legacy COBOL application that they wanted converted to Visual Basic.  I was never a fan of VB, but that's not an unreasonable thing to want.

Except that they wanted the interface to be preserved and to function identically to the existing version.

So we were forced to produce a VB app consisting of a single form with a grid of roughly 100 text entry boxes, all of which were completely passive.  Except the one in the bottom right, which had a single event handler that was several thousand lines long and processed all the data in all the entry boxes when you exited the field.

OwnerDisplayName: Dave Sherohman


Title: Python - replace commas in string

Body:
I have the following string:

string = "[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],,,,[11801 14001],[11801 14001],[14001],[14001],[14001]"

For putting the string into a list later, I want to remove 3 of the 4 commas in the middle of the string. I don't want a solution like string.replace(",,,,",",") because in other cases there are 7 or more commas in a row and then this doesn't work. Do you have a solution? Thanks.

Body:
Alternative way, Use split and join

>>> ','.join([i for i in string.split(',') if i])
'[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[11801 14001],[14001],[14001],[14001]'


问:
How to display Current date in HTML?
How to display Current date (DD mon YYYY) in HTML, this has to be implemented in Php code   </p>

```<code><div class="container-fluid" style="padding: 0rem 1rem;">
  <h3>Attendance : {current_date} </h3>
  <hr>
  <p id="Page_MsgBox" style="padding: 0rem 1rem;"></p>
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
    {$attendance_table}
  </div>
</div>
</code>```

答:
Try this:-

```<code><h3>Attendance : <?php echo date('d M Y'); ?></h3>
</code>```

Hope it helps!

Title: How to display Current date in HTML?

Body:
How to display Current date (DD mon YYYY) in HTML, this has to be implemented in Php code

Attendance : {current_date}

    {$attendance_table}

Body:
Try this:-

<h3>Attendance : <?php echo date('d M Y'); ?></h3>

Hope it helps!


问:
FOSUser login error only in "prod"
I have a fresh install of Symfony with fosuser and SonataAdmin. I try to show the users in the admin. I have followed the explainations in the Symfony doc, and everything is well if I go the myapp/app_dev.php/admin. I log in, go to the admin and see the users.

But, if I go the myapp/admin, I have an error when I try to log : "Authentication request could not be processed due to a system problem."

I don't have any log in the prod.log file.

I am new using Symfony, so maybe there is a simple mistake... ?

Thanks for your help !

PS : Here is my log when I log with app_dev, maybe it can help ?

https://pastebin.com/cDvDR4XK

答:
When things like this happen, you should do at least:

check symfony logs & apache/nginx logs

check confs & database

and obviously clear all caches

Title: FOSUser login error only in "prod"


问:
Java-Swing: A problem using layout managers!
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

```<code>scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();
</code>```

答: Try setting the maximum width for both the JScrollPane and the JList that is within it.

Body:
I'm working on a JDialog (by hand, no GUI builders) and I'm having a problem doing the layout.

I have this:

My problem is that I don't know what how to tell that JList (within a JScrollPane) to have a Maximum width, I used the setSize, setMaximumSize and nothing works! I need that JList's width to be the half of the picture's size.

Explain the layouts:

The "Gene Information" is a GridLayout 2x4, it's contained by a JPanel with BoxLayout, the +/- JButtons is a BoxLayout also, all what I said before is within a BoxLayout.
Now, the "Genes" JPanel is a GridBagLayout.

What can I do?

Thanks in advance!

PD: The other borders are just for seeign the boundaries of the components.

    Source Code:

scpGenesList.setViewportView(lstGenesList);

pnlGeneInfo.setLayout(new GridLayout(4, 2, 10, 10));
pnlGeneInfo.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Gene Information"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));
lblGeneSymbol.setText("Symbol:");
lblGeneSymbol.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneChromosome.setText("Chromosome:");
lblGeneChromosome.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStartPosition.setText("Start Position:");
lblGeneStartPosition.setHorizontalAlignment(SwingConstants.RIGHT);
lblGeneStopPosition.setText("Stop Position:");
lblGeneStopPosition.setHorizontalAlignment(SwingConstants.RIGHT);
pnlGeneInfo.add(lblGeneSymbol);
pnlGeneInfo.add(lblGeneSymbolValue);
pnlGeneInfo.add(lblGeneChromosome);
pnlGeneInfo.add(lblGeneChromosomeValue);
pnlGeneInfo.add(lblGeneStartPosition);
pnlGeneInfo.add(lblGeneStartPositionValue);
pnlGeneInfo.add(lblGeneStopPosition);
pnlGeneInfo.add(lblGeneStopPositionValue);

pnlGWASAddRemoveButtons.setLayout(new BoxLayout(pnlGWASAddRemoveButtons, BoxLayout.X_AXIS));
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());
pnlGWASAddRemoveButtons.add(cmdGenesAdd);
pnlGWASAddRemoveButtons.add(Box.createHorizontalStrut(10));
pnlGWASAddRemoveButtons.add(cmdGenesRemove);
pnlGWASAddRemoveButtons.add(Box.createHorizontalGlue());

pnlGeneInfoButtons.setLayout(new BoxLayout(pnlGeneInfoButtons, BoxLayout.Y_AXIS));
pnlGeneInfoButtons.add(pnlGeneInfo);
pnlGeneInfoButtons.add(Box.createVerticalStrut(10));
pnlGeneInfoButtons.add(pnlGWASAddRemoveButtons);

pnlGenesPanel.setLayout(new GridBagLayout());
pnlGenesPanel.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createTitledBorder("Genes"),
        BorderFactory.createEmptyBorder(10, 10, 10, 10)));

GridBagConstraints ctrGenes = new GridBagConstraints();
ctrGenes.fill = GridBagConstraints.BOTH;
ctrGenes.gridx = 0;
ctrGenes.gridy = 0;
ctrGenes.gridwidth = 1;
ctrGenes.gridheight = 1;
ctrGenes.weighty = 1.0;
ctrGenes.weightx = 1.0;
ctrGenes.insets = new Insets(0, 0, 0, 10);
pnlGenesPanel.add(scpGenesList, ctrGenes);

GridBagConstraints ctrGenesInfoButton = new GridBagConstraints();
ctrGenesInfoButton.fill = GridBagConstraints.BOTH;
ctrGenesInfoButton.gridx = 1;
ctrGenesInfoButton.gridy = 0;
ctrGenesInfoButton.gridwidth = 1;
ctrGenesInfoButton.gridheight = 1;
ctrGenesInfoButton.weighty = 1.0;
ctrGenesInfoButton.weightx = 1.0;
pnlGenesPanel.add(pnlGeneInfoButtons, ctrGenesInfoButton);

contentPane.add(pnlGenesPanel);

pack();


问:
Bootstrap datepicker in TypeScript is not working
I am a newbie to Angular 4 and I am trying to make a sort of jQuery call from my HTML. I have tried wrapping this jQuery call in a TypeScript method. Upon clicking the calendar button nothing appears.

I am unsure what line to exactly add in my index.html.

Below is my code snippet :

home.component.html

```<code><h2>As of date</h2>
<div class="input-group" style="width: 230px">
    <input class="form-control date" type='text' placeholder="dd/mm/yyyy" id="date-picker"/>
    <span class="input-group-btn">
      <button class="btn btn-primary btn-icon" (click)="pickDate()">
        <i class="fa fa-calendar-o"></i>
      </button>
    </span>
</div>
</code>```

home.component.ts

```<code> import { Component, OnInit } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    import { TasksService } from 'app/shared';

        @Component({
          selector: 'MyFirstAngularApplication-home',
          styleUrls: [ './home.component.scss' ],
          templateUrl: './home.component.html'
        })

        export class HomeComponent {
          pickDate() {
            $('#date-picker').datepicker('show');
          }
        }
</code>```

Where exactly am I going wrong?

答:
Try this,

Before added needs to be installed jquery in angular project via command like

npm install jquery

Index.Html

```<code><script src="assets/Scripts/Jquery3.2.1.min.js"></script>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/bootstrap-theme.min.css">
<script src="assets/Scripts/bootstrap.min.js"></script>
<link rel="stylesheet" href="assets/css/jquery-ui.css">
<script src="assets/Scripts/jquery-ui.js"></script>
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { TasksService } from 'app/shared';
declare var $: any;

    @Component({
      selector: 'MyFirstAngularApplication-home',
      styleUrls: [ './home.component.scss' ],
      templateUrl: './home.component.html'
    })

    export class HomeComponent {
      pickDate() {
        $("#date-picker").datepicker();
      }
    }
</code>```

Body:
I am a newbie to Angular 4 and I am trying to make a sort of jQuery call from my HTML. I have tried wrapping this jQuery call in a TypeScript method. Upon clicking the calendar button nothing appears.

I am unsure what line to exactly add in my index.html.

Below is my code snippet :

home.component.html

As of date

    <input class="form-control date" type='text' placeholder="dd/mm/yyyy" id="date-picker"/>

      <button class="btn btn-primary btn-icon" (click)="pickDate()">

      </button>

home.component.ts

 import { Component, OnInit } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    import { TasksService } from 'app/shared';

        @Component({
          selector: 'MyFirstAngularApplication-home',
          styleUrls: [ './home.component.scss' ],
          templateUrl: './home.component.html'
        })

        export class HomeComponent {
          pickDate() {
            $('#date-picker').datepicker('show');
          }
        }

Where exactly am I going wrong?

Body:
Try this,

Before added needs to be installed jquery in angular project via command like

npm install jquery

Index.Html

<script src="assets/Scripts/Jquery3.2.1.min.js"></script>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/bootstrap-theme.min.css">
<script src="assets/Scripts/bootstrap.min.js"></script>
<link rel="stylesheet" href="assets/css/jquery-ui.css">
<script src="assets/Scripts/jquery-ui.js"></script>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { TasksService } from 'app/shared';
declare var $: any;

    @Component({
      selector: 'MyFirstAngularApplication-home',
      styleUrls: [ './home.component.scss' ],
      templateUrl: './home.component.html'
    })

    export class HomeComponent {
      pickDate() {
        $("#date-picker").datepicker();
      }
    }


问:
How to load a trained MXnet model?
I have trained a network using MXnet, but am not sure how I can save and load the parameters for later use. First I define and train the network:

    dataIn = mx.sym.var('data')
    fc1 = mx.symbol.FullyConnected(data=dataIn, num_hidden=100)
    act1 = mx.sym.Activation(data=fc1, act_type="relu")
    fc2 = mx.symbol.FullyConnected(data=act1, num_hidden=50)
    act2 = mx.sym.Activation(data=fc2, act_type="relu")
    fc3 = mx.symbol.FullyConnected(data=act2, num_hidden=25)
    act3 = mx.sym.Activation(data=fc3, act_type="relu")
    fc4 = mx.symbol.FullyConnected(data=act3, num_hidden=10)
    act4 = mx.sym.Activation(data=fc4, act_type="relu")
    fc5 = mx.symbol.FullyConnected(data=act4, num_hidden=2)
    lenet = mx.sym.SoftmaxOutput(data=fc5, name='softmax',normalization = 'batch')

# create iterator around training and validation data
train_iter = mx.io.NDArrayIter(data=data[:ntrain], label = phen[:ntrain],batch_size=batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(data=data[ntrain:], label=phen[ntrain:], batch_size=batch_size)

# create a trainable module on GPU 0
lenet_model = mx.mod.Module(symbol=lenet, context=mx.gpu())
# train with the same
lenet_model.fit(train_iter,
                eval_data=val_iter,
                optimizer='adam',
                optimizer_params={'learning_rate':0.00001},
                eval_metric='f1',
                batch_end_callback = mx.callback.Speedometer(batch_size, 10),
                num_epoch=1000)
```

<p>This model performs well on the test set, so I want to keep it. Next, I save the network layout and the parameterization:</p>

<pre class="lang-python prettyprint-override"><code>lenet.save('./testNet_symbol.mxnet')
lenet_model.save_params('./testNet_module.mxnet')
</code>```

All the documentation I can find on loading the network seem to have implemented the save function within the training routine, to save the network parameters at the end of each epoch. I haven't set these checkpoints during the training process Other methods use the mx.model.FeedForward class, which doesn't seem appropriate. Still other methods load the network from a .json file, which I don't have as a result of my save functions. How can I save/load a network after it's already finished training?

答:
You just have to do this instead to save:

```<code>lenet_model.save_checkpoint('lenet', num_epoch, save_optimizer_states=True)
</code>```

This would create 3 files if the states flag is set to True else 2 files:

.params (weights),
.json (symbol),
.states

And this to load:

```<code>lenet_model = mx.mod.Module.load(prefix,epoch)
lenet_model.bind(for_training=False, data_shapes=[('data', (1,3,224,224))])
</code>```

Title: How to load a trained MXnet model?

Body:
I have trained a network using MXnet, but am not sure how I can save and load the parameters for later use. First I define and train the network:

    dataIn = mx.sym.var('data')
    fc1 = mx.symbol.FullyConnected(data=dataIn, num_hidden=100)
    act1 = mx.sym.Activation(data=fc1, act_type="relu")
    fc2 = mx.symbol.FullyConnected(data=act1, num_hidden=50)
    act2 = mx.sym.Activation(data=fc2, act_type="relu")
    fc3 = mx.symbol.FullyConnected(data=act2, num_hidden=25)
    act3 = mx.sym.Activation(data=fc3, act_type="relu")
    fc4 = mx.symbol.FullyConnected(data=act3, num_hidden=10)
    act4 = mx.sym.Activation(data=fc4, act_type="relu")
    fc5 = mx.symbol.FullyConnected(data=act4, num_hidden=2)
    lenet = mx.sym.SoftmaxOutput(data=fc5, name='softmax',normalization = 'batch')

# create iterator around training and validation data
train_iter = mx.io.NDArrayIter(data=data[:ntrain], label = phen[:ntrain],batch_size=batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(data=data[ntrain:], label=phen[ntrain:], batch_size=batch_size)

# create a trainable module on GPU 0
lenet_model = mx.mod.Module(symbol=lenet, context=mx.gpu())
# train with the same
lenet_model.fit(train_iter,
                eval_data=val_iter,
                optimizer='adam',
                optimizer_params={'learning_rate':0.00001},
                eval_metric='f1',
                batch_end_callback = mx.callback.Speedometer(batch_size, 10),
                num_epoch=1000)

This model performs well on the test set, so I want to keep it. Next, I save the network layout and the parameterization:

lenet.save('./testNet_symbol.mxnet')
lenet_model.save_params('./testNet_module.mxnet')

All the documentation I can find on loading the network seem to have implemented the save function within the training routine, to save the network parameters at the end of each epoch. I haven't set these checkpoints during the training process Other methods use the mx.model.FeedForward class, which doesn't seem appropriate. Still other methods load the network from a .json file, which I don't have as a result of my save functions. How can I save/load a network after it's already finished training?

Body:
You just have to do this instead to save:

lenet_model.save_checkpoint('lenet', num_epoch, save_optimizer_states=True)

This would create 3 files if the states flag is set to True else 2 files:

.params (weights),
.json (symbol),
.states

And this to load:

lenet_model = mx.mod.Module.load(prefix,epoch)
lenet_model.bind(for_training=False, data_shapes=[('data', (1,3,224,224))])


问:
Adding className but css is not affecting in ReactJS Components
I have a component called Single Box which will return a div , but i need to have the same class for 6 times , one of the way is i can write Single Box component six times , but thats not a good way.

So i made another component which Multiple Box , here i will loop the Single Box component for six times .

SingleBox

```<code>  render(){
    return(
      <div className="box-content"></div>
    )
  }
</code>```

MultipleBox

```<code> render(){
  let singleBoxArray = [];
   for (var i=0; i<3; i++) {
     if(i< 2){
       singleBoxArray.push(<SingleBox key={i}/>);
     }else {
       singleBoxArray.push(<SingleBox className="box-three"/>)
     }
   }
    return(
      <div>
        {singleBoxArray}
      </div>
    )

    }
</code>```

Here for the "Third SingleBox" , i need add one more class and it should affect the css. when i make the console.log("array" , singleBoxArray). For the third elememet i am getting the className in this.props, but my css is not changing .

Many Thanks in Advance

答:
You are adding class to Component and not to DOM.

So,thats why your CSS not showing effect.

Your SingleBox Component already attached with box-content class and you are not updating it.

In order to to update it,you need to attach class to DOM.

Use props for your custom class myclass

```<code>//SingleBox Component.

const SingleBox = (props) => (<div className={props.myclass}>Hello</div>);
</code>```

//MultipleBox

```<code>render() {
    let singleBoxArray = [];
    for (var i = 0; i < 3; i++) {
      if (i < 2) {
        singleBoxArray.push(<SingleBox key={i} myclass="box-content" />);
      } else {
        singleBoxArray.push(<SingleBox key={i} myclass="box-three" />)
      }
    }
    return (
      <div>
        {singleBoxArray}
      </div>
    )
  }
</code>```

Body:
I have a component called Single Box which will return a div , but i need to have the same class for 6 times , one of the way is i can write Single Box component six times , but thats not a good way.

So i made another component which Multiple Box , here i will loop the Single Box component for six times .

SingleBox

  render(){
    return(

    )
  }

MultipleBox

 render(){
  let singleBoxArray = [];
   for (var i=0; i<3; i++) {
     if(i< 2){
       singleBoxArray.push(<SingleBox key={i}/>);
     }else {
       singleBoxArray.push(<SingleBox className="box-three"/>)
     }
   }
    return(

        {singleBoxArray}

    )

    }

Here for the "Third SingleBox" , i need add one more class and it should affect the css. when i make the console.log("array" , singleBoxArray). For the third elememet i am getting the className in this.props, but my css is not changing .

Many Thanks in Advance

Body:
You are adding class to Component and not to DOM.

So,thats why your CSS not showing effect.

Your SingleBox Component already attached with box-content class and you are not updating it.

In order to to update it,you need to attach class to DOM.

Use props for your custom class myclass

//SingleBox Component.

const SingleBox = (props) => (<div className={props.myclass}>Hello</div>);

//MultipleBox

render() {
    let singleBoxArray = [];
    for (var i = 0; i < 3; i++) {
      if (i < 2) {
        singleBoxArray.push(<SingleBox key={i} myclass="box-content" />);
      } else {
        singleBoxArray.push(<SingleBox key={i} myclass="box-three" />)
      }
    }
    return (
      <div>
        {singleBoxArray}
      </div>
    )
  }


答:
Your SingleBox Component doesn't accept className as a prop.

it should be like this.

```<code>render(){
    const className = `box-content ${this.props.className}`
    return(
      <div className={className}></div>
    )
  }
</code>```

And you can keep a default Prop for className as empty string

you can set defaultProps to a component by simply setting it like this before exporting.

```<code>SingleBox.defaultProps = {
  className: ''
}

export default SingleBox;
</code>```

Title: Adding className but css is not affecting in ReactJS Components

Body:
Your SingleBox Component doesn't accept className as a prop.

it should be like this.

render(){
    const className = `box-content ${this.props.className}`
    return(
      <div className={className}></div>
    )
  }

And you can keep a default Prop for className as empty string

you can set defaultProps to a component by simply setting it like this before exporting.

SingleBox.defaultProps = {
  className: ''
}

export default SingleBox;


问:
Getting Current Location instead of Cache ios
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

```<code>@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}
</code>```

答: Lion thanks for the support, actually i was checking location inside the plaza and due to that i was not getting the right location, i tested by coming outside and it is showing perfectly. anyways thanks lion you have been really helpful.</p>

Body:
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}


问:
how to hide the border of text area in ui-tinymce
I want to do inline editing in ui-tinymce. Its the text area and I want to hide its border. It should edit only when user clicks on text area. I am inline as true, but still it shows border. </p>

```<code>$scope.tinymceOptions = {
        inline: true,
        menubar: false,
        toolbar: "bold italic underline styleselect",
        statusbar: false,
        skin: 'lightgray',
        theme : 'modern'
  };
</code>```

答:
Try this in your tinymceOptions :

```<code>inline_boundaries: false
</code>```

If still doesn't work you can always override the border from your css by :

```<code>.mce-container {
   border: 0px !important;
}
</code>```

Body:
I want to do inline editing in ui-tinymce. Its the text area and I want to hide its border. It should edit only when user clicks on text area. I am inline as true, but still it shows border.

$scope.tinymceOptions = {
        inline: true,
        menubar: false,
        toolbar: "bold italic underline styleselect",
        statusbar: false,
        skin: 'lightgray',
        theme : 'modern'
  };

Body:
Try this in your tinymceOptions :

inline_boundaries: false

If still doesn't work you can always override the border from your css by :

.mce-container {
   border: 0px !important;
}


问:
JGoodies Binding bug question about bufferedModels and keyboard input
I am using JGoodies Binding on a JTextField like so:

```<code>    trigger = new Trigger();

    PresentationModel<SpectralControlsModel> adapter = new PresentationModel<SpectralControlsModel>(model, trigger);

    ValueModel valueModelStartingSampleJTextField = adapter.getBufferedModel("startingSample");
    startingSampleJTextField = BasicComponentFactory.createLongField(valueModelStartingSampleJTextField);
    setupValueModelListener(valueModelStartingSampleJTextField, startingSampleJTextField);
</code>```

I have a keyListener on the JTextField that commits data to the model when the "enter" key is pushed.

The problem is when I enter in a new number in the JTextField and hit enter, the model gets the old value, even though I call trigger.triggerCommit(). If I enter a new number and then click something else, lose focus on the JTextField, and then gain focus again, then the new value ends up in the model as expected.

Let me know if I described the problem clearly enough, it is very strange behaviour and I need to get to the bottom of it, thanks.

UPDATE
I went to this Java2s.com JGoodies Example and added this code:

```<code>firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });
</code>```

When I hit the enter button with degbugging on, the actionListener fires just like it would if I hit Commit Buffer Button, but nothing is committed when I display the values. I am very puzzled by this. There has to be a way to get JGoodies working with keyboard input. I shouldn't have to click out of the JTextField for the text to get to the Value Model.

答:
Sorry about this question, I didn't explain it very clearly. Here is the answer though:

I looked through the JGoodies API (should have done this sooner) and found an unexpected static call, Bindings.commitImmediately()

If I call this method before my call to trigger.triggerCommit(), everything works as expected :)

Body:
I am using JGoodies Binding on a JTextField like so:

    trigger = new Trigger();

    PresentationModel<SpectralControlsModel> adapter = new PresentationModel<SpectralControlsModel>(model, trigger);

    ValueModel valueModelStartingSampleJTextField = adapter.getBufferedModel("startingSample");
    startingSampleJTextField = BasicComponentFactory.createLongField(valueModelStartingSampleJTextField);
    setupValueModelListener(valueModelStartingSampleJTextField, startingSampleJTextField);

I have a keyListener on the JTextField that commits data to the model when the "enter" key is pushed.

The problem is when I enter in a new number in the JTextField and hit enter, the model gets the old value, even though I call trigger.triggerCommit(). If I enter a new number and then click something else, lose focus on the JTextField, and then gain focus again, then the new value ends up in the model as expected.

Let me know if I described the problem clearly enough, it is very strange behaviour and I need to get to the bottom of it, thanks.

UPDATE
I went to this Java2s.com JGoodies Example and added this code:

firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });

When I hit the enter button with degbugging on, the actionListener fires just like it would if I hit Commit Buffer Button, but nothing is committed when I display the values. I am very puzzled by this. There has to be a way to get JGoodies working with keyboard input. I shouldn't have to click out of the JTextField for the text to get to the Value Model.


问:
WiX Setup project programmenu shortcut without uninstall option
I have set up a wix set up project that produces my application's msi installer. I have created a desktop shortcut and a program menu shortcut. In order to have the program menu shortcut, I have to specify a RemoveFolder element in the shortcut component which essentially creates an uninstall shortcut with it.

My question is, is there a way to create the program menu shortcut without having the uninstall shortcut? I would like the user to uninstall from going to the add/remove programs in the Control Panel.

I can simply not add the programmenu shortcut, but then the only way to use my application is via the desktop shortcut. It would not be a good user experience if they cannot find the application through the start/program menu. Thus I want to have a program menu shortcut but without the uninstall shortcut.

Any help would be appreciated.

答:
I realise that this was a very stupid question to ask in the first place. All I had to do was remove one line of code.</p>

```<code><!-- Start Menu Shortcut-->
<DirectoryRef Id="ApplicationProgramsFolder">
    <Component Id="ApplicationShortcut" Guid="PUT-GUID-HERE">
        <Shortcut Id="ApplicationStartMenuShortcut" Name="devapp" Description="My Application" Target="[#devapp.exe]" WorkingDirectory="APPLICATIONROOTDIRECTORY" />
        <!-- Uncomment the line below to have an uninstall shortcut in the program menu. -->
        <!--<Shortcut Id="UninstallProduct" Name="Uninstall devapp" Description="Uninstalls devapp" Target="[System64Folder]msiexec.exe" Arguments="/x [ProductCode]" />-->
        <RemoveFolder Id="CleanUpShortCut" Directory="ApplicationProgramsFolder" On="uninstall" />
        <RegistryValue Root="HKCU" Key="Software\CompanyName\ApplicationName" Name="installed" Type="integer" Value="1" KeyPath="yes" />
    </Component>
</DirectoryRef>
</code>```

Body:
I realise that this was a very stupid question to ask in the first place. All I had to do was remove one line of code.

<!-- Start Menu Shortcut-->
<DirectoryRef Id="ApplicationProgramsFolder">
    <Component Id="ApplicationShortcut" Guid="PUT-GUID-HERE">
        <Shortcut Id="ApplicationStartMenuShortcut" Name="devapp" Description="My Application" Target="[#devapp.exe]" WorkingDirectory="APPLICATIONROOTDIRECTORY" />
        <!-- Uncomment the line below to have an uninstall shortcut in the program menu. -->
        <!--<Shortcut Id="UninstallProduct" Name="Uninstall devapp" Description="Uninstalls devapp" Target="[System64Folder]msiexec.exe" Arguments="/x [ProductCode]" />-->
        <RemoveFolder Id="CleanUpShortCut" Directory="ApplicationProgramsFolder" On="uninstall" />
        <RegistryValue Root="HKCU" Key="Software\CompanyName\ApplicationName" Name="installed" Type="integer" Value="1" KeyPath="yes" />
    </Component>
</DirectoryRef>


问:
Unable to use for loop against array data in Yii2
I have a variable $data in my controller. In which I am getting the following result

```<code>Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)
</code>```

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

```<code> if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();
</code>```

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

```<code>Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}```
```

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

答:
instead of the for loop, use foreach:

```<code>foreach($data as $d)
{
    print_r($d);
}
</code>```

makes sure that you always stay within bounds of the array

Body:
I have a variable $data in my controller. In which I am getting the following result

Array( [0] => 99 [1] => 100 [2] => 101 [3] => 102 [4] => 103)

Now I want to get the single entry one by one by using for loop. The main purpose of this loop is that I want to insert these values in my DB table.

 if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

       for($i=0; $i<=count($data); $i++)
        {
            print_r($data[$i]);
        }
        //print_r($data);
    }
    else{
        echo 'no data';
    }
    exit();

When i Run this one, I am getting the error

500 Internal Server Error
  PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 5'

Stack Trace

Stack trace:
#0 E:\xampp\htdocs\inventory-
web\backend\controllers\OgpheaderController.php(170): yii\base\ErrorHandler-
>handleError(8, 'Undefined offse...',
'E:\\xampp\\htdocs...', 170, Array)
#1 [internal function]: backend\controllers\OgpheaderController-
>actionViewsetpdf('55')
#2 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\InlineAction.php(57):
call_user_func_array(Array, Array)
#3 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Controller.php(156): yii\base\InlineAction-
>runWithParams(Array)
#4 E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\base\Module.php(523):
yii\base\Controller->runAction('viewsetpdf', Array)
#5 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\web\Application.php(102): yii\base\Module-
>runAction('ogpheader/views...', Array)
#6 E:\xampp\htdocs\inventory-
web\vendor\yiisoft\yii2\base\Application.php(380): yii\web\Application-
>handleRequest(Object(yii\web\Request))
#7 E:\xampp\htdocs\inventory-web\backend\web\index.php(17):
yii\base\Application->run()
#8 {main}

I have searched for this error solution but couldn't find the correct answer(s).

Any help would be highly appreciated.

Body:
instead of the for loop, use foreach:

foreach($data as $d)
{
    print_r($d);
}

makes sure that you always stay within bounds of the array


问:
How do I print the success message
How do I print the success message in this JSON code using PHP

```<code>{
    "status": 0,

     " result":{
           "status":"success"
               }

}
</code>```

答:
```<code>$result = json_decode('{
    "status": 0,

     " result":{
           "status":"success"
               }

}');

echo $result['result']['status'];
</code>```

Title: How do I print the success message

Body:
How do I print the success message in this JSON code using PHP

{
    "status": 0,

     " result":{
           "status":"success"
               }

}


问:
xinetd service calls python script (doesn't execute properly)
I read this:

You can use xinetd to add a service starting your python script. The standard input and output will be transmitted over the network on desired port, so you do not need to modify your scripts (input/raw_input and print methods will work fine).

As a result, I'm using a custom xinet service to launch script.py when a TCP connection is established to 192.168.240.37:65123.  The behavior is not as desired/expected.

/root/script.py

```<code>#! /usr/bin/python
my_name = raw_input("Enter your name: ")
print my_name
quit()
</code>```

/etc/xinetd.d/netunique-server

```<code>service netunique
{
    disable         = no
    id              = netunique-server
    type            = unlisted
    wait            = no
    socket_type     = stream
    protocol        = tcp
    user            = root
    server          = /usr/bin/python
    server_args     = /root/script.py
    port            = 65123
    flags           = IPv4 REUSE
    bind            = 192.168.240.37
}
</code>```

systemctl status xinetd

```<code>Nov 11 21:24:00 netunique.ourhome.com xinetd[2161]: xinetd Version 2.3.15 started with libwrap loadavg labeled-ne... in.
Nov 11 21:24:00 netunique.ourhome.com xinetd[2161]: Started working: 1 available service
</code>```

telnet 192.168.240.37 65123 (expected behavior)

```<code>[root@netunique xinetd.d]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
Enter your name: John Smith          <-- I type name after prompt here
John Smith                           <-- Script prints entry back to screen
Connection closed by foreign host.   <-- Script does its quit()
</code>```

telnet 192.168.240.37 65123 (actual behavior)

```<code>[root@netunique xinetd.d]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
<blank>                              <-- no prompt as expected
John Smith                           <-- I enter some data and hit Enter
Enter your name: John Smith          <-- Hard to tell exactly what happened here
Connection closed by foreign host.   <-- Hard to tell exactly what happened here
[root@netunique xinetd.d]#
</code>```

When I say 'hard to tell exactly what happened here', I mean it's hard to tell if in the above output the 'John Smith' which shows up after the 'Enter your name: ' prompt is a result of the print statement and hard to tell if the 'Connection closed by foreign host' is a result of the quit() statement.

nc 192.168.240.37 65123 (actual behavior)

```<code>[root@netunique xinetd.d]# nc 192.168.240.37 65123
<blank>                              <-- no prompt as expected
John Smith                           <-- I enter some data and hit Enter
Enter your name: John Smith          <-- Hard to tell exactly what happened here
                                     <-- Nothing happened here, I hit Enter
                                     <-- I hit Enter again
Ncat: Broken pipe.                   <-- This is the end result
</code>```

As you can see I get very similar behavior with netcat.

答:
The real problem for me is apparently my lack of socket programming knowledge.  I found this post online searching for "xinetd python no data" (https://mail.python.org/pipermail/python-list/2007-July/423659.html) which helped me at least get my stuff working and sort of illustrated via example a bit about how socket programming actually works.  The solution is below, I removed the raw_input from the original script and replaced it with concepts from the post.

/root/script.py (original)

```<code>#! /usr/bin/python
my_name = raw_input("Enter your name: ")
print my_name
quit()
</code>```

/root/script.py (modified & working)

```<code>#! /usr/bin/python
import sys
print "Enter your name:"
sys.stdout.flush()
my_name = sys.stdin.readline().strip()
print "Your name is %s" % my_name
sys.stdout.flush()
quit()
</code>```

telnet 192.168.240.37 65123 (actual behavior - working)

```<code>[root@netunique ~]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
Enter your name:
Bob Smith
Your name is Bob Smith
Connection closed by foreign host.
</code>```

Body:
I read this:

You can use xinetd to add a service starting your python script. The standard input and output will be transmitted over the network on desired port, so you do not need to modify your scripts (input/raw_input and print methods will work fine).

As a result, I'm using a custom xinet service to launch script.py when a TCP connection is established to 192.168.240.37:65123.  The behavior is not as desired/expected.

/root/script.py

#! /usr/bin/python
my_name = raw_input("Enter your name: ")
print my_name
quit()

/etc/xinetd.d/netunique-server

service netunique
{
    disable         = no
    id              = netunique-server
    type            = unlisted
    wait            = no
    socket_type     = stream
    protocol        = tcp
    user            = root
    server          = /usr/bin/python
    server_args     = /root/script.py
    port            = 65123
    flags           = IPv4 REUSE
    bind            = 192.168.240.37
}

systemctl status xinetd

Nov 11 21:24:00 netunique.ourhome.com xinetd[2161]: xinetd Version 2.3.15 started with libwrap loadavg labeled-ne... in.
Nov 11 21:24:00 netunique.ourhome.com xinetd[2161]: Started working: 1 available service

telnet 192.168.240.37 65123 (expected behavior)

[root@netunique xinetd.d]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
Enter your name: John Smith          <-- I type name after prompt here
John Smith                           <-- Script prints entry back to screen
Connection closed by foreign host.   <-- Script does its quit()

telnet 192.168.240.37 65123 (actual behavior)

[root@netunique xinetd.d]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
<blank>                              <-- no prompt as expected
John Smith                           <-- I enter some data and hit Enter
Enter your name: John Smith          <-- Hard to tell exactly what happened here
Connection closed by foreign host.   <-- Hard to tell exactly what happened here
[root@netunique xinetd.d]#

When I say 'hard to tell exactly what happened here', I mean it's hard to tell if in the above output the 'John Smith' which shows up after the 'Enter your name: ' prompt is a result of the print statement and hard to tell if the 'Connection closed by foreign host' is a result of the quit() statement.

nc 192.168.240.37 65123 (actual behavior)

[root@netunique xinetd.d]# nc 192.168.240.37 65123
<blank>                              <-- no prompt as expected
John Smith                           <-- I enter some data and hit Enter
Enter your name: John Smith          <-- Hard to tell exactly what happened here
                                     <-- Nothing happened here, I hit Enter
                                     <-- I hit Enter again
Ncat: Broken pipe.                   <-- This is the end result

As you can see I get very similar behavior with netcat.

Body:
The real problem for me is apparently my lack of socket programming knowledge.  I found this post online searching for "xinetd python no data" (https://mail.python.org/pipermail/python-list/2007-July/423659.html) which helped me at least get my stuff working and sort of illustrated via example a bit about how socket programming actually works.  The solution is below, I removed the raw_input from the original script and replaced it with concepts from the post.

/root/script.py (original)

#! /usr/bin/python
my_name = raw_input("Enter your name: ")
print my_name
quit()

/root/script.py (modified & working)

#! /usr/bin/python
import sys
print "Enter your name:"
sys.stdout.flush()
my_name = sys.stdin.readline().strip()
print "Your name is %s" % my_name
sys.stdout.flush()
quit()

telnet 192.168.240.37 65123 (actual behavior - working)

[root@netunique ~]# telnet 192.168.240.37 65123
Trying 192.168.240.37...
Connected to 192.168.240.37.
Escape character is '^]'.
Enter your name:
Bob Smith
Your name is Bob Smith
Connection closed by foreign host.


问:
Weight scaler in android
When we take input from the user we normally use the edit text view in android. How to make weight scaler in which the user can select his weight as shown in the figure?

答: It's a quite complicated task, you will have to draw a custom view (a circle combined with an arc, draw the arc over the circle). Draw ticks on the circle every 1° (from 1° to 360°). This repository may help you: https://github.com/ngallazzi/MeterView</p>

Title: Weight scaler in android


答:
malloc() only allocates the memory, it does not zero it. You get whatever was in the memory before (e.g. random noise, or whatever the process that held the memory previously left in there when free()ing the memory -- which could be a safety issue if handling encryption keys and data).

If you need zeroed memory, use calloc().

Title: c malloc, why has my array random numbers in it?

Body:
i need to malloc an array with 1000 zeros but when I print it something weird happen

int MAX = 1000;
int *count_array
count_array = (int *) malloc(MAX * sizeof(int));
printf("success?\n");
print_array(count_array,MAX);

but the RETURN looks like:

 0 0 0 0 -1973472672 32766 134609 0 857747513 842276920 540291872 540024888 824194871 540293152 892477493 540161824 874525748 809050162 540227104 668466 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134081 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 133633 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

I really need to get rid of the other numbers, why they are in this array? did I used Malloc wrong?

best regards, Tim4497


问:
Extending an Angular 5 component using metadata
When my project was using Angular 2 and Angular 4, I was able to use this useful decorator for making a component extend another component:

```<code>// Modified from https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.s9pf0649f
// by Thierry Templier.

import { Component } from '@angular/core';

export function ComponentExtender(annotation: any): ((target: Function) => void) {
  return function(target: Function): void {
    let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    let parentAnnotations = Reflect.getMetadata('annotations', parentTarget); // TODO: Doesn't work in Angular 5, returns undefined.
    let parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
      if (parentAnnotation[key]) {
        if (!annotation[key]) {
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    let metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  };
}
</code>```

With this you could create a component class that extended an another component class, using @ComponentExtender instead of @Component, and inherit things from the superclass like the template and style if those things did not need to be changes in the subclass component.

This no longer works now that I've moved my project to Angular 5. The annotations metadata is undefined.

Does this perhaps have something to do with AOT compilation (even though I haven't selected that option)? Can anyone think of a way to revive what this decorator used to do for Angular 2 and Angular 4?

答:
You can get the annotation via target['__annotations__'][0].

There is also '__paramaters__' and '__prop__metadata__', see source of decorators.ts

Note: According to the Angular Blog, the build optimzer now is used by default for production builds, so the annotations will not be available at runtime.

Disclaimer: This is hacky and an implementation detail, so it should never be used in production code!

Body:
When my project was using Angular 2 and Angular 4, I was able to use this useful decorator for making a component extend another component:

// Modified from https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.s9pf0649f
// by Thierry Templier.

import { Component } from '@angular/core';

export function ComponentExtender(annotation: any): ((target: Function) => void) {
  return function(target: Function): void {
    let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    let parentAnnotations = Reflect.getMetadata('annotations', parentTarget); // TODO: Doesn't work in Angular 5, returns undefined.
    let parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
      if (parentAnnotation[key]) {
        if (!annotation[key]) {
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    let metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  };
}

With this you could create a component class that extended an another component class, using @ComponentExtender instead of @Component, and inherit things from the superclass like the template and style if those things did not need to be changes in the subclass component.

This no longer works now that I've moved my project to Angular 5. The annotations metadata is undefined.

Does this perhaps have something to do with AOT compilation (even though I haven't selected that option)? Can anyone think of a way to revive what this decorator used to do for Angular 2 and Angular 4?


问:
swift 3 removing bulk of text from textFiled
I'm working for mobile application will send pdf for selected contact, so the user will found add contact button to open table view that have all contact list. after that the user will click on done button.there is another view that have textFiled to display the contacts that user select. I need if the user start to remove name from textFiled by backspace,

to be removed the all name and remove also the id from array that will send the id's to server.
my code is

```<code>let idArray = ["1","2","3","4"]
let valueArray = ["Ahmad","ali","jean","sara"]
let StringVar = ""

//*Here I send the array to string to append "," to be showed in textFiled*
for item in valueArray {
            print("Found \(item)")
            StringVar = StringVar + item + ","
        }

textFiled?.text = StringVar
</code>```

any help please ??

答:
I did not implement such a thing before. but, I think I would have tried textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) from UITextFieldDelegate.
when a user will try to delete a character, you can remove the entire string between the two commas or from the first/last comma to the start/end of the string

Body:
I'm working for mobile application will send pdf for selected contact, so the user will found add contact button to open table view that have all contact list. after that the user will click on done button.there is another view that have textFiled to display the contacts that user select. I need if the user start to remove name from textFiled by backspace,

to be removed the all name and remove also the id from array that will send the id's to server.
my code is

let idArray = ["1","2","3","4"]
let valueArray = ["Ahmad","ali","jean","sara"]
let StringVar = ""

//*Here I send the array to string to append "," to be showed in textFiled*
for item in valueArray {
            print("Found \(item)")
            StringVar = StringVar + item + ","
        }

textFiled?.text = StringVar

any help please ??


问:
How to sort rows of dataframe in pyspark
I have a dataframe with two columns which contain numbers and i need to sort the dataframe row wise and not column wise. Everywhere it is given how to sort a dataframe by column but nowhere I can find how to sort all the rows of dataframe in pyspark

```<code>col1    col2

2        1

3        2
</code>```

Expected output

```<code>col1   col2

1       2

2       3
</code>```

答:
You may need some workaround to produce your desired result.

Here is an example to sort data based on a row.

From your dataframe, you may need create an index first.

```<code>df = spark.createDataFrame([['index1',3,2,1], ['index2',2,1,3]], ['index', 'a', 'b', 'c'])
columns = [i for i in df.columns if i != 'index']
df.show()
</code>```

```<code>def sort_row_df(row_to_sort):
    row_data = df.filter(col('index')==row_to_sort).collect()[0]

    sorted_row = sorted([[row_data[col_], col_] for col_ in columns])

    rearrange_col = [i[1] for i in sorted_row]

    return df.select("index", *rearrange_col)
</code>```

Lets say you wish to sort based on row 'index1',

```<code>row_to_sort = 'index1'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()
</code>```

To sort based on row 'index2',

```<code>row_to_sort = 'index2'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()
</code>```

If you want to sort all data based on rows, i would suggest you just to transpose all the data, sorts it, and transpose it back again. You may refer on how to transpose df in pyspark.

Body:
I have a dataframe with two columns which contain numbers and i need to sort the dataframe row wise and not column wise. Everywhere it is given how to sort a dataframe by column but nowhere I can find how to sort all the rows of dataframe in pyspark

col1    col2

2        1

3        2

Expected output

col1   col2

1       2

2       3

Body:
You may need some workaround to produce your desired result.

Here is an example to sort data based on a row.

From your dataframe, you may need create an index first.

df = spark.createDataFrame([['index1',3,2,1], ['index2',2,1,3]], ['index', 'a', 'b', 'c'])
columns = [i for i in df.columns if i != 'index']
df.show()

def sort_row_df(row_to_sort):
    row_data = df.filter(col('index')==row_to_sort).collect()[0]

    sorted_row = sorted([[row_data[col_], col_] for col_ in columns])

    rearrange_col = [i[1] for i in sorted_row]

    return df.select("index", *rearrange_col)

Lets say you wish to sort based on row 'index1',

row_to_sort = 'index1'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()

To sort based on row 'index2',

row_to_sort = 'index2'
sorted_df = sort_row_df(row_to_sort)
sorted_df.show()

If you want to sort all data based on rows, i would suggest you just to transpose all the data, sorts it, and transpose it back again. You may refer on how to transpose df in pyspark.


问:
Griddle v1 onRowClick not firing
Was tasked to upgrade from Griddle v0.7 to Griddle v1.1. But I can't seeme to get onRowClick to work.

```<code>import React, { Component } from 'react';
import Griddle from 'griddle-react';

export default class Table extends Component {
  render() {
    const data = [...something];

    return <Griddle
      data={data}
      onRowClick={() => console.log("row clicked")} />
  }
}
</code>```

If I look through the issues on github or other examples, this should work just fine.

答:
The Griddle v1 way to solve this would be to define a RowEnhancer to provide an onClick, like this example:

```<code>  <Griddle
    components={{
      RowEnhancer: OriginalComponent =>
        props => (
          <OriginalComponent
            {...props}
            onClick={() => console.log(`Click Row ${props.griddleKey}`)}
            />
        ),
    }}
    ...
    />
</code>```

Title: Griddle v1 onRowClick not firing

Body:
Was tasked to upgrade from Griddle v0.7 to Griddle v1.1. But I can't seeme to get onRowClick to work.

import React, { Component } from 'react';
import Griddle from 'griddle-react';

export default class Table extends Component {
  render() {
    const data = [...something];

    return <Griddle
      data={data}
      onRowClick={() => console.log("row clicked")} />
  }
}

If I look through the issues on github or other examples, this should work just fine.

Body:
The Griddle v1 way to solve this would be to define a RowEnhancer to provide an onClick, like this example:

  <Griddle
    components={{
      RowEnhancer: OriginalComponent =>
        props => (
          <OriginalComponent
            {...props}
            onClick={() => console.log(`Click Row ${props.griddleKey}`)}
            />
        ),
    }}
    ...
    />