问:
javax validation can't find Hibernate Validator in Karaf
I've implemented some code using javax.validation and Hibernate Validator. The unit tests using validation are working fine. The build produces OSGi bundles and features, and runs in Karaf.

When I run my PaxExam integration test, I get "Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath." As far as I can tell, I AM adding it to my classpath. I have a features.xml file that I've been incrementally adding dependencies to. It finally got past Karaf bundle resolution, but now it's failing with an exception with this message:

"Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath."

I would include the stacktrace, but it doesn't look useful to me. Most of it is in my code, junit, and paxexam.

I'm attempting to use version 5.4.1.Final of HV. Note again that the unit tests doing validation are working fine. It took a while to get the dependencies correct to get that far (like using version "3.0.1-b08" of "javax.el".

I've seen some mentions of a "hibernate-validator-osgi-karaf-features" artifact, but I'm not sure if that's relevant. I'm attempting to use both the hibernate-validator artifact and the hibernate-validator-annotation-processor artifact.

I don't know that it's going to matter, but here's an excerpt of my POM dependencies:

```<code>        <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>
            hibernate-validator-annotation-processor
        </artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.1-b08</version>
    </dependency>
</code>```

The following is an excerpt of a "features.xml" file from a bundle that is a dependency (by feature) of the bundle containing the test class:

```<code>    <bundle start-level="100">wrap:mvn:javax.validation/validation-api/1.1.0.Final$Bundle-Name=javax.validation&Bundle-SymbolicName=javax.validation&Bundle-Version=1.1.0.Final</bundle>
    <bundle>mvn:org.hibernate/hibernate-validator/5.4.1.Final</bundle>
    <bundle start-level="100">wrap:mvn:org.hibernate/hibernate-validator-annotation-processor/5.4.1.Final$Bundle-Name=hibernate-validator-annotation-processor&Bundle-SymbolicName=hibernate-validator-annotation-processor&Bundle-Version=5.4.1.Final</bundle>
</code>```

What else can I do at this point?

Update:

I've made some changes according to the answer that refers to the "hibernate-validator-osgi-karaf-features" artifact, but I'm now getting a different unexpected error.

In the pom dependencies I added the following:

```<code>    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>
            hibernate-validator-osgi-karaf-features
        </artifactId>
        <version>5.4.1.Final</version>
        <type>pom</type>
    </dependency>
</code>```

In the base features.xml file that is referred to by the features.xml file in my module, I removed the annotation-processor, and added this:

```<code>    <bundle>wrap:mvn:org.hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final$Bundle-Name=hibernate-validator-osgi-karaf-features&Bundle-SymbolicName=hibernate-validator-osgi-karaf-features&Bundle-Version=5.4.1.Final</bundle>
</code>```

I tried not having the "wrap:" and everything after the "$", but the result was the same.

When I ran my test, I saw this:

```<code>Caused by: shaded.org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact org.hibernate:hibernate-validator-osgi-karaf-features:jar:5.4.1.Final in central (http://repo1.maven.org/maven2/)
at shaded.org.eclipse.aether.connector.basic.ArtifactTransportListener.transferFailed(ArtifactTransportListener.java:39)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:355)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:581)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:249)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)[7:org.ops4j.pax.url.mvn:2.4.7]
... 16 more
</code>```

It's curious that it says it can't find it in central.  I can verify the artifact is my local maven cache, because my build likely copied it there after I added the maven dependency as described above.

Update:

I'm guessing that part of my problem is that this artifact is a POM artifact, not a JAR artifact, but I don't understand how I need to reference it.

Update:

Someone on karaf-user pointed out that I need to reference it as a feature, not a bundle, so I now replaced my bundle references with the following:

```<code><feature>hibernate-validator-osgi-karaf-features</feature>
</code>```

Along with the following repository definition next to two other repository definitions:

```<code>    <repository>mvn:org.hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final/xml/features</repository>
</code>```

However, after installing the features file and then rerunning my test, it fails with this:

```<code>org.osgi.service.resolver.ResolutionException: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=usl-fraudcheck; type=karaf.feature; version="[2.5.0.SNAPSHOT,2.5.0.SNAPSHOT]"; filter:="(&(osgi.identity=usl-fraudcheck)(type=karaf.feature)(version>=2.5.0.SNAPSHOT)(version<=2.5.0.SNAPSHOT))" [caused by: Unable to resolve usl-fraudcheck/2.5.0.SNAPSHOT: missing requirement [usl-fraudcheck/2.5.0.SNAPSHOT] osgi.identity; osgi.identity=usl-base; type=karaf.feature [caused by: Unable to resolve usl-base/2.5.0.SNAPSHOT: missing requirement [usl-base/2.5.0.SNAPSHOT] osgi.identity; osgi.identity=hibernate-validator-osgi-karaf-features; type=karaf.feature]]
</code>```

As I'm used to now, the last identity referenced here is the thing it can't find, unsurprisingly this new feature I'm referencing.

I then verified that the following file exists:

```<code>~/.m2/repository/org/hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final/hibernate-validator-osgi-karaf-features-5.4.1.Final-features.xml
</code>```

However, I found it curious that it begins with the following content:

```<code><?xml version="1.0" encoding="UTF-8"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0"
    name="hibernate-validator-osgi-features"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.4.0">
</code>```

The “name” property of the top-level features element is “hibernate-validator-osgi-features”, not “hibernate-validator-osgi-karaf-features”.  Is that a problem?

Update:

I now understand that my features file has to reference a feature named "hibernate-validator", which is defined in that "hibernate-validator-osgi-karaf-features" artifact.  That appears to have resolved my Karaf package resolution problems.  However, that simply puts me back to my original problem of:

```<code>    <bundle start-level="100">wrap:mvn:javax.validation/validation-api/1.1.0.Final$Bundle-Name=javax.validation&Bundle-SymbolicName=javax.validation&Bundle-Version=1.1.0.Final</bundle>
    <bundle>mvn:org.hibernate/hibernate-validator/5.4.1.Final</bundle>
    <bundle start-level="100">wrap:mvn:org.hibernate/hibernate-validator-annotation-processor/5.4.1.Final$Bundle-Name=hibernate-validator-annotation-processor&Bundle-SymbolicName=hibernate-validator-annotation-processor&Bundle-Version=5.4.1.Final</bundle>
</code>```0

I tried changing the "LogLevel" in my Pax Exam config from WARNING to DEBUG.  This gave me a lot more karaf debug output, but it didn't give me any significant info about why HV is not found in the classpath.

Is there some other debugging I can configure, or configuration in Pax Exam, that can help here?

答:
Just take a look at our Karaf integration tests for the 5.4 branch:

https://github.com/hibernate/hibernate-validator/tree/5.4/osgi/integrationtest

We also use Pax Exam. You should be able to make it work if you follow what we did.

BTW, I see you mention the annotation processor in your dependency for the 2nd time, it's not something you need at runtime. The annotation processor is used to check that the annotations you used make sense at compile time. You should only enable it when you build your project.

See the Maven example here: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-annotationprocessor-commandline .

Body:
I've implemented some code using javax.validation and Hibernate Validator. The unit tests using validation are working fine. The build produces OSGi bundles and features, and runs in Karaf.

When I run my PaxExam integration test, I get "Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath." As far as I can tell, I AM adding it to my classpath. I have a features.xml file that I've been incrementally adding dependencies to. It finally got past Karaf bundle resolution, but now it's failing with an exception with this message:

"Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath."

I would include the stacktrace, but it doesn't look useful to me. Most of it is in my code, junit, and paxexam.

I'm attempting to use version 5.4.1.Final of HV. Note again that the unit tests doing validation are working fine. It took a while to get the dependencies correct to get that far (like using version "3.0.1-b08" of "javax.el".

I've seen some mentions of a "hibernate-validator-osgi-karaf-features" artifact, but I'm not sure if that's relevant. I'm attempting to use both the hibernate-validator artifact and the hibernate-validator-annotation-processor artifact.

I don't know that it's going to matter, but here's an excerpt of my POM dependencies:

        <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>
            hibernate-validator-annotation-processor
        </artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.1-b08</version>
    </dependency>

The following is an excerpt of a "features.xml" file from a bundle that is a dependency (by feature) of the bundle containing the test class:

    <bundle start-level="100">wrap:mvn:javax.validation/validation-api/1.1.0.Final$Bundle-Name=javax.validation&Bundle-SymbolicName=javax.validation&Bundle-Version=1.1.0.Final</bundle>
    <bundle>mvn:org.hibernate/hibernate-validator/5.4.1.Final</bundle>
    <bundle start-level="100">wrap:mvn:org.hibernate/hibernate-validator-annotation-processor/5.4.1.Final$Bundle-Name=hibernate-validator-annotation-processor&Bundle-SymbolicName=hibernate-validator-annotation-processor&Bundle-Version=5.4.1.Final</bundle>

What else can I do at this point?

Update:

I've made some changes according to the answer that refers to the "hibernate-validator-osgi-karaf-features" artifact, but I'm now getting a different unexpected error.

In the pom dependencies I added the following:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>
            hibernate-validator-osgi-karaf-features
        </artifactId>
        <version>5.4.1.Final</version>
        <type>pom</type>
    </dependency>

In the base features.xml file that is referred to by the features.xml file in my module, I removed the annotation-processor, and added this:

    <bundle>wrap:mvn:org.hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final$Bundle-Name=hibernate-validator-osgi-karaf-features&Bundle-SymbolicName=hibernate-validator-osgi-karaf-features&Bundle-Version=5.4.1.Final</bundle>

I tried not having the "wrap:" and everything after the "$", but the result was the same.

When I ran my test, I saw this:

Caused by: shaded.org.eclipse.aether.transfer.ArtifactNotFoundException: Could not find artifact org.hibernate:hibernate-validator-osgi-karaf-features:jar:5.4.1.Final in central (http://repo1.maven.org/maven2/)
at shaded.org.eclipse.aether.connector.basic.ArtifactTransportListener.transferFailed(ArtifactTransportListener.java:39)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:355)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:581)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:249)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)[7:org.ops4j.pax.url.mvn:2.4.7]
at shaded.org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)[7:org.ops4j.pax.url.mvn:2.4.7]
... 16 more

It's curious that it says it can't find it in central.  I can verify the artifact is my local maven cache, because my build likely copied it there after I added the maven dependency as described above.

Update:

I'm guessing that part of my problem is that this artifact is a POM artifact, not a JAR artifact, but I don't understand how I need to reference it.

Update:

Someone on karaf-user pointed out that I need to reference it as a feature, not a bundle, so I now replaced my bundle references with the following:

<feature>hibernate-validator-osgi-karaf-features</feature>

Along with the following repository definition next to two other repository definitions:

    <repository>mvn:org.hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final/xml/features</repository>

However, after installing the features file and then rerunning my test, it fails with this:

org.osgi.service.resolver.ResolutionException: Unable to resolve root: missing requirement [root] osgi.identity; osgi.identity=usl-fraudcheck; type=karaf.feature; version="[2.5.0.SNAPSHOT,2.5.0.SNAPSHOT]"; filter:="(&(osgi.identity=usl-fraudcheck)(type=karaf.feature)(version>=2.5.0.SNAPSHOT)(version<=2.5.0.SNAPSHOT))" [caused by: Unable to resolve usl-fraudcheck/2.5.0.SNAPSHOT: missing requirement [usl-fraudcheck/2.5.0.SNAPSHOT] osgi.identity; osgi.identity=usl-base; type=karaf.feature [caused by: Unable to resolve usl-base/2.5.0.SNAPSHOT: missing requirement [usl-base/2.5.0.SNAPSHOT] osgi.identity; osgi.identity=hibernate-validator-osgi-karaf-features; type=karaf.feature]]

As I'm used to now, the last identity referenced here is the thing it can't find, unsurprisingly this new feature I'm referencing.

I then verified that the following file exists:

~/.m2/repository/org/hibernate/hibernate-validator-osgi-karaf-features/5.4.1.Final/hibernate-validator-osgi-karaf-features-5.4.1.Final-features.xml

However, I found it curious that it begins with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0"
    name="hibernate-validator-osgi-features"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.4.0">

The “name” property of the top-level features element is “hibernate-validator-osgi-features”, not “hibernate-validator-osgi-karaf-features”.  Is that a problem?

Update:

I now understand that my features file has to reference a feature named "hibernate-validator", which is defined in that "hibernate-validator-osgi-karaf-features" artifact.  That appears to have resolved my Karaf package resolution problems.  However, that simply puts me back to my original problem of:

Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.

I tried changing the "LogLevel" in my Pax Exam config from WARNING to DEBUG.  This gave me a lot more karaf debug output, but it didn't give me any significant info about why HV is not found in the classpath.

Is there some other debugging I can configure, or configuration in Pax Exam, that can help here?


来源: stackexchange

问:
how to find and click elements have a specific class and doesn't have a specific class?
in fact,  I wanna find elements that have a specific class and doesn't have a specific class, for example, I mean this is code.

in this code, we have toggle-like and has-like but I wanna find all of the elements that have toggle-like but doesn't have has-like

please if you can write javascript and jquery code.

```<code> <button class="widget-button toggle-like has-like fade-out no-text" aria-label="شما این نوشته را پسندیده‌اید" title="شما این نوشته را پسندیده‌اید" disabled="true">
    <i class="fa fa-heart" aria-hidden="true"></i>
</button>
</code>```

=================================

```<code>var sad = document.querySelectorAll("button:not([.has-like])");
    for (var i = 0; i < happy.length; i++) {
        sad[i].click();
    }
</code>```

答:
js:

```<code>document.querySelectorAll('button.toggle-like:not(.has-like)')
</code>```

jq:

```<code>$('button.toggle-like:not(.has-like)')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
in fact,  I wanna find elements that have a specific class and doesn't have a specific class, for example, I mean this is code.

in this code, we have toggle-like and has-like but I wanna find all of the elements that have toggle-like but doesn't have has-like

please if you can write javascript and jquery code.

 <button class="widget-button toggle-like has-like fade-out no-text" aria-label="شما این نوشته را پسندیده‌اید" title="شما این نوشته را پسندیده‌اید" disabled="true">

</button>

=================================

var sad = document.querySelectorAll("button:not([.has-like])");
    for (var i = 0; i < happy.length; i++) {
        sad[i].click();
    }

Body:
js:

document.querySelectorAll('button.toggle-like:not(.has-like)')

jq:

$('button.toggle-like:not(.has-like)')


问:
How to divide an NSIS script among developers?
I'd like to divide tasks for the development of a NSIS installer among a couple of developers.  How can I physically organize the code?  Do they have to edit and merge the single .nsi script when they check into SVN?  Is it possible to divide NSIS scripts into modular, separate files?  This would be ideal.

Thanks!

答: An obscure option that may work in some cases is to generate the NSI. I kind of half took that path.</p>

ContentLicense: CC BY-SA 2.5


问:
autocomplete using jquery shows bullet points with no values in Laravel 5.4
I am using Laravel 5.4, Ajax and Jquery to auto-complete search field. I am unable to show search result. All I get to see is the list of bullet points with no search data in it. I am not sure how to check if data is really passed to the view? I did console.log (ui) but no result on console

Below is the screenshot showing search bar with bullet points results.

jquery search code

```<code> $("#searchfield").autocomplete({
  source    : '{{ url("/admin/users/autocomplete") }}',
  minlength :1,
  autofocus : true,
  select:function (e,ui){
    console.log(ui);
    alert(ui);
  }
});
</code>```

input field code

```<code><input type="text" class="form-control" style="width:70%; display:none;" name="searchfield" id="searchfield" placeholder="Enter username..." >
</code>```

display none property in input field changes to display:block when first name is selected from drop down. that is not the issue if that thought crosses ur mind.

Updated - output from the url /admin/users/autocomplete?term=...

```<code>[{"id":6,"name":"Lulu"},{"id":14,"name":"Luis"}]
</code>```

Now I am in much better state, all I need is data to be inserted into those empty results. below are the images with update html state and screenshot of inspect element screen if it helps find bug:

答:
Jquery autocomplete expects a specificly formatted Array.
Try changing your autocomplete output to something like:

```<code>[
   {"data":6,"value":"Lulu"},
   {"data":14,"value":"Luis"}
]
</code>```

So just change the name of the object keys for every element from id, name to data, value

Body:
I am using Laravel 5.4, Ajax and Jquery to auto-complete search field. I am unable to show search result. All I get to see is the list of bullet points with no search data in it. I am not sure how to check if data is really passed to the view? I did console.log (ui) but no result on console

Below is the screenshot showing search bar with bullet points results.

jquery search code

 $("#searchfield").autocomplete({
  source    : '{{ url("/admin/users/autocomplete") }}',
  minlength :1,
  autofocus : true,
  select:function (e,ui){
    console.log(ui);
    alert(ui);
  }
});

input field code

<input type="text" class="form-control" style="width:70%; display:none;" name="searchfield" id="searchfield" placeholder="Enter username..." >

display none property in input field changes to display:block when first name is selected from drop down. that is not the issue if that thought crosses ur mind.

Updated - output from the url /admin/users/autocomplete?term=...

[{"id":6,"name":"Lulu"},{"id":14,"name":"Luis"}]

Now I am in much better state, all I need is data to be inserted into those empty results. below are the images with update html state and screenshot of inspect element screen if it helps find bug:

Body:
Jquery autocomplete expects a specificly formatted Array.
Try changing your autocomplete output to something like:

[
   {"data":6,"value":"Lulu"},
   {"data":14,"value":"Luis"}
]

So just change the name of the object keys for every element from id, name to data, value


问:
how to read FormData object in Laravel
I am trying to ajax submit form to a Laravel 5 controller method. I understand that in php, you can define a FormData object, append the input fields to the object and send it to the server where you can now extract the values using the input field names.

Like so:

```<code>var form_data = new FormData();
formdata.append('file_name', 'some_file_name_from_form.png');
</code>```

When form_data is sent as the data in the ajax call, I can get the file in PHP by using the $_FILES['file_name']['name'];.

So I tried this same logic in a Laravel controller method. I tried just to grab the name of the file in the $request object but only got null.

My controller method:

```<code>public function postImage(Request $request)
{
    $file = $request->get('file_name');

    dd($file);
}
</code>```

But when I dd the whole request, I see this weird object:

array:1 [
    "file_name" => UploadedFile {#199
      -test: false
      -originalName: "work-fitness_00255959.png"
      -mimeType: "image/png"
      -size: 34215
      -error: 0
      #hashName: null
      path: "/tmp"
      filename: "phpVodsUg"
      basename: "phpVodsUg"
      pathname: "/tmp/phpVodsUg"
      extension: ""
      realPath: "/tmp/phpVodsUg"
      aTime: 2017-06-04 12:42:26
      mTime: 2017-06-04 12:42:26
      cTime: 2017-06-04 12:42:26
      inode: 17573243
      size: 34215
      perms: 0100600
      owner: 1000
      group: 1000
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
    }
  ]

Please how do I get the image sent through FormData() object in Ajax through it's name?

Thanks for any help

答:
You can do this.

```<code>// get the `UploadedFile` object
$file = $request->file('file_name');
$file = $request->file_name;

// get the original file name
$filename = $request->file('file_name')->getClientOriginalName();
$filename = $request->file_name->getClientOriginalName();
</code>```

Check out the documentation for more information https://laravel.com/docs/5.4/requests#retrieving-uploaded-files

The api methods available on the uploaded file http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html

Title: how to read FormData object in Laravel

Body:
I am trying to ajax submit form to a Laravel 5 controller method. I understand that in php, you can define a FormData object, append the input fields to the object and send it to the server where you can now extract the values using the input field names.

Like so:

var form_data = new FormData();
formdata.append('file_name', 'some_file_name_from_form.png');

When form_data is sent as the data in the ajax call, I can get the file in PHP by using the $_FILES['file_name']['name'];.

So I tried this same logic in a Laravel controller method. I tried just to grab the name of the file in the $request object but only got null.

My controller method:

public function postImage(Request $request)
{
    $file = $request->get('file_name');

    dd($file);
}

But when I dd the whole request, I see this weird object:

array:1 [
    "file_name" => UploadedFile {#199
      -test: false
      -originalName: "work-fitness_00255959.png"
      -mimeType: "image/png"
      -size: 34215
      -error: 0
      #hashName: null
      path: "/tmp"
      filename: "phpVodsUg"
      basename: "phpVodsUg"
      pathname: "/tmp/phpVodsUg"
      extension: ""
      realPath: "/tmp/phpVodsUg"
      aTime: 2017-06-04 12:42:26
      mTime: 2017-06-04 12:42:26
      cTime: 2017-06-04 12:42:26
      inode: 17573243
      size: 34215
      perms: 0100600
      owner: 1000
      group: 1000
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
    }
  ]

Please how do I get the image sent through FormData() object in Ajax through it's name?

Thanks for any help

Body:
You can do this.

// get the `UploadedFile` object
$file = $request->file('file_name');
$file = $request->file_name;

// get the original file name
$filename = $request->file('file_name')->getClientOriginalName();
$filename = $request->file_name->getClientOriginalName();

Check out the documentation for more information https://laravel.com/docs/5.4/requests#retrieving-uploaded-files

The api methods available on the uploaded file http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/File/UploadedFile.html


问:
Generics classes and inheritance
I have the model object:

```<code>class Animal {
// ...
}
</code>```

And subclasses:

```<code>class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}
</code>```

Also I've created the generic class

```<code>class AnimalController<T: Animal> {
      var animal: T?
      func feed(animal: T) {
          let food = Food(T.self)
          animal.feed(food)
      }
}
</code>```

Here it's the issue:

```<code>class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Error

        // I want control a cat
        self.controller = AnimalController<Cat>()  // Error
    }
}
</code>```

How could I create generic class compatible with dogs and cats? Thanks!

UPDATED Hamish give me the solution linking other two posts.

I have the model object:

```<code>class Animal {
// ...
}
</code>```

And subclasses:

```<code>class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}
</code>```

Also I've created the generic class

```<code>class AnimalController<T> {
    var type: T

    init(type: T) {
        self.type = type
    }

    func feed() {
        if type is Animal.Type {
            let food = Food(type as! Animal.Type)
            animal.feed(food)
        }
    }
}
</code>```

Now it works:

```<code>class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Works!
        self.controller = AnimalController<Cat>()  // Works!
    }
}
</code>```

答: Swift is a strong type language. You have already declared your property controller, and you can't change its type, but that's entirely okay, because of Swift supports a generalization-paradigm, that allows you to save objects in a property with a common superclass.

Title: Generics classes and inheritance

Body:
I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T: Animal> {
      var animal: T?
      func feed(animal: T) {
          let food = Food(T.self)
          animal.feed(food)
      }
}

Here it's the issue:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Error

        // I want control a cat
        self.controller = AnimalController<Cat>()  // Error
    }
}

How could I create generic class compatible with dogs and cats? Thanks!

UPDATED Hamish give me the solution linking other two posts.

I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T> {
    var type: T

    init(type: T) {
        self.type = type
    }

    func feed() {
        if type is Animal.Type {
            let food = Food(type as! Animal.Type)
            animal.feed(food)
        }
    }
}

Now it works:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Works!
        self.controller = AnimalController<Cat>()  // Works!
    }
}


问:
jQuery: on checked checkbox append form
Hi Everyone I use a check box to load form if checked I want load form else remove form the bellow is my code </p>

```<code> $('.checkbox-primary').change(function () {
        $url = $('.form-edit').attr('action');
        $form = $('.form-edit').serialize();
        $.post($url, $form ,function ($data) {

            var x=document.getElementById("filebox_edit_hardcopylocation_warehouse");
            var warehouse=document.getElementById("filebox_edit_hardcopylocation_warehouse");
            if(x){
                $('.panel-footer').removeChild(warehouse);
                alert("yes");
            }
            else
            {
                $('.form-edit').append('<div class="form-group"> <label class="col-md-3 col-xs-12 control-label">WareHouse: </label> <div class="col-md-6 col-xs-12"> <select id="filebox_edit_hardcopylocation_warehouse" name="filebox_edit[hardcopylocation][warehouse]" class="form-control"><option value="">Please Select Warehouse</option><option value="6">HQ4</option><option value="7">KTC</option></select> </div> </div> <select id="filebox_edit_hardcopylocation_floor" name="filebox_edit[hardcopylocation][floor]" class="form-control"><option value="">Please Select Floor</option><option value="1">first floor</option><option value="2">second floor</option><option value="3">second floor</option><option value="4">first floor</option></select><select id="filebox_edit_hardcopylocation_room" name="filebox_edit[hardcopylocation][room]" class="form-control"><option value="">Please Select Room</option><option value="9">R122</option><option value="10">R2</option></select><select id="filebox_edit_hardcopylocation_rack" name="filebox_edit[hardcopylocation][rack]" class="form-control"><option value="">Please Select Rack</option><option value="15">RA3456</option><option value="16">RA1</option><option value="17">RA2</option><option value="18">RA39</option></select>')

            }

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

答:
Using JQuery, you can check:</p>

```<code>$('.checkbox-primary').change(function () {
    $(this).is(":checked") {
          // checkbox is checked
    } else {
          // It is unchecked
    }
}
</code>```

Title: jQuery: on checked checkbox append form

Body:
Hi Everyone I use a check box to load form if checked I want load form else remove form the bellow is my code

 $('.checkbox-primary').change(function () {
        $url = $('.form-edit').attr('action');
        $form = $('.form-edit').serialize();
        $.post($url, $form ,function ($data) {

            var x=document.getElementById("filebox_edit_hardcopylocation_warehouse");
            var warehouse=document.getElementById("filebox_edit_hardcopylocation_warehouse");
            if(x){
                $('.panel-footer').removeChild(warehouse);
                alert("yes");
            }
            else
            {
                $('.form-edit').append('
 WareHouse:
 <select id="filebox_edit_hardcopylocation_warehouse" name="filebox_edit[hardcopylocation][warehouse]" class="form-control"><option value="">Please Select Warehouse</option><option value="6">HQ4</option><option value="7">KTC</option></select>

 <select id="filebox_edit_hardcopylocation_floor" name="filebox_edit[hardcopylocation][floor]" class="form-control"><option value="">Please Select Floor</option><option value="1">first floor</option><option value="2">second floor</option><option value="3">second floor</option><option value="4">first floor</option></select><select id="filebox_edit_hardcopylocation_room" name="filebox_edit[hardcopylocation][room]" class="form-control"><option value="">Please Select Room</option><option value="9">R122</option><option value="10">R2</option></select><select id="filebox_edit_hardcopylocation_rack" name="filebox_edit[hardcopylocation][rack]" class="form-control"><option value="">Please Select Rack</option><option value="15">RA3456</option><option value="16">RA1</option><option value="17">RA2</option><option value="18">RA39</option></select>')

            }

        })
    });

Body:
Using JQuery, you can check:

$('.checkbox-primary').change(function () {
    $(this).is(":checked") {
          // checkbox is checked
    } else {
          // It is unchecked
    }
}


答:
This looks like a case where inheritance should be utilized instead of generics.

```<code>class AnimalController {
    // basic animal control tasks
}

class CatController: AnimalController {
    // specialized controller just for cats
}
class DogController: AnimalController {
    // ...
}
</code>```

Then you could just write

```<code>class MainViewController: UIViewController {
    var animalController: AnimalController

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = DogController()

        // I want control a cat
        self.controller = CatController()
    }
}
</code>```

Working with generics can lead to problems in this case as the Swift compiler resolves generic types and replaces them with concrete types (which is not possible unless you make your whole view controller generic but that would work well with interface builder)

Title: Generics classes and inheritance

Body:
This looks like a case where inheritance should be utilized instead of generics.

class AnimalController {
    // basic animal control tasks
}

class CatController: AnimalController {
    // specialized controller just for cats
}
class DogController: AnimalController {
    // ...
}

Then you could just write

class MainViewController: UIViewController {
    var animalController: AnimalController

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = DogController()

        // I want control a cat
        self.controller = CatController()
    }
}

Working with generics can lead to problems in this case as the Swift compiler resolves generic types and replaces them with concrete types (which is not possible unless you make your whole view controller generic but that would work well with interface builder)


问:
C OVERFLOW! number gets negative
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

```<code>long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}
</code>```

答:
Your main problem is that your loop steps through all of the buffer buf instead of only stepping through the '\0' terminated string it contains.

For example, if we assume buf was declared as char buf[100]; and we enter the string "3924456639" then buf will contain:

```<code>{'3','9','2','4','4','5','6','6','3','9','\n','\0', ... and 88 bytes of garbage}
</code>```

then your loop will correctly step through the digits and ignore the '\n'. But then it does not stop. Since '\0' is neither ' ' nor '\n', temp gets multiplied by ten and '\0' - '0' is added. And the same goes for every one of those 88 bytes of garbage that is neither ' ' nor '\n'.

To fix this, change:

```<code>for(int i = 0; i < sizeof buf ;i++){
</code>```

to:

```<code>for(int i = 0; i < strlen(buf) ;i++){
</code>```

or:

```<code>for(int i = 0; buf[i] != '\0' ;i++){
</code>```

(Remember to #include <string.h> if you want to use strlen().)

Note:

Your minor problem is that long might be too small for your number.

Like @KALALEX pointed out, you could use strtol().

Title: C OVERFLOW! number gets negative

Body:
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}

Body:
Your main problem is that your loop steps through all of the buffer buf instead of only stepping through the '\0' terminated string it contains.

For example, if we assume buf was declared as char buf[100]; and we enter the string "3924456639" then buf will contain:

{'3','9','2','4','4','5','6','6','3','9','\n','\0', ... and 88 bytes of garbage}

then your loop will correctly step through the digits and ignore the '\n'. But then it does not stop. Since '\0' is neither ' ' nor '\n', temp gets multiplied by ten and '\0' - '0' is added. And the same goes for every one of those 88 bytes of garbage that is neither ' ' nor '\n'.

To fix this, change:

for(int i = 0; i < sizeof buf ;i++){

to:

for(int i = 0; i < strlen(buf) ;i++){

or:

for(int i = 0; buf[i] != '\0' ;i++){

(Remember to #include <string.h> if you want to use strlen().)

Note:

Your minor problem is that long might be too small for your number.

Like @KALALEX pointed out, you could use strtol().


问:
Coldfusion Struct getting only numeric key list
I have a coldfusion Struct containing mix keys numeric and alpha, alphanumerics

I need to access only the numeric keys.

My code looks like

```<code><cfset ids = structkeyList(st ) />
<cfset numericIDs = "" />
<cfloop list="#ids#" index="i">
    <cfif IsNumeric(i)>
        <cfset numericIDs = ListAppend( numericIDs , i ) />
    </cfif>
</cfloop>
</code>```

Is there a better method to solve such problems?

答:
I had this:

```<code><cfscript> function ListNumeric(principal) {
    a=principal;
        cleanlist = '';     for (i=1; i <= ListLen(a);i=i+1) {      if(IsNumeric(ListGetAt(a,i))){  cleanlist = ListAppend(cleanlist,ListGetAt(a,i));   }   }   Return cleanlist; } </cfscript>
</code>```

Also possible to work with regular expression:

```<code>inList2 = REReplace(inList,"[^0-9.]", "","ALL");
</code>```

Body:
I have a coldfusion Struct containing mix keys numeric and alpha, alphanumerics

I need to access only the numeric keys.

My code looks like

<cfset ids = structkeyList(st ) />
<cfset numericIDs = "" />
<cfloop list="#ids#" index="i">
    <cfif IsNumeric(i)>
        <cfset numericIDs = ListAppend( numericIDs , i ) />
    </cfif>
</cfloop>

Is there a better method to solve such problems?

Body:
I had this:

<cfscript> function ListNumeric(principal) {
    a=principal;
        cleanlist = '';     for (i=1; i <= ListLen(a);i=i+1) {      if(IsNumeric(ListGetAt(a,i))){  cleanlist = ListAppend(cleanlist,ListGetAt(a,i));   }   }   Return cleanlist; } </cfscript>

Also possible to work with regular expression:

inList2 = REReplace(inList,"[^0-9.]", "","ALL");


问:
PIck randomly samples from a 2D matrix and keep the indexes in python
I have a numpy 2D matrix with data in python and I want to perform downsampling by keeping the 25% of the initial samples. In order to do so, I am using the following random.randint functionality:

```<code>reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=300), :]
</code>```

However, I am having a second matrix which contains the labels associated with the faces and I want to reduce with the same way. How, can I keep the indexes from the reduced matrix and apply them to the train_lbls matrix?

Body:
I have a numpy 2D matrix with data in python and I want to perform downsampling by keeping the 25% of the initial samples. In order to do so, I am using the following random.randint functionality:

reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=300), :]

However, I am having a second matrix which contains the labels associated with the faces and I want to reduce with the same way. How, can I keep the indexes from the reduced matrix and apply them to the train_lbls matrix?

Body:
Why don't you keep the selected index and use them to select data from both matrices?

import numpy as np

# setting up matrices
np.random.seed(1234)  # make example repeatable
                      # the seeding is optional, only for the showing the
                      # same results as below!
face_train = np.random.rand(8,3)
train_lbls= np.random.rand(8)

print('face_train:\n', face_train)
print('labels:\n', train_lbls)

# Setting the random indexes
random_idxs= np.random.randint(face_train.shape[0], size=4)
print('random_idxs:\n', random_idxs)

# Using the indexes to slice the matrixes
reduced_train_face = face_train[random_idxs, :]
reduced_labels = train_lbls[random_idxs]
print('reduced_train_face:\n', reduced_train_face)
print('reduced_labels:\n', reduced_labels)

Gives as output:

face_train:
 [[ 0.19151945  0.62210877  0.43772774]
 [ 0.78535858  0.77997581  0.27259261]
 [ 0.27646426  0.80187218  0.95813935]
 [ 0.87593263  0.35781727  0.50099513]
 [ 0.68346294  0.71270203  0.37025075]
 [ 0.56119619  0.50308317  0.01376845]
 [ 0.77282662  0.88264119  0.36488598]
 [ 0.61539618  0.07538124  0.36882401]]
labels:
 [ 0.9331401   0.65137814  0.39720258  0.78873014  0.31683612  0.56809865
  0.86912739  0.43617342]
random_idxs:
 [1 7 5 4]
reduced_train_face:
 [[ 0.78535858  0.77997581  0.27259261]
 [ 0.61539618  0.07538124  0.36882401]
 [ 0.56119619  0.50308317  0.01376845]
 [ 0.68346294  0.71270203  0.37025075]]
reduced_labels:
 [ 0.65137814  0.43617342  0.56809865  0.31683612]


问:
Mongoose encryption middleware doesn't call after aggregation
I have a mongoose's schema with a 'mongoose-encryption' plugin, for example:

```<code>let someSchema = new Schema({name, age});

someSchema.plugin(mongoose-encryption, {
        encryptionKey: 'eKey',
        signingKey: 'sKey',
        encryptedFields: ['age'],
        decryptPostSave: false
    });
</code>```

After initiating the model and the repository I tried to aggregate some query:

```<code>let aggregation = []; // just return all the docs.
someModel.aggregate(aggregation, (err, persons) => {
        return persons;
});
</code>```

As a result I'm still getting the age field encrypted, little reading has revealed that the 'post' method of the 'init' event isn't called after aggregation (as explained here - Mongoose Middleware Docs).

Is there a good solution? or any other workaround?

the data MUST be encrypt.

the aggregation is also required (in real life - lookup to other collection)

答:
As I didn't find a better answer, I changed my code (as workaround unfortunately) to decrypt the object by myself -
using the code of mongoose-encryption to decrypt after the aggregation has finished.

Most of the code was taken from GitHub (called decryptOne in my code):
decryptSync function of mongoose-encryption

The 'tricky' thing was to decrypt the inner lookup value - the inner document also has the "_ct" field that should be decrypted.

```<code>let lookup: { [innerField: string]: string[]; } = {
                    user: ['bio']
                };
this.decryptAggregation(aggregationResult, lookup);
</code>```

My function gets a dictionary of the known lookup collection and its wanted fields after decryption. In that example, the other collection named users and its encrypted field is just his bio.

```<code>decryptAggregation(res: any[], innerLookup: { [innerField: string]: string[]; }) {
    for (let doc of res) {
        this.decryptSync(doc, innerLookup);
    }
}

private decryptSync(doc: any, innerLookup: { [innerField: string]: string[]; }) {
    this.decryptOne(doc, this.encryptedFields);
    for (let innerObj in innerLookup) {
        if (innerLookup.hasOwnProperty(innerObj)) {
            this.decryptOne(doc[innerObj], innerLookup[innerObj]);
        }
    }
};

private decryptOne(doc: any, fields: string[]) {
    let ct, ctWithIV, decipher, iv, idString, decryptedObject, decryptedObjectJSON, decipheredVal;

    if (doc._ct) {
        ctWithIV = doc._ct.hasOwnProperty('buffer') ? doc._ct.buffer : doc._ct;
        iv = ctWithIV.slice(this.VERSION_LENGTH, this.VERSION_LENGTH + this.IV_LENGTH);
        ct = ctWithIV.slice(this.VERSION_LENGTH + this.IV_LENGTH, ctWithIV.length);

        decipher = crypto.createDecipheriv(this.ENCRYPTION_ALGORITHM, this.encryptionKey, iv);
        try {
            decryptedObjectJSON = decipher.update(ct, undefined, 'utf8') + decipher.final('utf8');
            decryptedObject = JSON.parse(decryptedObjectJSON);
        } catch (err) {
            if (doc._id) {
                idString = doc._id.toString();
            } else {
                idString = 'unknown';
            }
            throw new Error('Error parsing JSON during decrypt of ' + idString + ': ' + err);
        }

        fields.forEach((field) => {
            decipheredVal = mpath.get(field, decryptedObject);

            //JSON.parse returns {type: "Buffer", data: Buffer} for Buffers
            //https://nodejs.org/api/buffer.html#buffer_buf_tojson
            if (_.isObject(decipheredVal) && decipheredVal.type === "Buffer") {
                this.setFieldValue(doc, field, decipheredVal.data);
            } else {
                this.setFieldValue(doc, field, decipheredVal);
            }
        });

        doc._ct = undefined;
        doc._ac = undefined;
    }
}
</code>```

After those function I got my wanted object fully decrypted, the last thing to do was to project the wanted fields back to the client - with lodash.pick

Body:
I have a mongoose's schema with a 'mongoose-encryption' plugin, for example:

let someSchema = new Schema({name, age});

someSchema.plugin(mongoose-encryption, {
        encryptionKey: 'eKey',
        signingKey: 'sKey',
        encryptedFields: ['age'],
        decryptPostSave: false
    });

After initiating the model and the repository I tried to aggregate some query:

let aggregation = []; // just return all the docs.
someModel.aggregate(aggregation, (err, persons) => {
        return persons;
});

As a result I'm still getting the age field encrypted, little reading has revealed that the 'post' method of the 'init' event isn't called after aggregation (as explained here - Mongoose Middleware Docs).

Is there a good solution? or any other workaround?

the data MUST be encrypt.

the aggregation is also required (in real life - lookup to other collection)

Body:
As I didn't find a better answer, I changed my code (as workaround unfortunately) to decrypt the object by myself -
using the code of mongoose-encryption to decrypt after the aggregation has finished.

Most of the code was taken from GitHub (called decryptOne in my code):
decryptSync function of mongoose-encryption

The 'tricky' thing was to decrypt the inner lookup value - the inner document also has the "_ct" field that should be decrypted.

let lookup: { [innerField: string]: string[]; } = {
                    user: ['bio']
                };
this.decryptAggregation(aggregationResult, lookup);

My function gets a dictionary of the known lookup collection and its wanted fields after decryption. In that example, the other collection named users and its encrypted field is just his bio.

decryptAggregation(res: any[], innerLookup: { [innerField: string]: string[]; }) {
    for (let doc of res) {
        this.decryptSync(doc, innerLookup);
    }
}

private decryptSync(doc: any, innerLookup: { [innerField: string]: string[]; }) {
    this.decryptOne(doc, this.encryptedFields);
    for (let innerObj in innerLookup) {
        if (innerLookup.hasOwnProperty(innerObj)) {
            this.decryptOne(doc[innerObj], innerLookup[innerObj]);
        }
    }
};

private decryptOne(doc: any, fields: string[]) {
    let ct, ctWithIV, decipher, iv, idString, decryptedObject, decryptedObjectJSON, decipheredVal;

    if (doc._ct) {
        ctWithIV = doc._ct.hasOwnProperty('buffer') ? doc._ct.buffer : doc._ct;
        iv = ctWithIV.slice(this.VERSION_LENGTH, this.VERSION_LENGTH + this.IV_LENGTH);
        ct = ctWithIV.slice(this.VERSION_LENGTH + this.IV_LENGTH, ctWithIV.length);

        decipher = crypto.createDecipheriv(this.ENCRYPTION_ALGORITHM, this.encryptionKey, iv);
        try {
            decryptedObjectJSON = decipher.update(ct, undefined, 'utf8') + decipher.final('utf8');
            decryptedObject = JSON.parse(decryptedObjectJSON);
        } catch (err) {
            if (doc._id) {
                idString = doc._id.toString();
            } else {
                idString = 'unknown';
            }
            throw new Error('Error parsing JSON during decrypt of ' + idString + ': ' + err);
        }

        fields.forEach((field) => {
            decipheredVal = mpath.get(field, decryptedObject);

            //JSON.parse returns {type: "Buffer", data: Buffer} for Buffers
            //https://nodejs.org/api/buffer.html#buffer_buf_tojson
            if (_.isObject(decipheredVal) && decipheredVal.type === "Buffer") {
                this.setFieldValue(doc, field, decipheredVal.data);
            } else {
                this.setFieldValue(doc, field, decipheredVal);
            }
        });

        doc._ct = undefined;
        doc._ac = undefined;
    }
}

After those function I got my wanted object fully decrypted, the last thing to do was to project the wanted fields back to the client - with lodash.pick


答:
You can fix the seed just before applying your extraction:

```<code>import numpy as np

# Each labels correspond to the first element of each line of face_train
labels_train =  np.array(range(0,15,3))
face_train = np.array(range(15)).reshape(5,3)
np.random.seed(0)
reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=3), :]
np.random.seed(0)
reduced_train_labels = labels_train[np.random.randint(labels_train.shape[0], size=3)]

print(reduced_train_face, reduced_train_labels)
# [[12, 13, 14], [ 0,  1,  2], [ 9, 10, 11]], [12,  0,  9]
</code>```

With the same seed, it will be reduce the same way.

edit: I advice you to use np.random.choice(n_total_elem, n_reduce_elem) in order to ensure that you only choose each data once and not twice the same data

Title: PIck randomly samples from a 2D matrix and keep the indexes in python

Body:
You can fix the seed just before applying your extraction:

import numpy as np

# Each labels correspond to the first element of each line of face_train
labels_train =  np.array(range(0,15,3))
face_train = np.array(range(15)).reshape(5,3)
np.random.seed(0)
reduced_train_face = face_train[np.random.randint(face_train.shape[0], size=3), :]
np.random.seed(0)
reduced_train_labels = labels_train[np.random.randint(labels_train.shape[0], size=3)]

print(reduced_train_face, reduced_train_labels)
# [[12, 13, 14], [ 0,  1,  2], [ 9, 10, 11]], [12,  0,  9]

With the same seed, it will be reduce the same way.

edit: I advice you to use np.random.choice(n_total_elem, n_reduce_elem) in order to ensure that you only choose each data once and not twice the same data


问:
Memory leak with TensorFlow
I have a memory leak with TensorFlow. I refered to Tensorflow : Memory leak even while closing Session? to address my issue, and I followed the advices of the answer, that seemed to have solved the problem. However it does not work here.

In order to recreate the memory leak, I have created a simple example. First, I use this function (that I got here : How to get current CPU and RAM usage in Python?) to check the memory use of the python process :

```<code>def memory():
    import os
    import psutil
    pid = os.getpid()
    py = psutil.Process(pid)
    memoryUse = py.memory_info()[0]/2.**30  # memory use in GB...I think
    print('memory use:', memoryUse)
</code>```

Then, everytime I call the build_model function, the use of memory increases.

Here is the build_model function that has a memory leak :

```<code>def build_model():

    '''Model'''

    tf.reset_default_graph()

    with tf.Graph().as_default(), tf.Session() as sess:
        tf.contrib.keras.backend.set_session(sess)

        labels = tf.placeholder(tf.float32, shape=(None, 1))
        input = tf.placeholder(tf.float32, shape=(None, 1))

        x = tf.contrib.keras.layers.Dense(30, activation='relu', name='dense1')(input)
        x1 = tf.contrib.keras.layers.Dropout(0.5)(x)
        x2 = tf.contrib.keras.layers.Dense(30, activation='relu', name='dense2')(x1)
        y = tf.contrib.keras.layers.Dense(1, activation='sigmoid', name='dense3')(x2)

        loss = tf.reduce_mean(tf.contrib.keras.losses.binary_crossentropy(labels, y))

        train_step = tf.train.AdamOptimizer(0.004).minimize(loss)

        #Initialize all variables
        init_op = tf.global_variables_initializer()
        sess.run(init_op)

        sess.close()

    tf.reset_default_graph()

    return
</code>```

I would have thought that using the block with tf.Graph().as_default(), tf.Session() as sess: and then closing the session and calling tf.reset_default_graph would clear all the memory used by TensorFlow. Apparently it does not.

The memory leak can be recreated as following :

```<code>memory()
build_model()
memory()
build_model()
memory()
</code>```

The output of this is (for my computer) :

```<code>memory use: 0.1794891357421875
memory use: 0.184417724609375
memory use: 0.18923568725585938
</code>```

Clearly we can see that all the memory used by TensorFlow is not freed afterwards. Why?

I plotted the use of memory over 100 iterations of calling build_model, and this is what I get :

I think that goes to show that there is a memory leak.

答:
Normally what happened is we use the loop outside of a session. I think here what is happening is at each time you add more and more memory chunks when running this init_op = tf.global_variables_initializer().
Because if the loop is outside the session it will only get initialized for once.
What happen hear is it's always get initialized and keep that in the memory.

Editing the answer since still you have the memory issue

The possibly it's the graph. Because each time you will create a graph which will hold the memory.Try to remove it and run. By removing it will take your all operations as the default graph. I think you need some kind of memory flush function outside the tensorflow. because each time when you run this it will stack up a graph.

Title: Memory leak with TensorFlow

Body:
I have a memory leak with TensorFlow. I refered to Tensorflow : Memory leak even while closing Session? to address my issue, and I followed the advices of the answer, that seemed to have solved the problem. However it does not work here.

In order to recreate the memory leak, I have created a simple example. First, I use this function (that I got here : How to get current CPU and RAM usage in Python?) to check the memory use of the python process :

def memory():
    import os
    import psutil
    pid = os.getpid()
    py = psutil.Process(pid)
    memoryUse = py.memory_info()[0]/2.**30  # memory use in GB...I think
    print('memory use:', memoryUse)

Then, everytime I call the build_model function, the use of memory increases.

Here is the build_model function that has a memory leak :

def build_model():

    '''Model'''

    tf.reset_default_graph()

    with tf.Graph().as_default(), tf.Session() as sess:
        tf.contrib.keras.backend.set_session(sess)

        labels = tf.placeholder(tf.float32, shape=(None, 1))
        input = tf.placeholder(tf.float32, shape=(None, 1))

        x = tf.contrib.keras.layers.Dense(30, activation='relu', name='dense1')(input)
        x1 = tf.contrib.keras.layers.Dropout(0.5)(x)
        x2 = tf.contrib.keras.layers.Dense(30, activation='relu', name='dense2')(x1)
        y = tf.contrib.keras.layers.Dense(1, activation='sigmoid', name='dense3')(x2)

        loss = tf.reduce_mean(tf.contrib.keras.losses.binary_crossentropy(labels, y))

        train_step = tf.train.AdamOptimizer(0.004).minimize(loss)

        #Initialize all variables
        init_op = tf.global_variables_initializer()
        sess.run(init_op)

        sess.close()

    tf.reset_default_graph()

    return

I would have thought that using the block with tf.Graph().as_default(), tf.Session() as sess: and then closing the session and calling tf.reset_default_graph would clear all the memory used by TensorFlow. Apparently it does not.

The memory leak can be recreated as following :

memory()
build_model()
memory()
build_model()
memory()

The output of this is (for my computer) :

memory use: 0.1794891357421875
memory use: 0.184417724609375
memory use: 0.18923568725585938

Clearly we can see that all the memory used by TensorFlow is not freed afterwards. Why?

I plotted the use of memory over 100 iterations of calling build_model, and this is what I get :

I think that goes to show that there is a memory leak.


问:
Docker NGINX setup to run Django project is giving invalid port specification error
I am trying to setup Docker for my django project. I believe everything is setup to run docker in my machine. Currently, the docker version gives following output:

```<code>Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.2.1
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64
Server version: 17.05.0-ce
Server API version: 1.29
Go version (server): go1.7.5
Git commit (server): 89658be
OS/Arch (server): linux/amd64
</code>```

I have setup my docker-compose.yml file as follows:

```<code>version: '3'
services:
  nginx:
    restart: always
    image: nginx:latest
    container_name: NGINX
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static
    depends_on:
      - web
  web:
    restart: always
    build: .
    container_name: DJANGO
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"

  db:
    restart: always
    image: postgres:latest
    container_name: PSQL
</code>```

docker-compose build successfully builds docker images and shows following message:

```<code>Successfully built 6b13b02488dc
Successfully tagged loopserver_web:latest
nginx uses an image, skipping
</code>```

But, when I try to run docker-compose up following error occurs:

```<code>Creating NGINX ...
Creating NGINX ... error

ERROR: for NGINX  Cannot create container for service nginx: invalid port specification: "None"

ERROR: for nginx  Cannot create container for service nginx: invalid port specification: "None"
ERROR: Encountered errors while bringing up the project.
</code>```

And theserver.conf file inside config/nginx folder.

```<code>upstream web {
  ip_hash;
  server web:8000;
}

# portal
server {
  location /static/ {
        autoindex on;
        alias /static/;
    }
  location / {
        proxy_pass http://web/;
    }
  listen 8000;
  server_name localhost;
}
</code>```

I am using docker for the first time and stuck with this error. Any guidance will be very helpful.

答:
I leave the answer here to consult in the future.

As we investigated, it seems that there is some issue in your docker-compose version (< 1.12.0) with python3.

Bug: https://github.com/docker/compose/issues/4729

They recommend to upgrade to Python 3.4.4+ or 3.5.1+, and it should be fixed.

Body:
I am trying to setup Docker for my django project. I believe everything is setup to run docker in my machine. Currently, the docker version gives following output:

Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.2.1
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64
Server version: 17.05.0-ce
Server API version: 1.29
Go version (server): go1.7.5
Git commit (server): 89658be
OS/Arch (server): linux/amd64

I have setup my docker-compose.yml file as follows:

version: '3'
services:
  nginx:
    restart: always
    image: nginx:latest
    container_name: NGINX
    ports:
      - "8000:8000"
    volumes:
      - ./src:/src
      - ./config/nginx:/etc/nginx/conf.d
      - /static:/static
    depends_on:
      - web
  web:
    restart: always
    build: .
    container_name: DJANGO
    command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload"
    depends_on:
      - db
    volumes:
      - ./src:/src
      - /static:/static
    expose:
      - "8000"

  db:
    restart: always
    image: postgres:latest
    container_name: PSQL

docker-compose build successfully builds docker images and shows following message:

Successfully built 6b13b02488dc
Successfully tagged loopserver_web:latest
nginx uses an image, skipping

But, when I try to run docker-compose up following error occurs:

Creating NGINX ...
Creating NGINX ... error

ERROR: for NGINX  Cannot create container for service nginx: invalid port specification: "None"

ERROR: for nginx  Cannot create container for service nginx: invalid port specification: "None"
ERROR: Encountered errors while bringing up the project.

And theserver.conf file inside config/nginx folder.

upstream web {
  ip_hash;
  server web:8000;
}

# portal
server {
  location /static/ {
        autoindex on;
        alias /static/;
    }
  location / {
        proxy_pass http://web/;
    }
  listen 8000;
  server_name localhost;
}

I am using docker for the first time and stuck with this error. Any guidance will be very helpful.


问:
Capybara can't find a file to attach in an RSpec/Rails test
I'm using Capybara/RSpec to write a feature test in a Rails 5 app to check the uploading of images on my site.  I am getting this error:

```<code>  1) Photos user adds a photo
     Failure/Error: attach_file("photo[image]", '/app/assets/images/instagram-logo.jpg')

 Capybara::FileNotFound:
   cannot attach file, /app/assets/images/instagram-logo.jpg does not exist
</code>```

My test is
require 'rails_helper'
require 'web_helpers'

```<code>RSpec.feature "Photos", type: :feature do
  scenario "user adds a photo", :type => :feature do
    add_photo
    page.should have_content("Instagram Logo")
    expect(page).to have_css("img[src*='instagram-logo.jpg']")
  end
end
</code>```

Web helper:

```<code>def add_photo
  sign_up
  visit "/photos"
  click_button "New Photo"
  fill_in "Title", :with => "Instagram Logo"
  attach_file("photo[image]", Rails.root + '/app/assets/images/instagram-logo.jpg')
end
</code>```

The view:

```<code>  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title, id: :photo_title %>
  </div>

  <div class="field">
    <%= form.label :image %>
    <%= form.file_field :image, id: :photo_title %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
</code>```

The HTML compiled from the view:

```<code><form enctype="multipart/form-data" action="/photos" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="igZ4MndDfIQdZOmdiPxKu14bTIkAQTeKG+hwq0E6swKuskkkiCFwEVkarMgS26lc83z1eB/QyuQtnfFLRyuLWQ==" />

  <div class="field">
    <label for="photo_title">Title</label>
    <input id="photo_title" type="text" name="photo[title]" />
  </div>

  <div class="field">
    <label for="photo_image">Image</label>
    <input id="photo_title" type="file" name="photo[image]" />
  </div>

  <div class="actions">
    <input type="submit" name="commit" value="Create Photo" data-disable-with="Create Photo" />
  </div>
</form>
</code>```

The file is definitely in that filepath.  I have tried it without the Rails.root, and also originally had it in the public folder where I tried Rails.root + /public/instagram-logo.jp and simply /public/instagram-logo.jpg and finally instagram-logo.jp.  Not sure if the issue is the filepath or perhaps a bit further back along the line.  Have also tried attach_file("image"... in the web_helper.

Any help much appreciated!

答:
When you pass an abolute path like Rails.root + '/app/assets/images/instagram-logo.jpg', Rails.root will be ignored. Try Rails.root + 'app/assets/images/instagram-logo.jpg' and see what happens.

Also check if the File really exists with:

```<code>File.exist?(Rails.root + 'app/assets/images/instagram-logo.jpg')
</code>```

(Since this is the error thrown by CapyBara https://github.com/teamcapybara/capybara/blob/3a2c5d21e756460d388995aa9698c4bc8c6ba49d/lib/capybara/node/actions.rb#L238)

FYI: This is a behaviour of Pathname:

```<code>pry(main)> Pathname.new("/this/is/my/root") + "/plus/absolute"
=> #<Pathname:/plus/absolute>
pry(main)> Pathname.new("/this/is/my/root") + "plus/relative"
=> #<Pathname:/this/is/my/root/plus/relative>
</code>```

Body:
I'm using Capybara/RSpec to write a feature test in a Rails 5 app to check the uploading of images on my site.  I am getting this error:

  1) Photos user adds a photo
     Failure/Error: attach_file("photo[image]", '/app/assets/images/instagram-logo.jpg')

 Capybara::FileNotFound:
   cannot attach file, /app/assets/images/instagram-logo.jpg does not exist

My test is
require 'rails_helper'
require 'web_helpers'

RSpec.feature "Photos", type: :feature do
  scenario "user adds a photo", :type => :feature do
    add_photo
    page.should have_content("Instagram Logo")
    expect(page).to have_css("img[src*='instagram-logo.jpg']")
  end
end

Web helper:

def add_photo
  sign_up
  visit "/photos"
  click_button "New Photo"
  fill_in "Title", :with => "Instagram Logo"
  attach_file("photo[image]", Rails.root + '/app/assets/images/instagram-logo.jpg')
end

The view:

    <%= form.label :title %>
    <%= form.text_field :title, id: :photo_title %>

    <%= form.label :image %>
    <%= form.file_field :image, id: :photo_title %>

    <%= form.submit %>

The HTML compiled from the view:

<form enctype="multipart/form-data" action="/photos" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="igZ4MndDfIQdZOmdiPxKu14bTIkAQTeKG+hwq0E6swKuskkkiCFwEVkarMgS26lc83z1eB/QyuQtnfFLRyuLWQ==" />

    Title
    <input id="photo_title" type="text" name="photo[title]" />

    Image
    <input id="photo_title" type="file" name="photo[image]" />

    <input type="submit" name="commit" value="Create Photo" data-disable-with="Create Photo" />

</form>

The file is definitely in that filepath.  I have tried it without the Rails.root, and also originally had it in the public folder where I tried Rails.root + /public/instagram-logo.jp and simply /public/instagram-logo.jpg and finally instagram-logo.jp.  Not sure if the issue is the filepath or perhaps a bit further back along the line.  Have also tried attach_file("image"... in the web_helper.

Any help much appreciated!

Body:
When you pass an abolute path like Rails.root + '/app/assets/images/instagram-logo.jpg', Rails.root will be ignored. Try Rails.root + 'app/assets/images/instagram-logo.jpg' and see what happens.

Also check if the File really exists with:

File.exist?(Rails.root + 'app/assets/images/instagram-logo.jpg')

(Since this is the error thrown by CapyBara https://github.com/teamcapybara/capybara/blob/3a2c5d21e756460d388995aa9698c4bc8c6ba49d/lib/capybara/node/actions.rb#L238)

FYI: This is a behaviour of Pathname:

pry(main)> Pathname.new("/this/is/my/root") + "/plus/absolute"
=> #<Pathname:/plus/absolute>
pry(main)> Pathname.new("/this/is/my/root") + "plus/relative"
=> #<Pathname:/this/is/my/root/plus/relative>


问:
Unable to get constant variable in Laravel 5.4
I create file named constants.php in project\config folder

The content is

```<code><?php

return [

  'foo' => 'bar',

];

?>
</code>```

But I get empty response while I do config('constants.foo') or Config::get('constants.foo')

Where I'm doing wrong?

答:
Update the autoloader and clear the config cache.

Run

```<code>composer dump-autoload
</code>```

Then

```<code>php artisan config:clear
</code>```

Body:
I create file named constants.php in project\config folder

The content is

<?php

return [

  'foo' => 'bar',

];

?>

But I get empty response while I do config('constants.foo') or Config::get('constants.foo')

Where I'm doing wrong?

Body:
Update the autoloader and clear the config cache.

Run

composer dump-autoload

Then

php artisan config:clear


问:
run .jar on .app bundle with arguments
I created a .app bundle that executes jar file. I made the app bundle the default application for a specific file type. how to pass the selected file as argument to the java program

the script that I am using:

```<code>on run (input, parameters)
  set p to POSIX path of (path to me)
  do shell script java -jar" & p & "/Contents/Java/MyFile.jar'
end run
</code>```

答:
You OS should pass the file names as individual command line arguments. That means you get them as elements in the parameter of </p>

```<code>public void main(String[] args)
</code>```

Title: run .jar on .app bundle with arguments

Body:
I created a .app bundle that executes jar file. I made the app bundle the default application for a specific file type. how to pass the selected file as argument to the java program

the script that I am using:

on run (input, parameters)
  set p to POSIX path of (path to me)
  do shell script java -jar" & p & "/Contents/Java/MyFile.jar'
end run

Body:
You OS should pass the file names as individual command line arguments. That means you get them as elements in the parameter of

public void main(String[] args)


问:
Java Stream digits to number
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

```<code>IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.
</code>```

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

```<code>digits.forEach(element -> result=result.concat(result, element.toString()));
</code>```

答:
You were not doing that too bad, minor changes that I would suggest is using forEachOrdered, because forEach does not guarantee order for parallel streams and collection that to a StringBuilder. Something like:

```<code>IntStream digits = IntStream.of(1, 2, 3);
StringBuilder sb = new StringBuilder();
digits.forEachOrdered(sb::append);
System.out.println(new BigInteger(sb.toString()));
</code>```

Title: Java Stream digits to number

Body:
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

digits.forEach(element -> result=result.concat(result, element.toString()));

Body:
You were not doing that too bad, minor changes that I would suggest is using forEachOrdered, because forEach does not guarantee order for parallel streams and collection that to a StringBuilder. Something like:

IntStream digits = IntStream.of(1, 2, 3);
StringBuilder sb = new StringBuilder();
digits.forEachOrdered(sb::append);
System.out.println(new BigInteger(sb.toString()));


答:
In your example, there's no need to make AnimalController a generic class. It can simple have methods that work on Animals and they will work on both Dog and Cat via inheritance.

```<code>class Animals {
    // ...
}

class Dog: Animals {
    // ...
}

class Cat: Animals {
    // ...
}

class AnimalController {
    // methods to control any kind of animals
    var animal: Animals? // Will take both cats and dogs
    func feed(animal: Animals) {
        // Will take both cats and dogs
    }
}

class MainViewController: UIViewController {
    var controller: AnimalController?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog or a cat
        self.controller = AnimalController()

        let cat = Cat()
        controller?.animal = cat
        controller?.feed(animal: cat)

        let dog = Dog()
        controller?.animal = dog
        controller?.feed(animal: dog)
    }
}
</code>```

(updated)

Even after your edits, I see no need for generics:

```<code>class Animal {
    // ...
    func feed(_ food: Food){
        // feed the animal or maybe throw an error
        // if subclasses must implement
    }
}

class Dog: Animal {
    // ...
    override func feed(_ food: Food) {
        // feed a cat
    }
}

class Cat: Animal {
    // ...
    override func feed(_ food: Food) {
        // feed a dog
    }
}

class Food {
    init(_ animalType: Animal.Type) {
        // Make food
    }
}

class AnimalController {
    // methods to control any kind of animals
    var animal: Animal? // Will take both cats and dogs
    func feed(animal: Animal) {
        // Will take both cats and dogs
        let food = Food(type(of: animal))
        animal.feed(food)
    }
}

class MainViewController: UIViewController {
    var controller: AnimalController?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog or a cat
        self.controller = AnimalController()

        let cat = Cat()
        controller?.animal = cat
        controller?.feed(animal: cat)

        let dog = Dog()
        controller?.animal = dog
        controller?.feed(animal: dog)
    }
}
</code>```

Title: Generics classes and inheritance

Body:
I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T: Animal> {
      var animal: T?
      func feed(animal: T) {
          let food = Food(T.self)
          animal.feed(food)
      }
}

Here it's the issue:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Error

        // I want control a cat
        self.controller = AnimalController<Cat>()  // Error
    }
}

How could I create generic class compatible with dogs and cats? Thanks!

UPDATED Hamish give me the solution linking other two posts.

I have the model object:

class Animal {
// ...
}

And subclasses:

class Dog: Animal {
// ...
}

class Cat: Animal {
// ...
}

Also I've created the generic class

class AnimalController<T> {
    var type: T

    init(type: T) {
        self.type = type
    }

    func feed() {
        if type is Animal.Type {
            let food = Food(type as! Animal.Type)
            animal.feed(food)
        }
    }
}

Now it works:

class MainViewController: UIViewController {
      var controller: AnimalController<Animal>?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog
        self.controller = AnimalController<Dog>()  // Works!
        self.controller = AnimalController<Cat>()  // Works!
    }
}

Body:
In your example, there's no need to make AnimalController a generic class. It can simple have methods that work on Animals and they will work on both Dog and Cat via inheritance.

class Animals {
    // ...
}

class Dog: Animals {
    // ...
}

class Cat: Animals {
    // ...
}

class AnimalController {
    // methods to control any kind of animals
    var animal: Animals? // Will take both cats and dogs
    func feed(animal: Animals) {
        // Will take both cats and dogs
    }
}

class MainViewController: UIViewController {
    var controller: AnimalController?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog or a cat
        self.controller = AnimalController()

        let cat = Cat()
        controller?.animal = cat
        controller?.feed(animal: cat)

        let dog = Dog()
        controller?.animal = dog
        controller?.feed(animal: dog)
    }
}

(updated)

Even after your edits, I see no need for generics:

class Animal {
    // ...
    func feed(_ food: Food){
        // feed the animal or maybe throw an error
        // if subclasses must implement
    }
}

class Dog: Animal {
    // ...
    override func feed(_ food: Food) {
        // feed a cat
    }
}

class Cat: Animal {
    // ...
    override func feed(_ food: Food) {
        // feed a dog
    }
}

class Food {
    init(_ animalType: Animal.Type) {
        // Make food
    }
}

class AnimalController {
    // methods to control any kind of animals
    var animal: Animal? // Will take both cats and dogs
    func feed(animal: Animal) {
        // Will take both cats and dogs
        let food = Food(type(of: animal))
        animal.feed(food)
    }
}

class MainViewController: UIViewController {
    var controller: AnimalController?

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        // I want control a dog or a cat
        self.controller = AnimalController()

        let cat = Cat()
        controller?.animal = cat
        controller?.feed(animal: cat)

        let dog = Dog()
        controller?.animal = dog
        controller?.feed(animal: dog)
    }
}


问:
Extract first row from each text file in directory subtree
I have set of 5000 CSV files in tree directory structure.
Every file was first row denoting its enconding, then typical CSV content follows.

```<code>UTF-8
Key1,"Value 1",
Key2,"Value 2"
etc, etc...
</code>```

How can I quickly collect first row from each file in order to oversee set of their encodings?

I'm trying this with help of this answer but I don't clearly understand all syntax nuances of batch file variables so I am getting stuff like Echo is on.

```<code>for /R D:\resources\ %%f in (*.csv) do (
    set /p line1=<%%f
    echo %line1% >> out.txt
)
</code>```

If parts are executed individually (for single file), they work.

I was also trying single-liner

```<code>for /R D:\resources\ %f in (*.csv) do set /p line1=<%f & echo %line1% >> out.txt
</code>```

but this one put value collected from first file into output from each file.

答:
aschipfl's comment helped. Adding corrected and completed script for benefit of others:</p>

```<code>@echo off
copy NUL out.txt
SETLOCAL EnableDelayedExpansion
for /R D:\resources\ %%g in (*.csv) do (
  set /p line1=<%%g
  echo !line1! >> out.txt
)
</code>```

Body:
I have set of 5000 CSV files in tree directory structure.
Every file was first row denoting its enconding, then typical CSV content follows.

UTF-8
Key1,"Value 1",
Key2,"Value 2"
etc, etc...

How can I quickly collect first row from each file in order to oversee set of their encodings?

I'm trying this with help of this answer but I don't clearly understand all syntax nuances of batch file variables so I am getting stuff like Echo is on.

for /R D:\resources\ %%f in (*.csv) do (
    set /p line1=<%%f
    echo %line1% >> out.txt
)

If parts are executed individually (for single file), they work.

I was also trying single-liner

for /R D:\resources\ %f in (*.csv) do set /p line1=<%f & echo %line1% >> out.txt

but this one put value collected from first file into output from each file.

Body:
aschipfl's comment helped. Adding corrected and completed script for benefit of others:

@echo off
copy NUL out.txt
SETLOCAL EnableDelayedExpansion
for /R D:\resources\ %%g in (*.csv) do (
  set /p line1=<%%g
  echo !line1! >> out.txt
)


问:
starting xmonad
I'm completely new to xmonad but I'd like to start using it to boost my productivity.

This is the guide I've been using (I'm using Apple OS X Snow Leopard)
http://xmonad.org/tour.html#start

So far I've managed to install Haskell-Platform, Cabal, dMenu, and xmonad (using cabal install).

When I attempt to run xmonad from the terminal I run into this error:

```<code>SDGL0990Z464C:~ cflynn$ echo $PATH
/Users/cflynn/.cabal/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin
SDGL0990Z464C:~ cflynn$ xmonad
/Users/cflynn/.xmonad/xmonad-i386-darwin: executeFile: does not exist (No such file or directory)
X Error of failed request:  BadAccess (attempt to access private resource denied)
  Major opcode of failed request:  2 (X_ChangeWindowAttributes)
  Serial number of failed request:  7
  Current serial number in output stream:  8
</code>```

Can anyone explain what this means? Thanks!

答: Does the file /Users/cflynn/.xmonad/xmonad-i386-darwin exist?  It sounds like it does not.  You will need to compile your xmonad config and put the resulting executable at that location.</p>

Title: starting xmonad

Body:
I'm completely new to xmonad but I'd like to start using it to boost my productivity.

This is the guide I've been using (I'm using Apple OS X Snow Leopard)
http://xmonad.org/tour.html#start

So far I've managed to install Haskell-Platform, Cabal, dMenu, and xmonad (using cabal install).

When I attempt to run xmonad from the terminal I run into this error:

SDGL0990Z464C:~ cflynn$ echo $PATH
/Users/cflynn/.cabal/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin
SDGL0990Z464C:~ cflynn$ xmonad
/Users/cflynn/.xmonad/xmonad-i386-darwin: executeFile: does not exist (No such file or directory)
X Error of failed request:  BadAccess (attempt to access private resource denied)
  Major opcode of failed request:  2 (X_ChangeWindowAttributes)
  Serial number of failed request:  7
  Current serial number in output stream:  8

Can anyone explain what this means? Thanks!


问:
Amount to always show 2 decimal places
Hi I have an ajax that gives result of my Balance when a particular is selected. My question is I want it to show with 2 decimal places even the amount is not in decimal form.

For example:

9000 = 9000.00

9000.1 = 9000.10

9000.11 = 9000.11

9000.159 = 9000.16

The form looks like this to give you a view of the result.

I have already tried the toFixed that is mostly answered but I cannot seem to make it work here, I have tried 2 codes.

1st code:

```<code>function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        $('#subpaymentbalance'+row).val(response.feestudent_amount).toFixed(2);

    } // /successs
}); // /ajax

}
</code>```

2nd Code:

```<code>function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        parseFloat($('#subpaymentbalance'+row).val(response.feestudent_amount)).toFixed(2);

    } // /successs
}); // /ajax

}
</code>```

Still same results.

答:
.toFixed(2) is in the wrong place.

Instead of:

```<code>$('#subpaymentbalance' + row).val(response.feestudent_amount).toFixed(2);
</code>```

It should be:

```<code>$('#subpaymentbalance' + row).val(response.feestudent_amount.toFixed(2));
</code>```

Title: Amount to always show 2 decimal places

Body:
Hi I have an ajax that gives result of my Balance when a particular is selected. My question is I want it to show with 2 decimal places even the amount is not in decimal form.

For example:

9000 = 9000.00

9000.1 = 9000.10

9000.11 = 9000.11

9000.159 = 9000.16

The form looks like this to give you a view of the result.

I have already tried the toFixed that is mostly answered but I cannot seem to make it work here, I have tried 2 codes.

1st code:

function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        $('#subpaymentbalance'+row).val(response.feestudent_amount).toFixed(2);

    } // /successs
}); // /ajax

}

2nd Code:

function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        parseFloat($('#subpaymentbalance'+row).val(response.feestudent_amount)).toFixed(2);

    } // /successs
}); // /ajax

}

Still same results.

Body:
.toFixed(2) is in the wrong place.

Instead of:

$('#subpaymentbalance' + row).val(response.feestudent_amount).toFixed(2);

It should be:

$('#subpaymentbalance' + row).val(response.feestudent_amount.toFixed(2));


问:
Issue in case of conflict in Git while committing the changes?
While pushing, I got a conflict. So I pulled it, and fixed the conflict in my local.

Git pull and push is not working.

For pull, the error is:

```<code>abc@xyz MINGW64 /e/Git project (master|MERGING)
 *git pull origin master*
error: You have not concluded your merge (MERGE_HEAD exists).
hint: Please, commit your changes before merging.
fatal: Exiting because of unfinished merge.
</code>```

For push, error is:

```<code> ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to center git repository
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
</code>```

答:
My first recommendation is verify the repository

```<code>git status
</code>```

Then make the decision if you have resolved the conflict

```<code>git add files
git commit
</code>```

Now you can push your changes, but it depends of your situation, please read https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts

Body:
While pushing, I got a conflict. So I pulled it, and fixed the conflict in my local.

Git pull and push is not working.

For pull, the error is:

abc@xyz MINGW64 /e/Git project (master|MERGING)
 *git pull origin master*
error: You have not concluded your merge (MERGE_HEAD exists).
hint: Please, commit your changes before merging.
fatal: Exiting because of unfinished merge.

For push, error is:

 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to center git repository
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.

Body:
My first recommendation is verify the repository

git status

Then make the decision if you have resolved the conflict

git add files
git commit

Now you can push your changes, but it depends of your situation, please read https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts


问:
Cron job scheduling is not working in ubuntu
1) i have a script sp19.sh in the path /home/killer/Desktop/alok/scripts/test1

```<code>#script to copy file 1 in test dir
a=`ls -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "$a"  "$b"
</code>```

2) i scheduled a task to copy a file named 1 in the same location using the below code in crontab.But this is not working.

```<code>m h  dom mon dow   command
* * * * * /home/killer/Desktop/alok/scripts/test1/sp19.sh
</code>```

3) I have already tested that the sp19.sh is correct and generating the files but cron job is not working.

Thanks

答:
Change your Cron expression to

```<code>0 0/1 * 1/1 * ? *
</code>```

This will make it run every one minute.

If it doesn't work, you could take a look here

https://askubuntu.com/q/2368

Body:
1) i have a script sp19.sh in the path /home/killer/Desktop/alok/scripts/test1

#script to copy file 1 in test dir
a=`ls -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "$a"  "$b"

2) i scheduled a task to copy a file named 1 in the same location using the below code in crontab.But this is not working.

m h  dom mon dow   command
* * * * * /home/killer/Desktop/alok/scripts/test1/sp19.sh

3) I have already tested that the sp19.sh is correct and generating the files but cron job is not working.

Thanks

Body:
Change your Cron expression to

0 0/1 * 1/1 * ? *

This will make it run every one minute.

If it doesn't work, you could take a look here

https://askubuntu.com/q/2368


问:
Create an app lifetime object (not possible to be deallocated) in Swift
I want to create an object from a class. And I want it life time to be the app life time. I mean I want it not be deallocated since the app is running.

the class that I want to make an instance from:

```<code>extension Post {

    @NSManaged var userId: Int
    @NSManaged var id: Int
    @NSManaged var title: String
    @NSManaged var body: String

}

class Post: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

   override func awakeFromInsert() {
        super.awakeFromInsert()
        title = ""
        userId = 0
        id = 0
        body = ""

    }
}
</code>```

答:
An object that keeps a strong pointer to itself cannot be deallocated:

```<code>class Permanent {
    private var ref: Permanent?

    init() {
        ref = self
    }

    deinit {
        // This will never be called
        print("Permanent deinit")
    }
}

func test() {
    var a = [Permanent(), Permanent()]
    print(a.count)

    print("free the items")
    a = []
    print("end of test")
}

test()
</code>```

Output:

```<code>2
free the items
end of test
</code>```

If you comment out the ref = self line:

Output:

```<code>2
free the items
Permanent deinit
Permanent deinit
end of test
</code>```

Body:
I want to create an object from a class. And I want it life time to be the app life time. I mean I want it not be deallocated since the app is running.

the class that I want to make an instance from:

extension Post {

    @NSManaged var userId: Int
    @NSManaged var id: Int
    @NSManaged var title: String
    @NSManaged var body: String

}

class Post: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

   override func awakeFromInsert() {
        super.awakeFromInsert()
        title = ""
        userId = 0
        id = 0
        body = ""

    }
}

Body:
An object that keeps a strong pointer to itself cannot be deallocated:

class Permanent {
    private var ref: Permanent?

    init() {
        ref = self
    }

    deinit {
        // This will never be called
        print("Permanent deinit")
    }
}

func test() {
    var a = [Permanent(), Permanent()]
    print(a.count)

    print("free the items")
    a = []
    print("end of test")
}

test()

Output:

2
free the items
end of test

If you comment out the ref = self line:

Output:

2
free the items
Permanent deinit
Permanent deinit
end of test


问:
Awesome wm 4 middle align does not work in horizontal layout
On my previous awesome installation (awesome 3.5) I wrote the configurations that do not work the same way in version 4 anymore. I would align a container within horizontal align like this:

```<code>local center_layout = wibox.layout.fixed.horizontal()
local left_layout = wibox.layout.fixed.horizontal()
local right_layout = wibox.layout.fixed.horizontal()
-- Fill layouts with widgets

local layout = wibox.layout.align.horizontal()

layout:set_left(left_layout)
layout:set_right(right_layout)
layout:set_middle(center_layout)
</code>```

but the center_layout is aligned on the left instead of center like this:

I also tried replacing the above code with

```<code>local layout = wibox.widget {
    left_layout  ,
    center_layout ,
    right_layout  ,
    layout  = wibox.layout.align.horizontal
}
</code>```

but it diddin't do any change

答: Set expand to outside for your align layout: https://awesomewm.org/doc/api/classes/wibox.layout.align.html#wibox.layout.align.expand

Body:
On my previous awesome installation (awesome 3.5) I wrote the configurations that do not work the same way in version 4 anymore. I would align a container within horizontal align like this:

local center_layout = wibox.layout.fixed.horizontal()
local left_layout = wibox.layout.fixed.horizontal()
local right_layout = wibox.layout.fixed.horizontal()
-- Fill layouts with widgets

local layout = wibox.layout.align.horizontal()

layout:set_left(left_layout)
layout:set_right(right_layout)
layout:set_middle(center_layout)

but the center_layout is aligned on the left instead of center like this:

I also tried replacing the above code with

local layout = wibox.widget {
    left_layout  ,
    center_layout ,
    right_layout  ,
    layout  = wibox.layout.align.horizontal
}

but it diddin't do any change


问:
How to send SIGINT (Ctrl-C) to current remote process over SSH (without -t option)
I need to send a SIGINT to the remote process running in foreground in an SSH session.

The SSH session is already established, so I cannot use option of starting it with (as described in How to send SIGINT to a remote process over SSH?)

```<code>ssh -t user@host
</code>```

I know I could open a second ssh session and kill the process or close the current ssh session, but I want to avoid that and do it directly throw the current session (if this is possible).

答:
If you use ssh to start a process without a PTY on a remote system, then as far as I can tell, there's no way to signal the remote process through that ssh session.

The SSH protocol has a message to send a signal to the remote process. However, you're probably using OpenSSH for either the client or the server or both, and OpenSSH doesn't implement the signal message. So the OpenSSH client can't send the message, and the OpenSSH server won't act on it.

There is an SSH extension to send a "break" message which is supported by OpenSSH. In an interactive session, the OpenSSH client has an escape sequence that you can type to send a break to the server. The OpenSSH server handles break messages by sending a break to the PTY for the remote session, and unix PTYs will normally treat a break as a SIGINT. However, breaks are fundamentally a TTY concept, and none of this will work for remote sessions which don't have a PTY.

Body:
I need to send a SIGINT to the remote process running in foreground in an SSH session.

The SSH session is already established, so I cannot use option of starting it with (as described in How to send SIGINT to a remote process over SSH?)

ssh -t user@host

I know I could open a second ssh session and kill the process or close the current ssh session, but I want to avoid that and do it directly throw the current session (if this is possible).