问:
Java Spring MVC + Hibernate Class Composition
I am starting a project with Spring MVC and Hibernate. I am concerned about best practices related to class composition. Suppose I had a class called User with an ORM technology like Hibernate.

I am not sure if I should include everything related to the User entity inside of the User class. I know that Hibernate automatically improves performance by lazy loading so it does not retrieve all instance variables when we retrieve a user. However, I feel like if we included too much variables in the User class, it will become very expensive to query User objects.

Consider this example:

```<code>@Entity
@Table(name = "Users")
public class User{

private String username;
private String password;
private long user_id;

private Collection<Transaction> transactions;

}
</code>```

Here the User class stores a collection of transactions. Each transaction represents a purchase that user made on the website. But we do not need to store a transactions collection for every user.

Instead, we can make a transaction table like so:

```<code> @Entity
 @Table(name = "UserTransactions)
 public class Transaction{

    private int user_id;
    private int order_id;
    private double amount_paid;
}
</code>```

With this transaction table, we can still store every transaction every user has made.

This is only an example, there are many more variables that do not need to be stored in the User class and can be represented by their own table. So I am wondering if there is any harm to storing all of these variables in the User class, or should we be careful and be selective of what we include in the User class? What would be the pros/cons of each approach?

Thank you in advance!

答:
If you do not want to store all the variables in database then you can restrict them using

```<code> @Column(insertable=false, updatable=false) or @transient
</code>```

and using transaction table will be a more better approach where only transaction_id and user_id are there and rest all the user details you can store in some other table as it will be more organized and normalized and will cause less overhead

Body:
I am starting a project with Spring MVC and Hibernate. I am concerned about best practices related to class composition. Suppose I had a class called User with an ORM technology like Hibernate.

I am not sure if I should include everything related to the User entity inside of the User class. I know that Hibernate automatically improves performance by lazy loading so it does not retrieve all instance variables when we retrieve a user. However, I feel like if we included too much variables in the User class, it will become very expensive to query User objects.

Consider this example:

@Entity
@Table(name = "Users")
public class User{

private String username;
private String password;
private long user_id;

private Collection<Transaction> transactions;

}

Here the User class stores a collection of transactions. Each transaction represents a purchase that user made on the website. But we do not need to store a transactions collection for every user.

Instead, we can make a transaction table like so:

 @Entity
 @Table(name = "UserTransactions)
 public class Transaction{

    private int user_id;
    private int order_id;
    private double amount_paid;
}

With this transaction table, we can still store every transaction every user has made.

This is only an example, there are many more variables that do not need to be stored in the User class and can be represented by their own table. So I am wondering if there is any harm to storing all of these variables in the User class, or should we be careful and be selective of what we include in the User class? What would be the pros/cons of each approach?

Thank you in advance!

Body:
If you do not want to store all the variables in database then you can restrict them using

 @Column(insertable=false, updatable=false) or @transient

and using transaction table will be a more better approach where only transaction_id and user_id are there and rest all the user details you can store in some other table as it will be more organized and normalized and will cause less overhead


来源: stackexchange

问:
Eigen Library: Assertions failed in a template
I have a templated function, which should generate a compile-time known fixed-size Vector, dependent on the template parameter:

```<code>template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc()
{
    switch(nSize){
    case 2: return ExternalLibrary::generate_Vector_2d();
    case 3: return ExternalLibrary::generate_Vector_3d();
    }
}
</code>```

However, when i compile this code, i get a failed assertion, because the Vector_2d size doesn't fit the 3d size:

```<code>Eigen::Vector3d testVector3d = myFunc<3>(); // failed, because 3d doesn't fit the theoreticelly possible 2d
</code>```

Basically, the failed assertion is understandable, but of course this will never be an issue at runtime. How can i bypass this failed assertion? Or is there a more elegant way than the switch condition?

Thank you!

答:
Just declare the template function and don't define it, then define two specializations:

```<code>template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc();

template <>
Eigen::Matrix<double, 2, 1> myFunc<2>()
{
    return ExternalLibrary::generate_Vector_2d();
}

template <>
Eigen::Matrix<double, 3, 1> myFunc<3>()
{
    return ExternalLibrary::generate_Vector_3d();
}
</code>```

The compiler, while it will eliminate dead code as an optimization, must verify the validity of the dead code anyway, which means it must ensure that the return type of ExternalLibrary::generate_Vector_3d() can be converted to Eigen::Matrix<double, 2, 1>, even though it can be proven that that return statement can't be executed.  Because this conversion is not allowed, you get a compile-time error.

By separating out the two return statements into separate specializations, you eliminate this problem as it removes the return ExternalLibrary::generate_Vector_3d(); statement from a function that could return something other than an Eigen::Matrix<double, 3, 1>.

Note that using myFunc() with an nSize other than 2 or 3 will cause a link-time error.  We can move this error to compile-time by providing a body that will fail to instantiate, but that (ostensibly) depends on nSize so that the compiler won't try to instantiate it before it is used:

```<code>template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc()
{
    // With C++11, the following line provides a more useful diagnostic. If
    // you don't have C++11 support, remove it and the bad return statement
    // will do the job, albeit with a more cryptic error message.
    static_assert((static_cast<void>(nSize), false), "Invalid template parameter nSize");

    return static_cast<class INVALID_NSIZE_PARAMETER**********>(nSize);
}
</code>```

This will provide a diagnostic pointing to the incorrect use of myFunc().  For example, without C++11 support you would see something like:

```<code>main.cpp:12:12: error: cannot cast from type 'int' to pointer type 'class INVALID_NSIZE_PARAMETER **********'
    return static_cast<class INVALID_NSIZE_PARAMETER**********>(nSize);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:29:5: note: in instantiation of function template specialization 'myFunc<4>' requested here
    myFunc<4>();
    ^
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a templated function, which should generate a compile-time known fixed-size Vector, dependent on the template parameter:

template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc()
{
    switch(nSize){
    case 2: return ExternalLibrary::generate_Vector_2d();
    case 3: return ExternalLibrary::generate_Vector_3d();
    }
}

However, when i compile this code, i get a failed assertion, because the Vector_2d size doesn't fit the 3d size:

Eigen::Vector3d testVector3d = myFunc<3>(); // failed, because 3d doesn't fit the theoreticelly possible 2d

Basically, the failed assertion is understandable, but of course this will never be an issue at runtime. How can i bypass this failed assertion? Or is there a more elegant way than the switch condition?

Thank you!

Body:
Just declare the template function and don't define it, then define two specializations:

template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc();

template <>
Eigen::Matrix<double, 2, 1> myFunc<2>()
{
    return ExternalLibrary::generate_Vector_2d();
}

template <>
Eigen::Matrix<double, 3, 1> myFunc<3>()
{
    return ExternalLibrary::generate_Vector_3d();
}

The compiler, while it will eliminate dead code as an optimization, must verify the validity of the dead code anyway, which means it must ensure that the return type of ExternalLibrary::generate_Vector_3d() can be converted to Eigen::Matrix<double, 2, 1>, even though it can be proven that that return statement can't be executed.  Because this conversion is not allowed, you get a compile-time error.

By separating out the two return statements into separate specializations, you eliminate this problem as it removes the return ExternalLibrary::generate_Vector_3d(); statement from a function that could return something other than an Eigen::Matrix<double, 3, 1>.

Note that using myFunc() with an nSize other than 2 or 3 will cause a link-time error.  We can move this error to compile-time by providing a body that will fail to instantiate, but that (ostensibly) depends on nSize so that the compiler won't try to instantiate it before it is used:

template <int nSize>
Eigen::Matrix<double, nSize, 1> myFunc()
{
    // With C++11, the following line provides a more useful diagnostic. If
    // you don't have C++11 support, remove it and the bad return statement
    // will do the job, albeit with a more cryptic error message.
    static_assert((static_cast<void>(nSize), false), "Invalid template parameter nSize");

    return static_cast<class INVALID_NSIZE_PARAMETER**********>(nSize);
}

This will provide a diagnostic pointing to the incorrect use of myFunc().  For example, without C++11 support you would see something like:

main.cpp:12:12: error: cannot cast from type 'int' to pointer type 'class INVALID_NSIZE_PARAMETER **********'
    return static_cast<class INVALID_NSIZE_PARAMETER**********>(nSize);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:29:5: note: in instantiation of function template specialization 'myFunc<4>' requested here
    myFunc<4>();
    ^


问:
Simple Unity3d app get stucked on Android
I have a rather simple game in Unity3d. The game has about 300 3D objects - all of them have physics, some use cloth.

I am able to open the game on my Android phone, but the app get sucked after 2-3 minutes. The game works fine on my PC.

What am I doing wrong and what can I do to solve this issue?

答: You could use shared material technique, static or dynamic batching, GC.Collect() method and other techniques to improve the performance (you may find them by googling or here: https://unity3d.com/learn/tutorials/topics/performance-optimization). Anyway, I would suggest taking a look at Unity's profiler (biult-in) to find the bottlenecks of the app.</p>


问:
aspx submit form error
Im working with asp.net  framework 4.0 and I have this code:

form id="form1" runat="server" method="get" action="Profile.aspx"

```<code> // some code
</code>```

asp:Button runat="server" ID="SubmitButton" Text="Submit"

Each time i click the submit button i get this error:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

any idea how to fix it ???

答:
This is caused by cross-page POST (i.e. you are submitting the ViewState of the first page to the second). You can add PostBackUrl to the button like this:

```<code><asp:Button runat="server" ID="SubmitButton" Text="Submit" PostBackUrl="~/WebForm2.aspx" />
</code>```

Alternatively you can handle the click event of the button in the first page, move some of the logic in this handler and do a Response.Redirect (i.e. GET request) to the second page. The right solution depends on your particular case.

ContentLicense: CC BY-SA 2.5

Title: aspx submit form error

Body:
Im working with asp.net  framework 4.0 and I have this code:

form id="form1" runat="server" method="get" action="Profile.aspx"

 // some code

asp:Button runat="server" ID="SubmitButton" Text="Submit"

Each time i click the submit button i get this error:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

any idea how to fix it ???

Body:
This is caused by cross-page POST (i.e. you are submitting the ViewState of the first page to the second). You can add PostBackUrl to the button like this:

<asp:Button runat="server" ID="SubmitButton" Text="Submit" PostBackUrl="~/WebForm2.aspx" />

Alternatively you can handle the click event of the button in the first page, move some of the logic in this handler and do a Response.Redirect (i.e. GET request) to the second page. The right solution depends on your particular case.


问:
calculating consecutive 1's in a Binary number
```<code>import java.util.Scanner;
import java.util.Arrays;
class Solve
{
  public static void main(String args[])
  {
    Scanner in = new Scanner(System.in);
    int i=0,count=0;
    int[] arr = new int[10];
    int n =in.nextInt();
    while(n!=0)
    {
      arr[i]=n%2;
      i++;
      n=n/2;
    }
    System.out.println(Arrays.toString(arr));
  }

  }
}
</code>```

I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer  5.. How can i do that??

答:
```<code>    public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int counter = 0, max = Integer.MIN_VALUE;
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == 1){
            counter += nums[i];
        } else{
            counter = nums[i];
        }
        max = Math.max(counter, max);
    }
    return max;
}
</code>```

<p>}</p>

Body:
import java.util.Scanner;
import java.util.Arrays;
class Solve
{
  public static void main(String args[])
  {
    Scanner in = new Scanner(System.in);
    int i=0,count=0;
    int[] arr = new int[10];
    int n =in.nextInt();
    while(n!=0)
    {
      arr[i]=n%2;
      i++;
      n=n/2;
    }
    System.out.println(Arrays.toString(arr));
  }

  }
}

I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer  5.. How can i do that??

Body:
    public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int counter = 0, max = Integer.MIN_VALUE;
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == 1){
            counter += nums[i];
        } else{
            counter = nums[i];
        }
        max = Math.max(counter, max);
    }
    return max;
}

}


问:
Dynamically loading and autoplaying HTML5 video
I am trying to grab a video URL from data-src and add it to src for my video. I have that much working when I snoop the page code but the video isn't showing up on the page and playing. I'm using jQuery since I have a few other bits of code using it to run some functionality.

Markup:

```<code><video autoplay="autoplay" loop="loop" poster="/assets/video/bg-ss-vid.jpg">
    <source type="video/mp4" data-src="/assets/video/bg-ss-vid.mp4">
</video>
</code>```

jQuery:

```<code>jQuery(document).ready(function ($) {
    "use strict";

    $("#site-hero video").each(function () {
        $('source', $(this)).attr("src", $('source', $(this)).data('src'));
        $('source', $(this)).removeAttr('data-src');
    });
});
</code>```

How do I get it to show up / play the video after the src has been loaded?

答:
Use .play() after adding it's src.

jQuery(document).ready(function($) {
  "use strict";

  $("video").each(function() {
    var $source = $(this).find('source');
    var src = $source.attr('data-src');

    $source.removeAttr('data-src');
    $source.attr('src', src);
    $source.detach().appendTo($(this))

    $(this).get(0).play();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>video {
  width: 420px;
  height: 230px;
}</code>```

<video loop="loop" poster="http://placehold.it/420x230">
    <source type="video/mp4" data-src="http://techslides.com/demos/sample-videos/small.mp4">
</video>```

Body:
I am trying to grab a video URL from data-src and add it to src for my video. I have that much working when I snoop the page code but the video isn't showing up on the page and playing. I'm using jQuery since I have a few other bits of code using it to run some functionality.

Markup:

<video autoplay="autoplay" loop="loop" poster="/assets/video/bg-ss-vid.jpg">
    <source type="video/mp4" data-src="/assets/video/bg-ss-vid.mp4">
</video>

jQuery:

jQuery(document).ready(function ($) {
    "use strict";

    $("#site-hero video").each(function () {
        $('source', $(this)).attr("src", $('source', $(this)).data('src'));
        $('source', $(this)).removeAttr('data-src');
    });
});

How do I get it to show up / play the video after the src has been loaded?

Body:
Use .play() after adding it's src.

jQuery(document).ready(function($) {
  "use strict";

  $("video").each(function() {
    var $source = $(this).find('source');
    var src = $source.attr('data-src');

    $source.removeAttr('data-src');
    $source.attr('src', src);
    $source.detach().appendTo($(this))

    $(this).get(0).play();
  });
});

video {
  width: 420px;
  height: 230px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video loop="loop" poster="http://placehold.it/420x230">
    <source type="video/mp4" data-src="http://techslides.com/demos/sample-videos/small.mp4">
</video>


问:
Code Sign Failing from Jenkins for iOS application
I recently updated my Jenkins mac mini machine from yosemite to sierra along with latest xcode ( 8.3.2 ).

Now whenever I try to build my app and code sign from jenkins job, it fails with the following cryptic error

```<code>unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1
</code>```

When i ssh into my jenkins mac mini box as jenkins user and run the same build command everything works fine. Also, It works fine when building and signing the app from xcode. Has anyone seen this problem happening?

答:
Adding this to the build step in Jenkins job solved the problem for me.

security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k ${JENKINS_PWD} ~/Library/Keychains/login.keychain-db

Body:
I recently updated my Jenkins mac mini machine from yosemite to sierra along with latest xcode ( 8.3.2 ).

Now whenever I try to build my app and code sign from jenkins job, it fails with the following cryptic error

unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

When i ssh into my jenkins mac mini box as jenkins user and run the same build command everything works fine. Also, It works fine when building and signing the app from xcode. Has anyone seen this problem happening?


问:
JMS vs Hibernate Session
My project connects to a database using hibernate, getting connections from a connection pool on JBoss. I want to replace some of the reads/writes to tables with publish/consume from queues. I built a working example that uses OracleAQ, however, I am connecting to the DB using:

AQjmsFactory.getQueueConnectionFactory followed by createQueueConnection,
then using createQueueSession to get a (JMS) QueueSession on which I can call createProducer and createConsumer.

So I know how to do what I want using a jms.QueueSession. But using hibernate, I get a hibernate.session, which doesn't have those methods.

I don't want to open a new connection every time I perform an action on a queue - which is what I am doing now in my working example. Is there a way to perform queue operations from a hibernate.session? Only with SQL queries?

答:
I was also looking for some "sane" way how to use JMS connection to manipulate database data. There is not any. Dean is right, you have to use two different connections to the same data and have distributed XA transaction between them.

This solution opens a world of various problems never seen before. In real life distributed transactions can really be non-trivial. Surprisingly in some situations Oracle can detect that two connections are pointing into the same database and then two-phase commit can be bypassed - even when using XA.

Title: JMS vs Hibernate Session


问:
How does one convert ARRAY_TO_STRING and ARRAY_AGG into arel?
I have an Arel statement that looks like the following:

```<code>vulns.project(vulns[:id],
              vulns[:cve_id],
              vulns[:severity],
              vulns[:published_on],
              vulns[:description],
  "ARRAY_TO_STRING((ARRAY_AGG(#{releases[:version]} ORDER BY #{releases[:released_on]} DESC))[1:10], ', ')")
  .join(releases_vulns)
    .on(releases_vulns[:vulnerability_id].eq(vulns[:id]))
</code>```

The toughest part that I am running into is the array_agg and array_to_string. I've checked arel documentation and I did not see a particular matching method to work out a query like this. Has anyone encountered this problem? I could use some help. Thank You.

答:
The way to convert it is the following:</p>

```<code>Arel::Nodes::NamedFunction.new 'array_agg', [expression goes here]
Arel::Nodes::NamedFunction.new 'array_to_string', [array_input, Arel::Nodes::Quoted.new(',')]
</code>```

Body:
I have an Arel statement that looks like the following:

vulns.project(vulns[:id],
              vulns[:cve_id],
              vulns[:severity],
              vulns[:published_on],
              vulns[:description],
  "ARRAY_TO_STRING((ARRAY_AGG(#{releases[:version]} ORDER BY #{releases[:released_on]} DESC))[1:10], ', ')")
  .join(releases_vulns)
    .on(releases_vulns[:vulnerability_id].eq(vulns[:id]))

The toughest part that I am running into is the array_agg and array_to_string. I've checked arel documentation and I did not see a particular matching method to work out a query like this. Has anyone encountered this problem? I could use some help. Thank You.

Body:
The way to convert it is the following:

Arel::Nodes::NamedFunction.new 'array_agg', [expression goes here]
Arel::Nodes::NamedFunction.new 'array_to_string', [array_input, Arel::Nodes::Quoted.new(',')]


问:
In query variables replacement error
I am using SQL variable replacements, and I am getting the following errors:

```<code> at com.ibm.as400.access.JDError.throwSQLException(JDError.java:408)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setValue(AS400JDBCPreparedStatement.java:3532)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setString(AS400JDBCPreparedStatement.java:3211)
        at queries.RunQueryDB2.runNameAccount(RunQueryDB2.java:237)
</code>```

The trace brings me to this code section,

```<code>stmt.setString( 1, name[0]);
stmt.setString( 2, name[1]);
stmt.setString( 3, name[2]);
</code>```

which references this SQL variable replacement:

```<code>nameToAcctQuery="SELECT DISTINCT a.Acnum"
                    + "FROM table c, table p, table a "
                    + "WHERE c.First= '?.toUpperCase()' "
                    + "AND c.Mid= '?.toUpperCase()' "
                    + "AND c.Last= '?.toUpperCase()' "
                    + "AND p.Pol= a.pol"
                    + "AND p.name= c.name";
</code>```

I use this format in many other queries, and I can not, for the life of me, figure out why I am getting an error in my variable replacement. Any ideas why?

答:
As given by Taballeman, the problem is not the variable replacement, it is the missing space between the last character and the " on this lin </p>

```<code>+ "AND p.Pol= a.pol"
</code>```

Title: In query variables replacement error

Body:
I am using SQL variable replacements, and I am getting the following errors:

 at com.ibm.as400.access.JDError.throwSQLException(JDError.java:408)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setValue(AS400JDBCPreparedStatement.java:3532)
        at com.ibm.as400.access.AS400JDBCPreparedStatement.setString(AS400JDBCPreparedStatement.java:3211)
        at queries.RunQueryDB2.runNameAccount(RunQueryDB2.java:237)

The trace brings me to this code section,

stmt.setString( 1, name[0]);
stmt.setString( 2, name[1]);
stmt.setString( 3, name[2]);

which references this SQL variable replacement:

nameToAcctQuery="SELECT DISTINCT a.Acnum"
                    + "FROM table c, table p, table a "
                    + "WHERE c.First= '?.toUpperCase()' "
                    + "AND c.Mid= '?.toUpperCase()' "
                    + "AND c.Last= '?.toUpperCase()' "
                    + "AND p.Pol= a.pol"
                    + "AND p.name= c.name";

I use this format in many other queries, and I can not, for the life of me, figure out why I am getting an error in my variable replacement. Any ideas why?

Body:
As given by Taballeman, the problem is not the variable replacement, it is the missing space between the last character and the " on this lin

+ "AND p.Pol= a.pol"


问:
Preventing CALayer Sublayers From Getting Scaled
I have some CALayers in a layer hosted view. Each of these layers has additional layers to hold (1) a close button, and (2) a resize handle. These additional 'control' layers are added as sublayers to the parent layer.

Currently, when I zoom the workspace in which these layers reside, everything scales -- including these control layers. However, I would like to prevent these control layers from scaling.

Is there a way to override the behaviour of having scale transforms being applied to all sublayers, without having to override the drawInContext: method for each control layer (presumably to invert any existing scale transform -- assuming this is possible) and without having to manually send each of these control layers a setNeedsDisplay: with every zoom?

I found this thread which discusses doing something similar but the discussion goes in the direction of CATiledLayers which is not what I'm looking for here.

Redrawing CALayer subclass when super layer is scaled

Also, this post asks a somewhat related question but the responses do not apply to my situation, since I cannot overlay the controls -- they must be part of the layer hierarchy.

How do I keep a CALayer, sublayer of a CATiledLayer, from changing it's scale after a zoom?

答: I ended up solving this problem by overriding the layoutSublayers method of my custom CALayers, obtaining the accumulated scale transform of the layer hierarchy, and applying the inverse transform to the control sublayers.</p>


问:
Reading values from Json file
I am trying to read an attribute from a Json file using this:
    d['text']['entities']['mention'][0]['screen_name']

Json File

```<code>{
    "text" : {
        "content" : "@narendramodi Did u even know the fare of metro has been increased by 65%",

        "entities" : {
            "user_mentions" : [ ],
            "mention" : [
                {
                    "indices" : [
                        0,
                        13
                    ],
                    "id_str" : "18839785",
                    "screen_name" : "narendramodi",
                    "name" : "Narendra Modi",
                    "id" : 18839785
                }
            ],
            "hashtags" : [ ],
        },

    }
}
</code>```

I am trying to load many json files in Neo4J Database using py2neo library.

While accesing    d['text']['entities']['mention'][0]['screen_name']
in one of the json file in which "mention" : [ ], mention field is empty it says

IndexError: list index out of range

Error is pretty obvious but how should I handle this?

答:
You could just use try/except block. Like

```<code>try:
  data = d['text']['entities']['mention'][0]['screen_name']
  ...
except IndexError:
  data = None # or handle this case in other way
</code>```

Title: Reading values from Json file

Body:
I am trying to read an attribute from a Json file using this:
    d['text']['entities']['mention'][0]['screen_name']

Json File

{
    "text" : {
        "content" : "@narendramodi Did u even know the fare of metro has been increased by 65%",

        "entities" : {
            "user_mentions" : [ ],
            "mention" : [
                {
                    "indices" : [
                        0,
                        13
                    ],
                    "id_str" : "18839785",
                    "screen_name" : "narendramodi",
                    "name" : "Narendra Modi",
                    "id" : 18839785
                }
            ],
            "hashtags" : [ ],
        },

    }
}

I am trying to load many json files in Neo4J Database using py2neo library.

While accesing    d['text']['entities']['mention'][0]['screen_name']
in one of the json file in which "mention" : [ ], mention field is empty it says

IndexError: list index out of range

Error is pretty obvious but how should I handle this?

Body:
You could just use try/except block. Like

try:
  data = d['text']['entities']['mention'][0]['screen_name']
  ...
except IndexError:
  data = None # or handle this case in other way


问:
Data visualisation: Drawing occurence of value in grid
Right now I'm trying to draw a rect on a canvas for each occurence of the element in my array. For the positioning I use the longitude and latitude values of the elements in the array.

Let's say that I want to draw the occurence of elements in NYC in a square grid.

Since the latitude and longitude of those elements just varies slightly I'll have to use scaling to give the rects that I want to draw a bit of space (So it doesn't look like a chaotic cluster).
Therefore I multiplied the x and y of rect() with a factor.

```<code>var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

for (var i = 0; i < array.length; i++) {
    var lat = array[i].latitude;
    var lon = array[i].longitude;

    ctx.rect(lat*10,(lon+200)*2, 4, 4);
    ctx.stroke();
}
</code>```

My array looks something like this and contains 100.000 objects:

```<code>var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]
</code>```

Right now it doesn't display anything and I don't see what I did wrong …

Am I using the right approach for drawing a (square) grid?

答:
Your code works exactly as is for me. To test it I specified an array of the form:

```<code>var array = [{latitude: 1.2, longitude: 1.3}]
</code>```

Maybe it is your html or the array does not have the format you expect.

Check this example: https://codepen.io/anon/pen/mwyLMg

Body:
Right now I'm trying to draw a rect on a canvas for each occurence of the element in my array. For the positioning I use the longitude and latitude values of the elements in the array.

Let's say that I want to draw the occurence of elements in NYC in a square grid.

Since the latitude and longitude of those elements just varies slightly I'll have to use scaling to give the rects that I want to draw a bit of space (So it doesn't look like a chaotic cluster).
Therefore I multiplied the x and y of rect() with a factor.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

for (var i = 0; i < array.length; i++) {
    var lat = array[i].latitude;
    var lon = array[i].longitude;

    ctx.rect(lat*10,(lon+200)*2, 4, 4);
    ctx.stroke();
}

My array looks something like this and contains 100.000 objects:

var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]

Right now it doesn't display anything and I don't see what I did wrong …

Am I using the right approach for drawing a (square) grid?

Body:
Your code works exactly as is for me. To test it I specified an array of the form:

var array = [{latitude: 1.2, longitude: 1.3}]

Maybe it is your html or the array does not have the format you expect.

Check this example: https://codepen.io/anon/pen/mwyLMg


问:
java.sql.sqlException: Unexpected token: FIRST_VALUE
I am working on a legacy system using java 6 and oracle db and spring 3.0 jdbcTemplate.

The query which I am trying to execute is:

```<code>SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
  OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS lowest_sal
  FROM (SELECT * FROM employees WHERE department_id = 90
    ORDER BY employee_id)
  ORDER BY department_id, last_name, salary, lowest_sal;
</code>```

But I am getting the following error:

java.sql.SQLException: Unexpected token: FIRST_VALUE in statement
    [SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
          OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS ...]

Running the same query in sql developer runs fine. I am clueless what's wrong.

答:
Sounds to me like an issue with the client version that your Java 6 app implements, instructions like FIRST_VALUE and the window construction (the OVER clause) may not be supported in older clients as they where incorporated to the DBMS since 9i version.

I've run into problems such as, a "not valid" CASE condition within a select statement when I try to use it in Forms6i environment, since the built-in client for that version can't parse the statement, even though I'm connecting to a 11g DBMS.

A solution to this may be create a stored procedure in your DB to retrieve your data and then execute and read the results from your app.

Body:
I am working on a legacy system using java 6 and oracle db and spring 3.0 jdbcTemplate.

The query which I am trying to execute is:

SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
  OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS lowest_sal
  FROM (SELECT * FROM employees WHERE department_id = 90
    ORDER BY employee_id)
  ORDER BY department_id, last_name, salary, lowest_sal;

But I am getting the following error:

java.sql.SQLException: Unexpected token: FIRST_VALUE in statement
    [SELECT department_id, last_name, salary, FIRST_VALUE(last_name)
          OVER (ORDER BY salary ASC ROWS UNBOUNDED PRECEDING) AS ...]

Running the same query in sql developer runs fine. I am clueless what's wrong.


问:
Android granted runtime permissions to my app without asking
I'm trying to test the Runtime Permissions specifically for Android sdk > 23. But my app is being granted permissions automatically without asking.

Note : I'm using sdk version 24. Here's a snippet of code I'm using:

```<code>public void onCalendarClick(View view) {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
            .PERMISSION_DENIED) {
       if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
            //Display Explanation to the user
            //For granting permissions to the app.
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
        }
    }
}

@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast toast;
        switch (resultCode) {
            case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
                toast.show(); break;
            //Other Cases
        }
    }
}
</code>```

When I click on Calendar Button, the onCalendarClick() method run, but without asking for any permission, the App directly displays Calendar Permission Granted!! toast. In the App's settings, there are though No Permissions Granted/Requested being displayed.

Am I missing something or doing it the wrong way? Thanks for any help.

答:
So here it is. I found out that for android sdk > 22, though Runtime permissions are added programatically for your application but you still need to declare your app's permission in the AndroidManifest.xml file. So, after adding the code:

```<code><uses-permission android:name="android.permission.WRITE_CALENDAR"/>
</code>```

in the AndroidManifest.xml, the app asks for the permission and it's finally working.
For more information : Android M permission dialog not showing
.Thanks to all for helping me out )

Body:
I'm trying to test the Runtime Permissions specifically for Android sdk > 23. But my app is being granted permissions automatically without asking.

Note : I'm using sdk version 24. Here's a snippet of code I'm using:

public void onCalendarClick(View view) {
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager
            .PERMISSION_DENIED) {
       if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_CALENDAR)) {
            //Display Explanation to the user
            //For granting permissions to the app.
        }
        else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, CALLBACK_CALENDAR);
        }
    }
}

@Override
public void onRequestPermissionsResult(int resultCode, String permission[], int grantResults[]) {
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Toast toast;
        switch (resultCode) {
            case CALLBACK_CALENDAR : toast = Toast.makeText(this,"Calendar Permission Granted!!",Toast.LENGTH_LONG);
                toast.show(); break;
            //Other Cases
        }
    }
}

When I click on Calendar Button, the onCalendarClick() method run, but without asking for any permission, the App directly displays Calendar Permission Granted!! toast. In the App's settings, there are though No Permissions Granted/Requested being displayed.

Am I missing something or doing it the wrong way? Thanks for any help.

Body:
So here it is. I found out that for android sdk > 22, though Runtime permissions are added programatically for your application but you still need to declare your app's permission in the AndroidManifest.xml file. So, after adding the code:

<uses-permission android:name="android.permission.WRITE_CALENDAR"/>

in the AndroidManifest.xml, the app asks for the permission and it's finally working.
For more information : Android M permission dialog not showing
.Thanks to all for helping me out )


问:
C# Mono+Winforms MessageBox problem
I have a file called hellowf.cs

```<code>class MyFirstApp {
static void Main() {
     System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!");
   }
}
</code>```

On Ubuntu 8.10, I do the following

```<code>gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll
mono hellowf.exe
</code>```

... and it looks like this:

alt text http://img136.imageshack.us/img136/4674/helloproblemuk5.png

The second part of the message is missing. Why is this happening? The same binary - hellowf.exe - works fine on Windows.

Update:
This is really annoying. Here are the mono versions I have had and tried to make this work on so far:

```<code>    1.9.1 (from official ubuntu repo)
    2.0.1 (from some some 3rd party repo)
    2.2   (wiped every mono pkg and compiled myself)
</code>```

My Current mono version:

```<code>mono --version
Mono JIT compiler version 2.2 (tarball Wed Jan 14 22:58:21 CET 2009)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com
    TLS:           __thread
    GC:            Included Boehm (with typed GC)
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  x86
    Disabled:      none
gmcs --version
Mono C# compiler version 2.2.0.0
</code>```

... any clues?

答: stick an @ in front of the "Hello, Mono+WinForms!" and see if it still happens.</p>

Title: C# Mono+Winforms MessageBox problem

Body:
I have a file called hellowf.cs

class MyFirstApp {
static void Main() {
     System.Windows.Forms.MessageBox.Show("Hello, Mono+WinForms!");
   }
}

On Ubuntu 8.10, I do the following

gmcs hellowf.cs -r:System.Drawing.dll -r:System.Windows.Forms.dll
mono hellowf.exe

... and it looks like this:

alt text http://img136.imageshack.us/img136/4674/helloproblemuk5.png

The second part of the message is missing. Why is this happening? The same binary - hellowf.exe - works fine on Windows.

Update:
This is really annoying. Here are the mono versions I have had and tried to make this work on so far:

    1.9.1 (from official ubuntu repo)
    2.0.1 (from some some 3rd party repo)
    2.2   (wiped every mono pkg and compiled myself)

My Current mono version:

mono --version
Mono JIT compiler version 2.2 (tarball Wed Jan 14 22:58:21 CET 2009)
Copyright (C) 2002-2008 Novell, Inc and Contributors. www.mono-project.com
    TLS:           __thread
    GC:            Included Boehm (with typed GC)
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  x86
    Disabled:      none
gmcs --version
Mono C# compiler version 2.2.0.0

... any clues?

OwnerDisplayName: Tom Anderson


问:
Editable table in PHP
In a PHP application I'm building, I'd like to have an 'editable' table. The idea is that each row will have an edit button, which, when clicked, will replace certain fields with text fields and select lists and change to a save button. When the user clicks save, the data data should be validated and changed if appropriate.

I'm mainly tackling this as a learning project (I'm aware there's a ton of stuff already out there) and to see if I can get anything 'cool' working. I've created a PHP table-generating class that can take an array of objects as a datasource, and can have columns created based on those class methods.

e.g.

```<code>$table = new Table($dataSource);
$table->addColumn('Name', 'getName');
$table->addColumn('Amount Due', array('getOrdersManager', 'getTotalAmountDue')); //First calls getOrdersManager() on each data item and then calls the getTotalAmountDue() on the result
</code>```

I'd like to try my hand at extending this to be able to the table row and have those changes reflect on the corresponding object in the data source.

I don't really have very much experience with AJAX although it's clearly going to play a very important role in getting this to work correctly.

Any tips on how I should approach such a task?

Edit: I'm not really interesting in looking at Ajax libraries at this point (I do have some experience with jQuery). I'm more interested in learning the basics of Ajax at this point.

答:
my tip is to use jquery(does most of the heavy lifting for you and is easy to learn).

The idea is that each row will have an
  edit button, which, when clicked, will
  replace certain fields with text
  fields and select lists and change to
  a save button

http://api.jquery.com/click/

When the user clicks save, the data
  data should be validated and changed
  if appropriate.

http://api.jquery.com/jQuery.post/

Title: Editable table in PHP

Body:
In a PHP application I'm building, I'd like to have an 'editable' table. The idea is that each row will have an edit button, which, when clicked, will replace certain fields with text fields and select lists and change to a save button. When the user clicks save, the data data should be validated and changed if appropriate.

I'm mainly tackling this as a learning project (I'm aware there's a ton of stuff already out there) and to see if I can get anything 'cool' working. I've created a PHP table-generating class that can take an array of objects as a datasource, and can have columns created based on those class methods.

e.g.

$table = new Table($dataSource);
$table->addColumn('Name', 'getName');
$table->addColumn('Amount Due', array('getOrdersManager', 'getTotalAmountDue')); //First calls getOrdersManager() on each data item and then calls the getTotalAmountDue() on the result

I'd like to try my hand at extending this to be able to the table row and have those changes reflect on the corresponding object in the data source.

I don't really have very much experience with AJAX although it's clearly going to play a very important role in getting this to work correctly.

Any tips on how I should approach such a task?

Edit: I'm not really interesting in looking at Ajax libraries at this point (I do have some experience with jQuery). I'm more interested in learning the basics of Ajax at this point.


问:
Cannot identify error with code, failing a test case
I have to submit this code as a solution. My code runs perfectly for the given test cases, but I am not able to submit as the code fails one of the tests in the solver. Please help if you can. Any help is appreciated.

Gift Article with Digits

Many customers liked the gift articles with digits inscribed on them and they started buying them for gifting for Birthdays and anniversaries. One customer came to purchase a gift for his mom's 25th wedding anniversary and another customer came to purchase a gift for his son's 18th Birthday. They were disappointed to see only single digits inscribed on the gift items.

Seeing the craze for this kind of gift items, Nisha gave a bulk order for gift items with 2 digit numbers inscribed on them. The parcel arrived when she was busy and her 4 year old son started arranging the newly arrived items in the rack for display. But he has placed all items upside down. She needs to change the orientation of the items.

But to her surprise, she found that some 2-digit numbers were valid when read both ways. [Eg. 68 read upside down would be 89 which is also a valid number] Help Nisha in identifying all such 2 digit numbers.

TestCase

Input 1

18

Output 1

YES

Input 2

46

Output 2

NO

Input 3

a4

Output 3

Invalid Input

C code:

```<code>#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{

char str[2];

scanf("%s",str);

int flag=0;

if (strlen(str)!=2)
{
    flag=2;goto label;
}
else if (str[1]=='0')
{
    flag=1;goto label;
}

for(int i=0;i<2;i++)
{

    if(isdigit(str[i]))
    {
        if((str[i]!='0')&&(str[i]!='1')&&(str[i]!='6')&&(str[i]!='8')&&
    (str[i]!='9'))
        {
        flag=1;break;
        }

    }
    else
    {flag=2;break;}

    }

label:
if (flag==0) printf("YES");
else if (flag==1) printf("NO");
else if (flag==2) printf("Invalid Input");
return 0;
}
</code>```

The output after evaluation is as follows:

答:
You can try the below code!</p>

```<code>#include<stdio.h>
#include<string.h>
void main(){
char str[2];
int a,b;
scanf("%s",str);
a=str[0];
b=str[1];
if(strlen(str)!=2)
printf("Invalid Input");
else if(str[0]=='0')
printf("NO");
else if((a>47&&a<58)&&(b>47&&b<58))
{
    if(((str[0]=='1')||(str[0]=='6')||(str[0]=='8')||(str[0]=='9'))&&((str[1]=='1')||(str[1]=='6')||(str[1]=='8')||(str[1]=='9')))
    printf("YES");
    else
    printf("NO");
}
else
printf("Invalid Input");

}
</code>```

Body:
I have to submit this code as a solution. My code runs perfectly for the given test cases, but I am not able to submit as the code fails one of the tests in the solver. Please help if you can. Any help is appreciated.

Gift Article with Digits

Many customers liked the gift articles with digits inscribed on them and they started buying them for gifting for Birthdays and anniversaries. One customer came to purchase a gift for his mom's 25th wedding anniversary and another customer came to purchase a gift for his son's 18th Birthday. They were disappointed to see only single digits inscribed on the gift items.

Seeing the craze for this kind of gift items, Nisha gave a bulk order for gift items with 2 digit numbers inscribed on them. The parcel arrived when she was busy and her 4 year old son started arranging the newly arrived items in the rack for display. But he has placed all items upside down. She needs to change the orientation of the items.

But to her surprise, she found that some 2-digit numbers were valid when read both ways. [Eg. 68 read upside down would be 89 which is also a valid number] Help Nisha in identifying all such 2 digit numbers.

TestCase

Input 1

18

Output 1

YES

Input 2

46

Output 2

NO

Input 3

a4

Output 3

Invalid Input

C code:

#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{

char str[2];

scanf("%s",str);

int flag=0;

if (strlen(str)!=2)
{
    flag=2;goto label;
}
else if (str[1]=='0')
{
    flag=1;goto label;
}

for(int i=0;i<2;i++)
{

    if(isdigit(str[i]))
    {
        if((str[i]!='0')&&(str[i]!='1')&&(str[i]!='6')&&(str[i]!='8')&&
    (str[i]!='9'))
        {
        flag=1;break;
        }

    }
    else
    {flag=2;break;}

    }

label:
if (flag==0) printf("YES");
else if (flag==1) printf("NO");
else if (flag==2) printf("Invalid Input");
return 0;
}

The output after evaluation is as follows:

Body:
You can try the below code!

#include<stdio.h>
#include<string.h>
void main(){
char str[2];
int a,b;
scanf("%s",str);
a=str[0];
b=str[1];
if(strlen(str)!=2)
printf("Invalid Input");
else if(str[0]=='0')
printf("NO");
else if((a>47&&a<58)&&(b>47&&b<58))
{
    if(((str[0]=='1')||(str[0]=='6')||(str[0]=='8')||(str[0]=='9'))&&((str[1]=='1')||(str[1]=='6')||(str[1]=='8')||(str[1]=='9')))
    printf("YES");
    else
    printf("NO");
}
else
printf("Invalid Input");

}


问:
How can i get the label of a text field of existing fillable PDF file
I am having an fillable pdf file. I want to know the label name of the input variables.</p>

答:
Fields in PDF don't have visible labels like HTML. However, you can get the tooltip using code similar to below. You'll replace the field name with your own.

```<code>var tooltip = this.getField("myField").userName
</code>```

"userName" does not refer to the user, it refers to the name of the field that's presented to the user.

Body:
Fields in PDF don't have visible labels like HTML. However, you can get the tooltip using code similar to below. You'll replace the field name with your own.

var tooltip = this.getField("myField").userName

"userName" does not refer to the user, it refers to the name of the field that's presented to the user.


问:
Delete string match from another file
i have 1.txt:

```<code>hi aa my name is bb tom
how are you cc today
</code>```

and i have 2.txt ( the word that i dont want )

```<code>aa
bb
cc
</code>```

and my expected output is

```<code>hi my name is tom
how are you today
</code>```

what i have tried so far is

```<code>sed -e "s/$(sed 's:/:\\/:g' 2.txt)/ /"
or
grep -Fvf 2.txt 1.txt
</code>```

i have more than 100 words that i dont want, so i have to put it in one sentence, thanks

答:
without normalizing spaces...

```<code>$ sed -f <(sed 's/.*/s_\\b&\\b__g/' remove_list) file

hi  my name is  tom
how are you  today
aardwark
</code>```

to handle spaces and word boundaries, one alternative

```<code>$ sed -f <(sed 's/.*/s_ &\\b__g;s_\\b& __g;s_\\b&\\b__g/' remove) file
</code>```

however, at this point it's better to switch to awk

Title: Delete string match from another file

Body:
i have 1.txt:

hi aa my name is bb tom
how are you cc today

and i have 2.txt ( the word that i dont want )

aa
bb
cc

and my expected output is

hi my name is tom
how are you today

what i have tried so far is

sed -e "s/$(sed 's:/:\\/:g' 2.txt)/ /"
or
grep -Fvf 2.txt 1.txt

i have more than 100 words that i dont want, so i have to put it in one sentence, thanks

Body:
without normalizing spaces...

$ sed -f <(sed 's/.*/s_\\b&\\b__g/' remove_list) file

hi  my name is  tom
how are you  today
aardwark

to handle spaces and word boundaries, one alternative

$ sed -f <(sed 's/.*/s_ &\\b__g;s_\\b& __g;s_\\b&\\b__g/' remove) file

however, at this point it's better to switch to awk


问:
Find dup records with different extensions in SQL Server
I have a subscriptions table. Sample records:

```<code>  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R
</code>```

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

答:
You can use row_Number and partition by as below:</p>

```<code>Select * from (
    Select *, DupeRecords = Row_number() over(partition by replace([Subs Name],'-R','') order by Subs_Id)
       from #yoursubs
   ) a Where a.DupeRecords > 1
</code>```

Body:
I have a subscriptions table. Sample records:

  SUBS_ID    |   SUBS Name
     1       |   SC FORM 124
     2       |   SC FORM 124-R

I need to find both the records, as the subscription name is exactly the same but just with an extension-R.

Body:
You can use row_Number and partition by as below:

Select * from (
    Select *, DupeRecords = Row_number() over(partition by replace([Subs Name],'-R','') order by Subs_Id)
       from #yoursubs
   ) a Where a.DupeRecords > 1


问:
Change VM options generte a error
I changed vm options and add Xxs16m , now when i try open idea.sh i have this error in console.

Unrecognized option: -Xxs16m
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

答: As the error says, there's no such option as -Xxs[size]. I'm guessing you meant to configure the minimal heap size, which would be -Xms16m.

Title: Change VM options generte a error


问:
How to get a uniform distribution in a range [r1,r2] in PyTorch?
I want to get a 2-D torch.Tensor with size [a,b] filled with values from a uniform distribution (in range [r1,r2]) in PyTorch.

答:
If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].

Thus, you just need:

```<code>(r1 - r2) * torch.rand(a, b) + r2
</code>```

Alternatively, you can simply use:

```<code>torch.FloatTensor(a, b).uniform_(r1, r2)
</code>```

To fully explain this formulation, let's look at some concrete numbers:

r1 = 2 # Create uniform random numbers in half-open interval [2.0, 5.0)
r2 = 5

a = 1  # Create tensor shape 1 x 7
b = 7
```

<p>We can break down the expression <code>(r1 - r2) * torch.rand(a, b) + r2</code> as follows:</p>

<ol>
<li><code>torch.rand(a, b)</code> produces an <code>a x b</code> (1x7) tensor with numbers uniformly distributed in the range [0.0, 1.0).</li>
</ol>

<pre class="lang-py prettyprint-override"><code>x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])
</code>```

(r1 - r2) * torch.rand(a, b) produces numbers distributed in the uniform range [0.0, -3.0)

print((r1 - r2) * x)
tensor([[-1.7014, -2.9441, -2.4972, -0.0722, -0.6216, -1.8577, -1.4112]])
```

<ol start="3">
<li><code>(r1 - r2) * torch.rand(a, b) + r2</code> produces numbers in the uniform range [5.0, 2.0)</li>
</ol>

<pre class="lang-py prettyprint-override"><code>print((r1 - r2) * x + r2)
tensor([[3.2986, 2.0559, 2.5028, 4.9278, 4.3784, 3.1423, 3.5888]])
</code>```

Now, let's break down the answer suggested by @Jonasson: (r2 - r1) * torch.rand(a, b) + r1

Again, torch.rand(a, b) produces (1x7) numbers uniformly distributed in the range [0.0, 1.0).

x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])
```

<ol start="2">
<li><code>(r2 - r1) * torch.rand(a, b)</code> produces numbers uniformly distributed in the range [0.0, 3.0).</li>
</ol>

<pre class="lang-py prettyprint-override"><code>print((r2 - r1) * x)
# tensor([[1.7014, 2.9441, 2.4972, 0.0722, 0.6216, 1.8577, 1.4112]])
</code>```

(r2 - r1) * torch.rand(a, b) + r1 produces numbers uniformly distributed in the range [2.0, 5.0)

print((r2 - r1) * x + r1)
tensor([[3.7014, 4.9441, 4.4972, 2.0722, 2.6216, 3.8577, 3.4112]])
```

In summary, (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the range [r2, r1), while (r2 - r1) * torch.rand(a, b) + r1 produces numbers in the range [r1, r2).

ContentLicense: CC BY-SA 4.0

Body:
If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].

Thus, you just need:

(r1 - r2) * torch.rand(a, b) + r2

Alternatively, you can simply use:

torch.FloatTensor(a, b).uniform_(r1, r2)

To fully explain this formulation, let's look at some concrete numbers:

r1 = 2 # Create uniform random numbers in half-open interval [2.0, 5.0)
r2 = 5

a = 1  # Create tensor shape 1 x 7
b = 7

We can break down the expression (r1 - r2) * torch.rand(a, b) + r2 as follows:

torch.rand(a, b) produces an a x b (1x7) tensor with numbers uniformly distributed in the range [0.0, 1.0).

x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])

(r1 - r2) * torch.rand(a, b) produces numbers distributed in the uniform range [0.0, -3.0)

print((r1 - r2) * x)
tensor([[-1.7014, -2.9441, -2.4972, -0.0722, -0.6216, -1.8577, -1.4112]])

(r1 - r2) * torch.rand(a, b) + r2 produces numbers in the uniform range [5.0, 2.0)

print((r1 - r2) * x + r2)
tensor([[3.2986, 2.0559, 2.5028, 4.9278, 4.3784, 3.1423, 3.5888]])

Now, let's break down the answer suggested by @Jonasson: (r2 - r1) * torch.rand(a, b) + r1

Again, torch.rand(a, b) produces (1x7) numbers uniformly distributed in the range [0.0, 1.0).

x = torch.rand(a, b)
print(x)
# tensor([[0.5671, 0.9814, 0.8324, 0.0241, 0.2072, 0.6192, 0.4704]])

(r2 - r1) * torch.rand(a, b) produces numbers uniformly distributed in the range [0.0, 3.0).

print((r2 - r1) * x)
# tensor([[1.7014, 2.9441, 2.4972, 0.0722, 0.6216, 1.8577, 1.4112]])

(r2 - r1) * torch.rand(a, b) + r1 produces numbers uniformly distributed in the range [2.0, 5.0)

print((r2 - r1) * x + r1)
tensor([[3.7014, 4.9441, 4.4972, 2.0722, 2.6216, 3.8577, 3.4112]])

In summary, (r1 - r2) * torch.rand(a, b) + r2 produces numbers in the range [r2, r1), while (r2 - r1) * torch.rand(a, b) + r1 produces numbers in the range [r1, r2).


问:
Using iterative variable from C# for loop in JavaScript function
On one of my pages I have a for loop to iterate through a list of "Projects" (which is the main model for my website) and display some of their data. The following code is nested in a table and the middle cells removed for redundancy.

```<code>foreach (var item in Model.Projects)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.SubmissionNumber)</td>
        <td>@Html.DisplayFor(modelItem => item.Status)</td>
        <!-- and so on -->
        <td>@Html.ActionLink("Detail", "DisplayDetails", new { id = item.ProjectID })</td>
    </tr>
}
</code>```

The "Detail" link in the last cell will ideally make a box pop up (I'm thinking of using a Modal via Bootstrap) containing all of the data for the project. The "DisplayDetails" controller action returns a partial view that presents this information, but since I'm not using JavaScript or anything to render the partial view on the current page it renders it as it's own unformatted page. This is the controller action:

```<code>[HttpGet]
public ActionResult DisplayDetails(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Project project = db.Projects.Find(id);
    if (project == null)
    {
        return HttpNotFound();
    }
    return PartialView("~/Views/Projects/_Detail.cshtml", project);
}
</code>```

Ideally I would pass the ID to the controller using AJAX like I did below (which is code from another page of my website, again edited to remove redudancy):

```<code>$("#show").on("click", function () {
    $.ajax({
        url: '/Projects/SearchTable',
        type: "GET",
        data: {
            Line1: $('#' + '@Html.IdFor(m => m.Project.ProjectAddress.Line1)').val(),
            // and so on
            County: $('#' + '@Html.IdFor(m => m.Project.ProjectAddress.County)').val(),
        }
    }).done(function(partialViewResult) {
        $(".wrapper").html(partialViewResult);
        $(".wrapper").css('display', 'block');
    });
});
</code>```

And by doing this I can embed the partial view onto the current page instead of it opening as a new page. I'm just not sure how to pass the project ID for a specific row in the table as data to the controller. Is this even possible? If not is there another way to achieve the same result?

答:
You can replace your ActionLink with this:

```<code><td><a href="#" class="details" data-id="@item.ProjectID">Details</a></td>
</code>```

Then,

```<code>$(".details").on("click", function (e) {
    e.preventDefault();
    var projectId = $(this).data('id');
    // Make the AJAX call here...
});
</code>```

Body:
On one of my pages I have a for loop to iterate through a list of "Projects" (which is the main model for my website) and display some of their data. The following code is nested in a table and the middle cells removed for redundancy.

foreach (var item in Model.Projects)
{

        @Html.DisplayFor(modelItem => item.SubmissionNumber)
        @Html.DisplayFor(modelItem => item.Status)

        @Html.ActionLink("Detail", "DisplayDetails", new { id = item.ProjectID })

}

The "Detail" link in the last cell will ideally make a box pop up (I'm thinking of using a Modal via Bootstrap) containing all of the data for the project. The "DisplayDetails" controller action returns a partial view that presents this information, but since I'm not using JavaScript or anything to render the partial view on the current page it renders it as it's own unformatted page. This is the controller action:

[HttpGet]
public ActionResult DisplayDetails(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Project project = db.Projects.Find(id);
    if (project == null)
    {
        return HttpNotFound();
    }
    return PartialView("~/Views/Projects/_Detail.cshtml", project);
}

Ideally I would pass the ID to the controller using AJAX like I did below (which is code from another page of my website, again edited to remove redudancy):

$("#show").on("click", function () {
    $.ajax({
        url: '/Projects/SearchTable',
        type: "GET",
        data: {
            Line1: $('#' + '@Html.IdFor(m => m.Project.ProjectAddress.Line1)').val(),
            // and so on
            County: $('#' + '@Html.IdFor(m => m.Project.ProjectAddress.County)').val(),
        }
    }).done(function(partialViewResult) {
        $(".wrapper").html(partialViewResult);
        $(".wrapper").css('display', 'block');
    });
});

And by doing this I can embed the partial view onto the current page instead of it opening as a new page. I'm just not sure how to pass the project ID for a specific row in the table as data to the controller. Is this even possible? If not is there another way to achieve the same result?

Body:
You can replace your ActionLink with this:

<td><a href="#" class="details" data-id="@item.ProjectID">Details</a></td>

Then,

$(".details").on("click", function (e) {
    e.preventDefault();
    var projectId = $(this).data('id');
    // Make the AJAX call here...
});


问:
How to resize the image programmatically in objective-c in iphone
I have an application where I am displaying large images in a small space.
The images are quite large, but I am only displaying them in 100x100 pixel frames.
My app is responding slowly because of the size fo the images I am using.

To improve performance, how can I resize the images programmatically using Objective-C?

答:
```<code>   -(UIImage *)scaleImage:(UIImage *)image toSize:.     (CGSize)targetSize
   {
//If scaleFactor is not touched, no scaling will occur
   CGFloat scaleFactor = 1.0;

//Deciding which factor to use to scale the image (factor = targetSize / imageSize)
if (image.size.width > targetSize.width ||
   image.size.height > targetSize.height || image.size.width == image.size.height)
    if (!((scaleFactor = (targetSize.width /
    image.size.width)) > (targetSize.height /
      image.size.height))) //scale to fit width, or
        scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
</code>```


问:
NSAutolayoutConstraint - Apply constant before multiplier
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)
</code>```

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)
</code>```

Because I end up losing the constraint.constant that comes from the storyboard.

答:
Let's say your superView is main screen.</p>

```<code>newConstraint.constant = (UIScreen.mainScreen().bounds.size.width - 2) * your_multiplier
</code>```

Body:
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)

Because I end up losing the constraint.constant that comes from the storyboard.

Body:
Let's say your superView is main screen.

newConstraint.constant = (UIScreen.mainScreen().bounds.size.width - 2) * your_multiplier


问:
Android Quiz app crashing while updating score
The submit button id is ShowScore
correct answers are right1,right2...right53
when the button is clicked the app crashes...
android studios doest show any errors
right answer awards 1 point
wrong answer is -1
please help me out    </p>

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int score = 0;

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

    public void setScore() {
        RadioButton check1 = (RadioButton) findViewById(R.id.right1);
        boolean doit1 = check1.isChecked();
        RadioButton check2 = (RadioButton) findViewById(R.id.right2);
        boolean doit2 = check2.isChecked();
        RadioButton check3 = (RadioButton) findViewById(R.id.right3);
        boolean doit3 = check3.isChecked();
        RadioButton check4 = (RadioButton) findViewById(R.id.right4);
        boolean doit4 = check4.isChecked();
        CheckBox check5 = (CheckBox) findViewById(R.id.right51);
        boolean doit5 = check5.isChecked();
        CheckBox check52 = (CheckBox) findViewById(R.id.right52);
        boolean doit52 = check52.isChecked();
        CheckBox check53 = (CheckBox) findViewById(R.id.right53);
        boolean doit53 = check53.isChecked();
        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();

    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;

        }
        return score;

    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;

    }

    private void showScore() {
        TextView olds = (TextView) findViewById(R.id.ShowScore);
        olds.setText(score);
    }
}
</code>```

答:
#. I guess you have defined setScore() method to SUBMIT Button in your XML using attribute android:onClick="setScore". But your method doesn't have any View parameter. Update your method as below:

```<code>    public void setScore(View v) {
        ..........
        .............
    }
</code>```

#. As score is an int value, use olds.setText(String.valueOf(score)) to set score on TextView.

Here is the full code:

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView olds;
    RadioButton check1, check2, check3, check4;
    CheckBox check5, check52, check53;

    int score = 0;

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

        olds = (TextView) findViewById(R.id.ShowScore);
        check1 = (RadioButton) findViewById(R.id.right1);
        check2 = (RadioButton) findViewById(R.id.right2);
        check3 = (RadioButton) findViewById(R.id.right3);
        check4 = (RadioButton) findViewById(R.id.right4);
        check5 = (CheckBox) findViewById(R.id.right51);
        check52 = (CheckBox) findViewById(R.id.right52);
        check53 = (CheckBox) findViewById(R.id.right53);
    }

    public void setScore(View v) {

        boolean doit1 = check1.isChecked();
        boolean doit2 = check2.isChecked();
        boolean doit3 = check3.isChecked();
        boolean doit4 = check4.isChecked();
        boolean doit5 = check5.isChecked();
        boolean doit52 = check52.isChecked();
        boolean doit53 = check53.isChecked();

        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();
    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private void showScore() {
        olds.setText(String.valueOf(score));
    }
}
</code>```

Body:
The submit button id is ShowScore
correct answers are right1,right2...right53
when the button is clicked the app crashes...
android studios doest show any errors
right answer awards 1 point
wrong answer is -1
please help me out

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int score = 0;

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

    public void setScore() {
        RadioButton check1 = (RadioButton) findViewById(R.id.right1);
        boolean doit1 = check1.isChecked();
        RadioButton check2 = (RadioButton) findViewById(R.id.right2);
        boolean doit2 = check2.isChecked();
        RadioButton check3 = (RadioButton) findViewById(R.id.right3);
        boolean doit3 = check3.isChecked();
        RadioButton check4 = (RadioButton) findViewById(R.id.right4);
        boolean doit4 = check4.isChecked();
        CheckBox check5 = (CheckBox) findViewById(R.id.right51);
        boolean doit5 = check5.isChecked();
        CheckBox check52 = (CheckBox) findViewById(R.id.right52);
        boolean doit52 = check52.isChecked();
        CheckBox check53 = (CheckBox) findViewById(R.id.right53);
        boolean doit53 = check53.isChecked();
        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();

    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;

        }
        return score;

    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;

    }

    private void showScore() {
        TextView olds = (TextView) findViewById(R.id.ShowScore);
        olds.setText(score);
    }
}

Body:
#. I guess you have defined setScore() method to SUBMIT Button in your XML using attribute android:onClick="setScore". But your method doesn't have any View parameter. Update your method as below:

    public void setScore(View v) {
        ..........
        .............
    }

#. As score is an int value, use olds.setText(String.valueOf(score)) to set score on TextView.

Here is the full code:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView olds;
    RadioButton check1, check2, check3, check4;
    CheckBox check5, check52, check53;

    int score = 0;

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

        olds = (TextView) findViewById(R.id.ShowScore);
        check1 = (RadioButton) findViewById(R.id.right1);
        check2 = (RadioButton) findViewById(R.id.right2);
        check3 = (RadioButton) findViewById(R.id.right3);
        check4 = (RadioButton) findViewById(R.id.right4);
        check5 = (CheckBox) findViewById(R.id.right51);
        check52 = (CheckBox) findViewById(R.id.right52);
        check53 = (CheckBox) findViewById(R.id.right53);
    }

    public void setScore(View v) {

        boolean doit1 = check1.isChecked();
        boolean doit2 = check2.isChecked();
        boolean doit3 = check3.isChecked();
        boolean doit4 = check4.isChecked();
        boolean doit5 = check5.isChecked();
        boolean doit52 = check52.isChecked();
        boolean doit53 = check53.isChecked();

        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();
    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private void showScore() {
        olds.setText(String.valueOf(score));
    }
}


问:
Java cannot send email with html with images
I am trying to send email with html which has two images. The two images are sent from the AngularJS client side as base64 strings and looks like:

```<code>data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAALuCAYAAAA9jTxNAAAgAElEQ
</code>```

Note that I have truncated the base64 string as its too long.

```<code>String temp = baseString.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);

BodyPart messageBodyPart = new MimeBodyPart();
InputStream inputStream = new ByteArrayInputStream(tile);
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);
</code>```

The InputStreamDataSource:

```<code>public class InputStreamDataSource implements DataSource {

    private InputStream inputStream;

    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    public String getContentType() {
        return "*/*";
    }

    public String getName() {
        return "InputStreamDataSource";
    }
}
</code>```

The image does not show up in the mail.

But it works perfectly fine when I use a FileDataSource instead of base64 string:

```<code>    DataSource fds = new FileDataSource("D:\\Projects\\Extras\\sofa1.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    multipart.addBodyPart(messageBodyPart);
</code>```

This works fine and shows the images.

Someone please help me fix this.

答:
Use ByteArrayDataSource instead of your own InputStreamDataSource.

Your code only shows one image; hopefully you're using different Content-IDs for each image.

Your code also doesn't should how the html content is referencing the images; hopefully it's using the correct "cid:" URL.

The JavaMail FAQ has more information on how to send messages that include images.

Body:
I am trying to send email with html which has two images. The two images are sent from the AngularJS client side as base64 strings and looks like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAALuCAYAAAA9jTxNAAAgAElEQ

Note that I have truncated the base64 string as its too long.

String temp = baseString.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);

BodyPart messageBodyPart = new MimeBodyPart();
InputStream inputStream = new ByteArrayInputStream(tile);
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);

The InputStreamDataSource:

public class InputStreamDataSource implements DataSource {

    private InputStream inputStream;

    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    public String getContentType() {
        return "*/*";
    }

    public String getName() {
        return "InputStreamDataSource";
    }
}

The image does not show up in the mail.

But it works perfectly fine when I use a FileDataSource instead of base64 string:

    DataSource fds = new FileDataSource("D:\\Projects\\Extras\\sofa1.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    multipart.addBodyPart(messageBodyPart);

This works fine and shows the images.

Someone please help me fix this.


问:
Narrow results by typing case sensitivity issue
I have a search box that limits options available in a dropdown menu on keyup. I'm having an issue with case sensitivity - how can I modify this function to ensure my option contains upper or lower case versions of the character typed?

Fiddle: https://jsfiddle.net/g2q8hvf4/

Notice how the results differ between 'i' and 'I'

$(document).on('keyup', '#condition-search', function(e) {
  var str = $('#condition option:contains(' + $(this).val() + ')');
  if (str) {
    $('#condition option').hide();
    str.show();
  } else {
    $('#condition option').show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="condition-search">
<select class="form-control" id="condition" size="15" style="overflow-y: scroll" ;>
        <option class="cat-1">Item1</option>
        <option class="cat-2">item2</option>
        <option class="cat-3">Item3</option>
        <option class="cat-4">item4</option>
        <option class="cat-5">Item5</option>
    </select></code>```

答:
You can use the filter() method and convert both the query and the current text to lower case before comparing:

$(document).on('keyup', '#condition-search', function(e) {
  var query = $(this).val().toLowerCase();
  var str = $('#condition option').filter(function () {
    return $(this).text().toLowerCase().includes(query);
  });
  if (str) {
    $('#condition option').hide();
    str.show();
  } else {
    $('#condition option').show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="condition-search">
<select class="form-control" id="condition" size="15" style="overflow-y: scroll" ;>
        <option class="cat-1">Item1</option>
        <option class="cat-2">item2</option>
        <option class="cat-3">Item3</option>
        <option class="cat-4">item4</option>
        <option class="cat-5">Item5</option>
    </select></code>```

Body:
I have a search box that limits options available in a dropdown menu on keyup. I'm having an issue with case sensitivity - how can I modify this function to ensure my option contains upper or lower case versions of the character typed?

Fiddle: https://jsfiddle.net/g2q8hvf4/

Notice how the results differ between 'i' and 'I'

$(document).on('keyup', '#condition-search', function(e) {
  var str = $('#condition option:contains(' + $(this).val() + ')');
  if (str) {
    $('#condition option').hide();
    str.show();
  } else {
    $('#condition option').show();
  }
});

<input type="text" class="form-control" id="condition-search">
<select class="form-control" id="condition" size="15" style="overflow-y: scroll" ;>
        <option class="cat-1">Item1</option>
        <option class="cat-2">item2</option>
        <option class="cat-3">Item3</option>
        <option class="cat-4">item4</option>
        <option class="cat-5">Item5</option>
    </select>

Body:
You can use the filter() method and convert both the query and the current text to lower case before comparing:

$(document).on('keyup', '#condition-search', function(e) {
  var query = $(this).val().toLowerCase();
  var str = $('#condition option').filter(function () {
    return $(this).text().toLowerCase().includes(query);
  });
  if (str) {
    $('#condition option').hide();
    str.show();
  } else {
    $('#condition option').show();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="condition-search">
<select class="form-control" id="condition" size="15" style="overflow-y: scroll" ;>
        <option class="cat-1">Item1</option>
        <option class="cat-2">item2</option>
        <option class="cat-3">Item3</option>
        <option class="cat-4">item4</option>
        <option class="cat-5">Item5</option>
    </select>


答: I'd compare the entered string in its lowercase version (using javascript's toLowercase() ) to your available list item's lowercase versions.

Title: Narrow results by typing case sensitivity issue


问:
How to auto create Sheet Name based in names in column A in Sheet1 in google spreadsheet?
I'm still learning GoogleApp scripting by myself. Can anyone guide me in the right direction how to edit the below script in such a way that instead of naming the new sheet as per the current date, it takes the names from the column A of Sheet1 and then rename it.

Note that i keep on updating column A with new name in new cells down the column off an on.

Thank you for your help in advance!

This is the script I have which works for dates only:

```<code>function onOpen() {
var menu = [{name: "Add", functionName: "newSheet"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
var sheetName = formatDate();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getActiveSheet();
ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
}

function formatDate() {
var month, day, d = new Date();
month = ('0'+(d.getUTCMonth()+1)).slice(-2);
day = ('0'+d.getUTCDate()).slice(-2);
return d.getUTCFullYear()+'-'+month+'-'+day;
}
</code>```

答:
See if this works out for you.</p>

```<code>function onOpen() {
  var menu = [{name: "Add", functionName: "newSheet"}];
  SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet()
{
  var sp = SpreadsheetApp.getActiveSpreadsheet();
  var sheetnameobj = sp.getSheetByName("Sheet1");
  //You can place a for loop here, if you want to create multiple sheets
  var newsheetname = sheetnameobj.getRange("A2").getValue();//Get Name of Your New Sheet From Column A of Sheet1

  sp.insertSheet(newsheetname);
}
</code>```

Body:
I'm still learning GoogleApp scripting by myself. Can anyone guide me in the right direction how to edit the below script in such a way that instead of naming the new sheet as per the current date, it takes the names from the column A of Sheet1 and then rename it.

Note that i keep on updating column A with new name in new cells down the column off an on.

Thank you for your help in advance!

This is the script I have which works for dates only:

function onOpen() {
var menu = [{name: "Add", functionName: "newSheet"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet() {
var sheetName = formatDate();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getActiveSheet();
ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
}

function formatDate() {
var month, day, d = new Date();
month = ('0'+(d.getUTCMonth()+1)).slice(-2);
day = ('0'+d.getUTCDate()).slice(-2);
return d.getUTCFullYear()+'-'+month+'-'+day;
}

Body:
See if this works out for you.

function onOpen() {
  var menu = [{name: "Add", functionName: "newSheet"}];
  SpreadsheetApp.getActiveSpreadsheet().addMenu("Sheet", menu);
}

function newSheet()
{
  var sp = SpreadsheetApp.getActiveSpreadsheet();
  var sheetnameobj = sp.getSheetByName("Sheet1");
  //You can place a for loop here, if you want to create multiple sheets
  var newsheetname = sheetnameobj.getRange("A2").getValue();//Get Name of Your New Sheet From Column A of Sheet1

  sp.insertSheet(newsheetname);
}


问:
Sort table by integer value stored in varchar field
Me working in spring hibernate

I have column in my database table, that of type VARCHAR, but it store integer value. So if i sort it using sql or hql or Criteria(Order.asc), all are sorting it as string. I need it to be sorted as integer value it store. Here i cannot alter my table.

Is There anyway to sort it as integer using Criteria

Is the only solution for me is, after reading it to some list and sort inside my service?

Edited : me using MYSQL

Thank you

答:
SQL:</p>

```<code>SELECT CAST(t.order AS UNSIGNED INTEGER) AS intOrder
    FROM myTable t ORDER BY intOrder ASC
</code>```

Body:
SQL:

SELECT CAST(t.order AS UNSIGNED INTEGER) AS intOrder
    FROM myTable t ORDER BY intOrder ASC


问:
PHP Fatal error: Allowed memory size of 268435456 bytes exhausted
I am getting the following error when clicking on a category named Test

FastCGI sent in stderr:

PHP message: PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in /home/mydomain/public_html/app/functions/fn.catalog.php on line 736" while reading response header from upstream, client: 24.xx.xx.xx, server: www.mydomain.com, request: "GET /test-page-313/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "www.mydomain.com", referrer: "http://www.mydomain....lesale-towels/"

My 736 Line is as follows

In my php.ini I've already increase the memory_limit to = 1G

```<code>for ($qty = $min_qty; $qty <= $max_qty; $qty += $product['qty_step']) {
    $qty_content[] = $qty;
}
</code>```

答:
Several possibilities :

$product['qty_step'] doesn't contain a number

There are two many steps in your loop that makes your program creating many entries in the $qty_content array.

For example, if you have:

```<code>$min_qty = 0;
$max_qty = 400000;
$product = array("qty_step" => 0.001);
$qty_content = [];

// The loop
for ($qty = $min_qty; $qty <= $max_qty; $qty += $product['qty_step']) {
    $qty_content[] = $qty;
}
</code>```

The program will try to make up to 400000000 entries in the array, which takes so much memory that PHP can't handle it. So it throws the error you've got. As someones said in your question's comments, try to debug the content of all variables, for example:

```<code>var_dump(
  array('qty' => $qty,
    'min_qty' => $min_qty,
    'max_qty' => $max_qty,
    'product["qty_step"]' => $product['qty_step'])
);
</code>```

And see what you get. In all cases, this error means you're taking too much memory, so you must reduce the loop's iterations by increasing $product['qty_step'] or reducing the difference between $min_qty and $max_qty.

Body:
I am getting the following error when clicking on a category named Test

FastCGI sent in stderr:

PHP message: PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in /home/mydomain/public_html/app/functions/fn.catalog.php on line 736" while reading response header from upstream, client: 24.xx.xx.xx, server: www.mydomain.com, request: "GET /test-page-313/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "www.mydomain.com", referrer: "http://www.mydomain....lesale-towels/"

My 736 Line is as follows

In my php.ini I've already increase the memory_limit to = 1G

for ($qty = $min_qty; $qty <= $max_qty; $qty += $product['qty_step']) {
    $qty_content[] = $qty;
}

Body:
Several possibilities :

$product['qty_step'] doesn't contain a number

There are two many steps in your loop that makes your program creating many entries in the $qty_content array.

For example, if you have:

$min_qty = 0;
$max_qty = 400000;
$product = array("qty_step" => 0.001);
$qty_content = [];

// The loop
for ($qty = $min_qty; $qty <= $max_qty; $qty += $product['qty_step']) {
    $qty_content[] = $qty;
}

The program will try to make up to 400000000 entries in the array, which takes so much memory that PHP can't handle it. So it throws the error you've got. As someones said in your question's comments, try to debug the content of all variables, for example:

var_dump(
  array('qty' => $qty,
    'min_qty' => $min_qty,
    'max_qty' => $max_qty,
    'product["qty_step"]' => $product['qty_step'])
);

And see what you get. In all cases, this error means you're taking too much memory, so you must reduce the loop's iterations by increasing $product['qty_step'] or reducing the difference between $min_qty and $max_qty.


问:
how to inject Environment on application context
I'm currently working with legacy code and I wanna read some properties from the Environment. I know this would be easily done using spring boot with:

```<code>@Autowired
Environment environment;
</code>```

But, since I'm wiring all the components using an application-context.xml file, I don't know how to wire the Environment there,

```<code><bean name="myBean" class="com.acme.MyClass">
???
</bean>
</code>```

答:
It seems that you have no experience in Spring XML config. You should look at this example by Spring team: https://spring.io/blog/2011/01/04/green-beans-getting-started-with-spring-mvc/

You need something like this in your application-context.xml:

```<code><!-- Scans within the base package of the application for @Components
to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="xyz.sample.baremvc" />

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
</code>```

Now your,

```<code>@Autowired
Environment environment
</code>```

should work!

Body:
I'm currently working with legacy code and I wanna read some properties from the Environment. I know this would be easily done using spring boot with:

@Autowired
Environment environment;

But, since I'm wiring all the components using an application-context.xml file, I don't know how to wire the Environment there,

<bean name="myBean" class="com.acme.MyClass">
???
</bean>

Body:
It seems that you have no experience in Spring XML config. You should look at this example by Spring team: https://spring.io/blog/2011/01/04/green-beans-getting-started-with-spring-mvc/

You need something like this in your application-context.xml:

<!-- Scans within the base package of the application for @Components
to configure as beans -->
<!-- @Controller, @Service, @Configuration, etc. -->
<context:component-scan base-package="xyz.sample.baremvc" />

<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />

Now your,

@Autowired
Environment environment

should work!