问:
Setting an enum by int value
I have an enum with an int value for storage in a DB:

```<code>public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}
</code>```

And here is a setter for this enum:

```<code>private DayType dayType

public void setDayType(int dayType) {

     switch(dayType) {
        case 1:
            this.dayType = DayType.REGULAR;
            break;

        case 2:
            this.dayType = DayType.VACATION;
            break;

        case 3:
            this.dayType = DayType.SICK;
            break;

        default :
            this.dayType = DayType.REGULAR;
            break;
    }
</code>```

Everything works just fine. But there has to be a more "pretty" way to write the setter if there is a int value for each enum value. Without using switch case...

答:
You can avoid use of switch statement by using

```<code>public void setDayType(int type) {

    for(DayType dayType : DayType.values()) {
        if(dayType.getValue() == type) {
            this.dayType = dayType;
        }
    }
}
</code>```

If you needed performance rather than memory you can use HashMap:

```<code>private HashMap<Integer, DayType> dayTypes;

private void initDayTypes() {

    for(DayType type : DayType.values()) {
        dayTypes.put(type.value, type);
    }
}
</code>```

Usage will be the next:

```<code>public void setDayType(int type) {

    this.dayType = dayTypes.get(type);
}
</code>```

Title: Setting an enum by int value

Body:
I have an enum with an int value for storage in a DB:

public enum DayType {
    REGULAR(1), VACATION(2), SICK(3);

    private final int value;
    private DayType(int value)
    {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

And here is a setter for this enum:

private DayType dayType

public void setDayType(int dayType) {

     switch(dayType) {
        case 1:
            this.dayType = DayType.REGULAR;
            break;

        case 2:
            this.dayType = DayType.VACATION;
            break;

        case 3:
            this.dayType = DayType.SICK;
            break;

        default :
            this.dayType = DayType.REGULAR;
            break;
    }

Everything works just fine. But there has to be a more "pretty" way to write the setter if there is a int value for each enum value. Without using switch case...

Body:
You can avoid use of switch statement by using

public void setDayType(int type) {

    for(DayType dayType : DayType.values()) {
        if(dayType.getValue() == type) {
            this.dayType = dayType;
        }
    }
}

If you needed performance rather than memory you can use HashMap:

private HashMap<Integer, DayType> dayTypes;

private void initDayTypes() {

    for(DayType type : DayType.values()) {
        dayTypes.put(type.value, type);
    }
}

Usage will be the next:

public void setDayType(int type) {

    this.dayType = dayTypes.get(type);
}


来源: stackexchange

问:
Selecting specific part of an HTML text
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script id="hello">

    </script>
</head>
<body>

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

For example, I want to get the body and save it in a new variable:

```<code>var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
</code>```

Where data is the HTML text as a string that the original function is returning.

Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??

Thank you very much

答:
```<code>var newVar = $("#hello").html();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Selecting specific part of an HTML text

Body:
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

For example, I want to get the body and save it in a new variable:

var body = data.split("").slice(1).join(">").split("")[0];

Where data is the HTML text as a string that the original function is returning.

Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??

Thank you very much

Body: var newVar = $("#hello").html();


问:
How to automate app versioning in Android
I have a CI tool(Bamboo) which runs my Unit Tests and builds the app-release.apk. Whenever I make changes in my app and the build in successful I create a new Version number.I store the version number and build time in a file. Can I make Gradle to read from that file and change the app version accordingly?

Content of my file looks like this:

```<code>ProductVersion=0.0.0.0.0
ProductBuildDateTime=2017-01-01T00:00:00.000
</code>```

答:
Yes of course, this is how I do it:

I store my versions in a version.properties file.

Then in the app's build.gradle I use the following code:

```<code>//Path to the file of your properties file that contains the version number
final String VERSION_PROPERTIES_FILE = projectDir.getParentFile().getParent() + "/file.properties"

 /**
 * Returns the id of the property name from config file, null if it doesn't exist
     * @param propertyName
     * @param properties file name in assets dir
     * @return
     */
    def getPropertyFromFile(propertiesFilePath, propertyName) {
        def propsFile = new File(propertiesFilePath);
        if (propsFile.canRead()) {
            def props = new Properties();
            props.load(new FileInputStream(propsFile));
            return props.getProperty(propertyName, null);
        } else {
            throw new GradleException("Could not read $propertiesFilePath !")
        }
    }

int vCode = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionCode") as Integer
String vName = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionName")

defaultConfig {
    applicationId "com.x.x"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode vCode
    versionName vName
}
</code>```

In your case, you could pass "ProductBuildDateTime" and "ProductVersion" to the method that reads the file.

Body:
I have a CI tool(Bamboo) which runs my Unit Tests and builds the app-release.apk. Whenever I make changes in my app and the build in successful I create a new Version number.I store the version number and build time in a file. Can I make Gradle to read from that file and change the app version accordingly?

Content of my file looks like this:

ProductVersion=0.0.0.0.0
ProductBuildDateTime=2017-01-01T00:00:00.000

Body:
Yes of course, this is how I do it:

I store my versions in a version.properties file.

Then in the app's build.gradle I use the following code:

//Path to the file of your properties file that contains the version number
final String VERSION_PROPERTIES_FILE = projectDir.getParentFile().getParent() + "/file.properties"

 /**
 * Returns the id of the property name from config file, null if it doesn't exist
     * @param propertyName
     * @param properties file name in assets dir
     * @return
     */
    def getPropertyFromFile(propertiesFilePath, propertyName) {
        def propsFile = new File(propertiesFilePath);
        if (propsFile.canRead()) {
            def props = new Properties();
            props.load(new FileInputStream(propsFile));
            return props.getProperty(propertyName, null);
        } else {
            throw new GradleException("Could not read $propertiesFilePath !")
        }
    }

int vCode = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionCode") as Integer
String vName = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionName")

defaultConfig {
    applicationId "com.x.x"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode vCode
    versionName vName
}

In your case, you could pass "ProductBuildDateTime" and "ProductVersion" to the method that reads the file.


问:
Auto-load the seed data from db/seeds.rb with rake
I'm using rails-rspec gem and I have several specs (models, controllers, etc).  When I run:

```<code>bundle exec rake
</code>```

everything is tested.  However, I would like to improve my specs by seeding some data (from db/seeds.rb) just after the database is created (in test environment).

My spec/spec_helper.rb file looks like this:

```<code>ENV["RAILS_ENV"] ||= 'test'

require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'ruby-debug'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = false

  config.include SpecHelper

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
    stub_xmpp_rest_client!
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.include Devise::TestHelpers, :type => :controller
  config.include Delorean
  config.after(:each) { back_to_the_present }
  config.include Factory::Syntax::Methods
  config.extend ControllerMacros, :type => :controller
end
</code>```

What could do the best way to do so?  Thanks.

答:
copy the seed.rb file inside the config/initializers folder.So seed.rb file will be executed on server start.

Run the below command to fill the test db with the seed.rb data

RAILS_ENV=test rake db:seed

Body:
I'm using rails-rspec gem and I have several specs (models, controllers, etc).  When I run:

bundle exec rake

everything is tested.  However, I would like to improve my specs by seeding some data (from db/seeds.rb) just after the database is created (in test environment).

My spec/spec_helper.rb file looks like this:

ENV["RAILS_ENV"] ||= 'test'

require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'ruby-debug'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = false

  config.include SpecHelper

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
    stub_xmpp_rest_client!
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.include Devise::TestHelpers, :type => :controller
  config.include Delorean
  config.after(:each) { back_to_the_present }
  config.include Factory::Syntax::Methods
  config.extend ControllerMacros, :type => :controller
end

What could do the best way to do so?  Thanks.


问:
Count function calls with closure with function attribute
I'm trying to count how many times a function was called by adding an attribute to it. The counter works fine, but I'm not able to access its value from outside the function- see below. Why wouldn't g.n return 2 in my case?

var countFunc = function (func) {
  func.n = 0

  return function () {
    func.n++;
    console.log('called ' + func.n + ' times')
    return func.apply(null, arguments)
  }
}

var f = function (x) { return x };
var g = countFunc(f)

console.log(g(1));  //called 1 times, 1
console.log(g(2)); //called 2 times, 2
console.log(g.n); //undefined```

答:
Just save counter to the newly created function instead of the original one.

var countFunc = function (func) {
  function wrapped () {
    wrapped.n++;
    console.log('called ' + wrapped.n + ' times')
    return func.apply(null, arguments)
  };

  wrapped.n = 0;

  return wrapped;
}

var f = function (x) { return x };
var g = countFunc(f)

console.log(g(1));  //called 1 times, 1
console.log(g(2)); //called 2 times, 2
console.log(g.n); //2```


问:
Mongodb replica set permission denied on arbiter heartbeat
I'm trying to set up a mongo db replicaset, working with Mongodb 3.4.

ServerA:

srv1:27017 - primary

arb:27027 - arbiter

ServerB:

srv2:27017 - secondary

arb shouldn't be hosted with srv1 on ServerA, plan to move later.

The server ports are open, connecting mongo shell works on all instances.

Running rs.status() on srv1 shows everything is fine.

Running it on srv2, however, shows:

```<code>{
    "_id" : 2,
    "name" : "ServerA:27027",
    "health" : 0,
    "state" : 8,
    "stateStr" : "(not reachable/healthy)",
    "uptime" : 0,
    "lastHeartbeat" : ISODate("2017-11-17T14::36:48.088Z"),
    "lastHeartbeatMessage" : "Permission denied",
    "configVersion" : -1
}
</code>```

for the arbiter section (the rest are fine).
The logs on srv2 are repeating these three lines:

```<code>2017-11-17T09:19:02.758-0500 | ASIO [NetworkInterfaceASIO-Replication-0] Failed to connect to ServerA:27027 - HostUnreachable: Permission denied
2017-11-17T09:19:02.758-0500 | ASIO [NetworkInterfaceASIO-Replication-0] Dropping all pooled connections to ServerA:27027 due to failed operation on a connection
2017-11-17T09:19:02.758-0500 | REPL [ReplicationExecutor] Error in heartbeat request to ServerA:27027; HostUnreachable: Permission denied
</code>```

None of them have any authentication set, and srv1, which is hosted on the same machine has no heartbeat problem with the arbiter. Srv2 has no heartbeat problem with srv1.
Googling around, I've seen people not being able to connect because of ip addresses not being bound in mongod.config, or being firewalled, but that's not the case here.

答:
I figured it out. It turns out SELinux was preventing communication on 27027. I guess mongo shell and telnet have no policies preventing tcp traffic. I think ServerA doesn't have any issues because both mongo instances are on the same host.

So in addition to allowing 27017, i had to allow 27027 as well:

```<code>semanage port -a -t mongod_port_t -p tcp 27027
</code>```

If you don't care about added security, another solution is to disable SELinux altogether.

It looks like that if you're running a replica set on servers that have SELinux, you need to allow all ports that are used between members of the replica set.

This is running RedHat 7.4, other distros might ship with different policies.

Body:
I'm trying to set up a mongo db replicaset, working with Mongodb 3.4.

ServerA:

srv1:27017 - primary

arb:27027 - arbiter

ServerB:

srv2:27017 - secondary

arb shouldn't be hosted with srv1 on ServerA, plan to move later.

The server ports are open, connecting mongo shell works on all instances.

Running rs.status() on srv1 shows everything is fine.

Running it on srv2, however, shows:

{
    "_id" : 2,
    "name" : "ServerA:27027",
    "health" : 0,
    "state" : 8,
    "stateStr" : "(not reachable/healthy)",
    "uptime" : 0,
    "lastHeartbeat" : ISODate("2017-11-17T14::36:48.088Z"),
    "lastHeartbeatMessage" : "Permission denied",
    "configVersion" : -1
}

for the arbiter section (the rest are fine).
The logs on srv2 are repeating these three lines:

2017-11-17T09:19:02.758-0500 | ASIO [NetworkInterfaceASIO-Replication-0] Failed to connect to ServerA:27027 - HostUnreachable: Permission denied
2017-11-17T09:19:02.758-0500 | ASIO [NetworkInterfaceASIO-Replication-0] Dropping all pooled connections to ServerA:27027 due to failed operation on a connection
2017-11-17T09:19:02.758-0500 | REPL [ReplicationExecutor] Error in heartbeat request to ServerA:27027; HostUnreachable: Permission denied

None of them have any authentication set, and srv1, which is hosted on the same machine has no heartbeat problem with the arbiter. Srv2 has no heartbeat problem with srv1.
Googling around, I've seen people not being able to connect because of ip addresses not being bound in mongod.config, or being firewalled, but that's not the case here.

Body:
I figured it out. It turns out SELinux was preventing communication on 27027. I guess mongo shell and telnet have no policies preventing tcp traffic. I think ServerA doesn't have any issues because both mongo instances are on the same host.

So in addition to allowing 27017, i had to allow 27027 as well:

semanage port -a -t mongod_port_t -p tcp 27027

If you don't care about added security, another solution is to disable SELinux altogether.

It looks like that if you're running a replica set on servers that have SELinux, you need to allow all ports that are used between members of the replica set.

This is running RedHat 7.4, other distros might ship with different policies.


答:
The correct syntax is this:</p>

```<code>int[][] iArr = Arrays.stream(s.split("\n")).map(r
        -> // It transforms a String 'r' into a int[]
        Arrays.stream(r.split("\t")).mapToInt(Integer::parseInt).toArray()
// It transforms a Stream of int[] into int [][]
).toArray(int[][]::new);

System.out.println(Arrays.deepToString(iArr));//Print your result
</code>```

Title: String to 2D Array with streams [Java 8]

Body:
I am currently learning how to do streams, while doing some assignments for fun (Advent of code). While I know how how to do it with temporary arrays, I do not know the correct syntax for streams or if it is even possible to do it in one line.

public class M3 {
public static void main(String[] args) {
    String s = "104\t240\t147\t246\t123\t175\t372\t71\t116\t230\t260\t118\t202\t270\t277\t292\n" +
            "740\t755\t135\t205\t429\t822\t844\t90\t828\t115\t440\t805\t526\t91\t519\t373\n" +
            "1630\t991\t1471\t1294\t52\t1566\t50\t1508\t1367\t1489\t55\t547\t342\t512\t323\t51\n" +
            "1356\t178\t1705\t119\t1609\t1409\t245\t292\t1434\t694\t405\t1692\t247\t193\t1482\t1407\n" +
            "2235\t3321\t3647\t212\t1402\t3711\t3641\t1287\t2725\t692\t1235\t3100\t123\t144\t104\t101\n" +
            "1306\t1224\t1238\t186\t751\t734\t1204\t1275\t366\t149\t1114\t166\t1118\t239\t153\t943\n" +
            "132\t1547\t1564\t512\t2643\t2376\t2324\t2159\t1658\t107\t1604\t145\t2407\t131\t2073\t1878\n" +
            "1845\t91\t1662\t108\t92\t1706\t1815\t1797\t1728\t1150\t1576\t83\t97\t547\t1267\t261\n" +
            "78\t558\t419\t435\t565\t107\t638\t173\t93\t580\t338\t52\t633\t256\t377\t73\n" +
            "1143\t3516\t4205\t3523\t148\t401\t3996\t3588\t300\t1117\t2915\t1649\t135\t134\t182\t267\n" +
            "156\t2760\t1816\t2442\t2985\t990\t2598\t1273\t167\t821\t138\t141\t2761\t2399\t1330\t1276\n" +
            "3746\t3979\t2989\t161\t4554\t156\t3359\t173\t3319\t192\t3707\t264\t762\t2672\t4423\t2924\n" +
            "3098\t4309\t4971\t5439\t131\t171\t5544\t595\t154\t571\t4399\t4294\t160\t6201\t4329\t5244\n" +
            "728\t249\t1728\t305\t2407\t239\t691\t2241\t2545\t1543\t55\t2303\t1020\t753\t193\t1638\n" +
            "260\t352\t190\t877\t118\t77\t1065\t1105\t1085\t1032\t71\t87\t851\t56\t1161\t667\n" +
            "1763\t464\t182\t1932\t1209\t640\t545\t931\t1979\t197\t1774\t174\t2074\t1800\t939\t161";

    int[][] iArr = Arrays.stream(s.split("\n")).map(String[]::String.split("\t"));
}

Body:
The correct syntax is this:

int[][] iArr = Arrays.stream(s.split("\n")).map(r
        -> // It transforms a String 'r' into a int[]
        Arrays.stream(r.split("\t")).mapToInt(Integer::parseInt).toArray()
// It transforms a Stream of int[] into int [][]
).toArray(int[][]::new);

System.out.println(Arrays.deepToString(iArr));//Print your result


问:
Line coverage between SonarQube and Jacoco is different
i have the problem that in SonarQube v6.7 the line coverage is lower than in jacoco report.

When I'm opening sonar my class file has a lot of uncovered lines. When opening the jacoco report, it shows me that these lines are covered.

I'm using the gradle plugin. (v2.6)

Any ideas what can be the issue?

答:
OK, had found the solution in a different thread.

Just added into the build.gradle

```<code>subprojects {
tasks.withType(Test) {
    // redirect all coverage data to one file
    // ... needs cleaning the data prior to the build to avoid accumulating coverage data of different runs.
    // see `task cleanJacoco`
    jacoco {
//            destinationFile = file("$rootProject.buildDir/jacoco/${project.name}.exec")
        destinationFile = file("$rootProject.buildDir/jacoco/test.exec")
    }
}

task cleanJacoco(dependsOn: 'clean') {  delete "$buildDir/jacoco" }
</code>```

}

Body:
OK, had found the solution in a different thread.

Just added into the build.gradle

subprojects {
tasks.withType(Test) {
    // redirect all coverage data to one file
    // ... needs cleaning the data prior to the build to avoid accumulating coverage data of different runs.
    // see `task cleanJacoco`
    jacoco {
//            destinationFile = file("$rootProject.buildDir/jacoco/${project.name}.exec")
        destinationFile = file("$rootProject.buildDir/jacoco/test.exec")
    }
}

task cleanJacoco(dependsOn: 'clean') {  delete "$buildDir/jacoco" }

}


问:
Get mailchimp form on one line with CSS
I am trying to get my mailchimp embed form all on one line, the call to signup, the input field and the submit button. I have tried following this answer here: https://codepen.io/pageaffairs/pen/JDrhG Tweaked a few things but still all in the middle and stacked on top of each other. http://theinvicto.com/

Tried changing the "clear: left" to "clear:none" and centered the form with text-align but still not on the same line. Would I use table for this?

HTML:

   #mc_embed_signup{background:#50B1C5; clear:none; }

    #mc-embedded-subscribe-form.validate {
        background: #50B1C5;
    }

    #mc_embed_signup #mce-EMAIL {
        border: 3px solid #F3A733;
    }

    input#mc-embedded-subscribe.button {
    background-color: #F3A733;
    font-family: ‘Abel’;
    }

    *, *:before, *:after {-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;}
     #mc_embed_signup{ clear:none; font:18px Abel,Arial,sans-serif; vertical-align: middle; width: 100%; margin: 0 auto;}
     #mc_embed_signup form {display:block; position:relative; text-align:center;}
     #mc_embed_signup input {border:3px solid #F3A733; -webkit-appearance:none;}
     #mc_embed_signup input:focus {border-color:#333;}
     #mc_embed_signup .button {background-color: #F3A733; border: 0 none; border-radius:4px; color: #FFFFFF; cursor: pointer; display: inline-block; font-size:15px; height: 32px; line-height: 32px; margin: 0 5px 10px 0; padding:0; text-align: center; text-decoration: none; vertical-align: top; white-space: nowrap; width: auto;}
     #mc_embed_signup .button:hover {background-color:#EB7162;}
     #mc_embed_signup .small-meta {font-size: 11px;}
     #mc_embed_signup .nowrap {white-space:nowrap;}
     #mc_embed_signup .clear {clear:none; display: inline-block; width: 31%; vertical-align: top;}

     #mc_embed_signup label {display:inline-block; font-size:16px; padding-bottom:10px; font-weight:bold; width: 70%;vertical-align: top;}
     #mc_embed_signup input.email {display:inline-block; padding:8px 0; margin:0 10px 10px 0; text-indent:5px; width:34%;vertical-align: top;}
     #mc_embed_signup input.button {display:block; width:100%; margin:0 0 10px 0;}

     @media screen and (max-width: 780px) {
      #mc_embed_signup {width: 100%;}
      #mc_embed_signup label, #mc_embed_signup input.email, #mc_embed_signup .clear {display: block; width: 100%;}
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- Begin MailChimp Signup Form -->
    <div id="mc_embed_signup">
    <form action="https://theinvicto.us17.list-manage.com/subscribe/post?u=197c4c27bd3b031b5957c0035&id=0d6f057689" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
        <div id="mc_embed_signup_scroll">
     <label for="mce-EMAIL"><span style="font-size: 35px;">be the first to know:</span></label>
     <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
        <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_197c4c27bd3b031b5957c0035_0d6f057689" tabindex="-1" value=""></div>
        <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
        </div>
    </form>
</div>

    <!--End mc_embed_signup-->

 </code>```

Let me know if anyone has had luck with something else. I'm learning and trying to troubleshoot but have finally decided to ask where I've gone wrong. Thinking maybe it's a display: table thing but I could be so wrong, hah.

答:
```<code><div>
  <p class="line">Lorem Ipsum</p>
  <input type="text" class="line">
  <button class="line">Submit</button>
</div>
</code>```

And the css

```<code>.line {
  float: left;
}
</code>```

Just put on each element float: left, if this doesnt work try to play with your width on the wrapper and each element, for ex: #wrapper="width: 100%" and since there are 3 elements just put each of them to have 33% width. Hope this helps

Title: Get mailchimp form on one line with CSS

Body:
I am trying to get my mailchimp embed form all on one line, the call to signup, the input field and the submit button. I have tried following this answer here: https://codepen.io/pageaffairs/pen/JDrhG Tweaked a few things but still all in the middle and stacked on top of each other. http://theinvicto.com/

Tried changing the "clear: left" to "clear:none" and centered the form with text-align but still not on the same line. Would I use table for this?

HTML:

   #mc_embed_signup{background:#50B1C5; clear:none; }

    #mc-embedded-subscribe-form.validate {
        background: #50B1C5;
    }

    #mc_embed_signup #mce-EMAIL {
        border: 3px solid #F3A733;
    }

    input#mc-embedded-subscribe.button {
    background-color: #F3A733;
    font-family: ‘Abel’;
    }

    *, *:before, *:after {-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;}
     #mc_embed_signup{ clear:none; font:18px Abel,Arial,sans-serif; vertical-align: middle; width: 100%; margin: 0 auto;}
     #mc_embed_signup form {display:block; position:relative; text-align:center;}
     #mc_embed_signup input {border:3px solid #F3A733; -webkit-appearance:none;}
     #mc_embed_signup input:focus {border-color:#333;}
     #mc_embed_signup .button {background-color: #F3A733; border: 0 none; border-radius:4px; color: #FFFFFF; cursor: pointer; display: inline-block; font-size:15px; height: 32px; line-height: 32px; margin: 0 5px 10px 0; padding:0; text-align: center; text-decoration: none; vertical-align: top; white-space: nowrap; width: auto;}
     #mc_embed_signup .button:hover {background-color:#EB7162;}
     #mc_embed_signup .small-meta {font-size: 11px;}
     #mc_embed_signup .nowrap {white-space:nowrap;}
     #mc_embed_signup .clear {clear:none; display: inline-block; width: 31%; vertical-align: top;}

     #mc_embed_signup label {display:inline-block; font-size:16px; padding-bottom:10px; font-weight:bold; width: 70%;vertical-align: top;}
     #mc_embed_signup input.email {display:inline-block; padding:8px 0; margin:0 10px 10px 0; text-indent:5px; width:34%;vertical-align: top;}
     #mc_embed_signup input.button {display:block; width:100%; margin:0 0 10px 0;}

     @media screen and (max-width: 780px) {
      #mc_embed_signup {width: 100%;}
      #mc_embed_signup label, #mc_embed_signup input.email, #mc_embed_signup .clear {display: block; width: 100%;}
     }

    <form action="https://theinvicto.us17.list-manage.com/subscribe/post?u=197c4c27bd3b031b5957c0035&id=0d6f057689" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

     be the first to know:
     <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>

<input type="text" name="b_197c4c27bd3b031b5957c0035_0d6f057689" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

    </form>

Let me know if anyone has had luck with something else. I'm learning and trying to troubleshoot but have finally decided to ask where I've gone wrong. Thinking maybe it's a display: table thing but I could be so wrong, hah.

Body:
<div>
  <p class="line">Lorem Ipsum</p>
  <input type="text" class="line">
  <button class="line">Submit</button>
</div>

And the css

.line {
  float: left;
}

Just put on each element float: left, if this doesnt work try to play with your width on the wrapper and each element, for ex: #wrapper="width: 100%" and since there are 3 elements just put each of them to have 33% width. Hope this helps


问:
Giving more memory to mex programs in Matlab
My C mex-compiled files are running out of memory (more specifically, my calls to mxMalloc sometimes return NULL). From a quick calculation I estimate that my files ask mxMalloc for about 500 MB of memory in total (maybe as much as 1 GB), and I run my files on a 64 bit Linux machine with 16 GB of memory running Matlab almost exclusively. Yet, mxMalloc returns NULL quite often.

I guess that that there are several reasons why this could happen (memory fragmentation, etc.), but in any case, 500 MB do not seem to be that much to ask from a 16-GB-memory machine.

I presume that my calls to mxMalloc request memory from Matlab's heap, but am not 100% sure about it ( mxMalloc requests are handled by Matlab after all, and not directly by the OS). So is there a way of increasing my mex file's "heap" size?

Thanks

答:
You can use malloc (not mxMalloc) but the memory must be managed manually (e.g. You must call free; it's not optional like mxFree is). You could also try compiling using c++ and boost's shared/scoped pointers. Your mexFunction signature will need extern "C" prepended to it.

One reason you may be running out of memory is that your arrays are too long.mxArray must be contiguous data. So mxMallocing them and the mxFreeing them could fragment your memory space. While std::vector must be contiguous too, std::list doesn't have to be.

Something like the original STL's rope class could be a good implementation too.

ContentLicense: CC BY-SA 2.5


问:
How to open Console window in Eclipse?
I accidentally closed the Console window in Eclipse, and now I can't see the result of my code being run.

How do you open it again?

答:
The only reliable way to open it is Window -> Show View -> Other -> Search "console".
There was a handful suggestions in this post and none of them works! Apparently Eclipse likes to change their logic every other second.

Also, resetting the view is the most horrible suggestion, because that way you will lose everything you have ever done to change the layout, so it will probably not work for the most of the readers.

Title: How to open Console window in Eclipse?


问:
Is it possible to disable chart located in charts folder in kubernetes?
I have a subchart in charts/ directory. I would like to disable it for some deployments.

Is it possible somehow? Currently i see the only way to add condition to all templates like below:

deployment.yaml

```<code>{{- if .Values.isDev }}
deployment code
{{- end }}
</code>```

service.yaml

```<code>{{- if .Values.isDev }}
service code
{{- end }}
</code>```

答:
As a general rule of thumb I always have

```<code>{{- if .Values.enabled }}
...
{{- end }}
</code>```

in every file in every subchart. Depending on situation the default value will be either true for regular components or false for dev related, or simply false for everything if I want to enable these in completely selective manner. A typical values for deployment for this approach looks like ie.:

```<code>api:
  enabled: true
  database:
    host: mysql-dev

mysql:
  enabled: false

mysql-dev:
  enabled: true
</code>```

Body:
I have a subchart in charts/ directory. I would like to disable it for some deployments.

Is it possible somehow? Currently i see the only way to add condition to all templates like below:

deployment.yaml

{{- if .Values.isDev }}
deployment code
{{- end }}

service.yaml

{{- if .Values.isDev }}
service code
{{- end }}

Body:
As a general rule of thumb I always have

{{- if .Values.enabled }}
...
{{- end }}

in every file in every subchart. Depending on situation the default value will be either true for regular components or false for dev related, or simply false for everything if I want to enable these in completely selective manner. A typical values for deployment for this approach looks like ie.:

api:
  enabled: true
  database:
    host: mysql-dev

mysql:
  enabled: false

mysql-dev:
  enabled: true


问:
How to place the last
 on the top right side of my page?
I want to move the last li to top right side and also it need to be aligned with menu text called Home | About | Contact but my CSS is not working.

My full html can be found here https://jsfiddle.net/g2upojoc/1/

Please tell me what I need to modify in css code. thanks

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */

@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
  margin: 10px;
}

ul li {
  list-style: none;
}

.navbar ul {
  border: 1px solid red;
  padding: 0;
  margin: 50px;
}

.navbar ul:after {
  /* clearfix */
  content: "";
  display: table;
  clear: both;
}

.navbar li {
  float: left;
  /* all li items */
  padding: 0;
  margin: 0;
  border: 1px solid green;
  list-style: none;
}

.navbar li:last-child {
  float: right;
  /* last li item */
}

.gCountryFlag {
  margin-left: 0;
  padding-left: 0;
}

.gCountryFlag li {
  float: left;
  display: inline-block;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type="text/javascript" src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<form method="post" action="./default.aspx" id="ctl01">

  <div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
      </div>
      <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
          <li>Home</li>
          <li>About</li>
          <li>Contact</li>
          <li>
            <div class="flagChangeCountry">
              <img id="currentCultureFlagImage" class="topFlag" src="http://www.bba-reman.com/images/flags/us.gif" alt="English (United Kingdom)" />

            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <div class="container body-content">

    <br /><br />
    Home
    About
    Contact
    <br /><br /><br /><br />

    <input type="submit" name="ctl00$MainContent$Button1" value="Button" id="MainContent_Button1" />

    <br /><br />

    <span id="MainContent_lbltext">Welcome to My WebSite</span>

    <hr />
    <footer class="navbar-fixed-bottom">
      <div id="footer_column6" class="col-md-12">
        <ul>
          <li class="countryTitle">Other Country</li>
          <li>

            <ul id="flag" class="gCountryFlag">

              <li>

                  <img src="http://www.bba-reman.com/images/flags/de.gif" alt="BBA Reman - DE Flag">

              </li>

              <li>

                  <img src="http://www.bba-reman.com/images/flags/fr.gif" alt="BBA Reman - FR Flag">

              </li>
              <li>

                  <img src="http://www.bba-reman.com/images/flags/gb.gif" alt="BBA Reman - GB Flag">

              </li>

              <li>

                  <img src="http://www.bba-reman.com/images/flags/us.gif" alt="BBA Reman - US Flag">

              </li>

            </ul>
          </li>
        </ul>
      </div>
    </footer>

  </div>

</form></code>```

答:
Add a class to the li, call it lang-icon
and add the following css:

```<code>.lang-icon{
  position: absolute !important;
  right: 0;
  top: 0;
}
</code>```

Title: How to place the last <li> on the top right side of my page?

Body:
I want to move the last li to top right side and also it need to be aligned with menu text called Home | About | Contact but my CSS is not working.

My full html can be found here https://jsfiddle.net/g2upojoc/1/

Please tell me what I need to modify in css code. thanks

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */

@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
  margin: 10px;
}

ul li {
  list-style: none;
}

.navbar ul {
  border: 1px solid red;
  padding: 0;
  margin: 50px;
}

.navbar ul:after {
  /* clearfix */
  content: "";
  display: table;
  clear: both;
}

.navbar li {
  float: left;
  /* all li items */
  padding: 0;
  margin: 0;
  border: 1px solid green;
  list-style: none;
}

.navbar li:last-child {
  float: right;
  /* last li item */
}

.gCountryFlag {
  margin-left: 0;
  padding-left: 0;
}

.gCountryFlag li {
  float: left;
  display: inline-block;
  margin: 5px;
}

<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<form method="post" action="./default.aspx" id="ctl01">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>

Home

About

Contact

    Home
    About
    Contact

    <input type="submit" name="ctl00$MainContent$Button1" value="Button" id="MainContent_Button1" />

    Welcome to My WebSite

Other Country

</form>

Body:
Add a class to the li, call it lang-icon
and add the following css:

.lang-icon{
  position: absolute !important;
  right: 0;
  top: 0;
}

ContentLicense: CC BY-SA 4.0


问:
Find changeset using commit message mercurial

I was wondering if I can find, in mercurial, a changeset using a part of a commit message

for example I have some commits with following messages:
"Test-254 modified some files"
"Test-256 added logs"

And I want to find the changeset which has a commit containing Test-254 or Test-256

答:
Mercurial supports advanced selection language called revset. You can access the help with hg help revset.

It supports both predicates and operators.

Predicates are for example all() to match all revision or desc(string) to match revisions containing string in their message.

Operators are x:y for selecting a range or or for an or condition.

By combining both, you can select the right commits you want:

hg log -r "desc('Test-254')" will matches all revision that includes Test-254 in their message.

hg log -r "desc('Test-256')" will matches all revision that includes Test-256 in their message.

hg log -r "desc('Test-254') or desc('Test-256')" will matches all revision that includes either Test-254 or Test-256 in their message.


问:
error when using <%#Eval("")%> asp.net
Hello

I get Error usign <%#Eval("ComlainnID")%>

I got error on every line which have <%#Eval%>

My GridView code is this

```<code>      <asp:GridView CssClass="tbl" runat="server" AutoGenerateColumns="False" DataKeyNames="ComplainID"
      DataSourceID="SqlDataSource1" ItemType="q" CellPadding="4" ForeColor="#333333" ID="gv" style="direction: ltr"
       OnPageIndexChanging="gv_PageIndexChanging" AllowPaging="True" EmptyDataText="No Complain Found"
        BorderColor="Black" BorderStyle="Solid" BorderWidth="2px" PageSize="25"
      OnDataBinding="gv_DataBinding" OnRowDataBound ="gv_DataBound" AllowSorting="True" OnRowEditing="gv_RowEditing"

      >
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>

            <asp:ImageField  HeaderStyle-CssClass="border" HeaderText="Photo"  DataImageUrlField="ImagePath" ItemStyle-Height="50px" ItemStyle-Width="50px">
                <ItemStyle  CssClass="border"  Height="50px" Width="50px">
                </ItemStyle>
            </asp:ImageField>

             <asp:CommandField ButtonType="Button" EditText="Reply" ShowEditButton="True"
                 HeaderStyle-CssClass="border" ItemStyle-CssClass="border" >

            </asp:CommandField>
            <asp:TemplateField>
                <ItemTemplate>

                    <asp:Label Text='<%#Eval("ComplainID")%>' ID="Label1" runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>

    </asp:GridView>
</code>```

The Error is on line

```<code>             <asp:Label Text='<%#Eval("ComplainID")%>' ID="Label1" runat="server"></asp:Label>
</code>```

The Error is :

```<code>        Error   CS0246  The type or namespace name 'q' could not be found (are you missing a using directive or an assembly reference?)
</code>```

This is web application in .NET Framework 4.6

答:
You should probably remove this from your gridview properties:</p>

```<code>ItemType="q"
</code>```

Title: error when using <%#Eval("")%> asp.net

Body:
Hello

I get Error usign <%#Eval("ComlainnID")%>

I got error on every line which have <%#Eval%>

My GridView code is this

      <asp:GridView CssClass="tbl" runat="server" AutoGenerateColumns="False" DataKeyNames="ComplainID"
      DataSourceID="SqlDataSource1" ItemType="q" CellPadding="4" ForeColor="#333333" ID="gv" style="direction: ltr"
       OnPageIndexChanging="gv_PageIndexChanging" AllowPaging="True" EmptyDataText="No Complain Found"
        BorderColor="Black" BorderStyle="Solid" BorderWidth="2px" PageSize="25"
      OnDataBinding="gv_DataBinding" OnRowDataBound ="gv_DataBound" AllowSorting="True" OnRowEditing="gv_RowEditing"

      >
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>

            <asp:ImageField  HeaderStyle-CssClass="border" HeaderText="Photo"  DataImageUrlField="ImagePath" ItemStyle-Height="50px" ItemStyle-Width="50px">
                <ItemStyle  CssClass="border"  Height="50px" Width="50px">
                </ItemStyle>
            </asp:ImageField>

             <asp:CommandField ButtonType="Button" EditText="Reply" ShowEditButton="True"
                 HeaderStyle-CssClass="border" ItemStyle-CssClass="border" >

            </asp:CommandField>
            <asp:TemplateField>
                <ItemTemplate>

                    <asp:Label Text='<%#Eval("ComplainID")%>' ID="Label1" runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>

    </asp:GridView>

The Error is on line

             <asp:Label Text='<%#Eval("ComplainID")%>' ID="Label1" runat="server"></asp:Label>

The Error is :

        Error   CS0246  The type or namespace name 'q' could not be found (are you missing a using directive or an assembly reference?)

This is web application in .NET Framework 4.6

Body:
You should probably remove this from your gridview properties:

ItemType="q"


问:
Java HTTP Server Library
I'm writing an application which needs to be able to handle HTTP requests from an external source (in this case, it's actually a script from Second Life). I started out by using HTTPComponents by Apache, which worked great as long as the Java server only had to respond to GET requests. Now it needs to be able to receive data from the body of POST requests, and I don't see any way to do so with HTTPComponents. Is there a superior library to use for this?

I did find through some Googling that there is a basic HTTP server included in the Sun packages. For the purposes of this application, it could be required that it only run on an actual Sun/Oracle JVM implementation -- but that's still a code smell to me, and I'd probably only do so if the only option was to write my own HTTP server library from scratch, working up from sockets and such. Any suggestions for an alternative?

答: Use Apache Tomcat. It's the standard Java web server.</p>

Title: Java HTTP Server Library


问:
How can I get JSON data from the server by using Autobhan(Crossbar)
I got this as below from backend developer:

```<code> session.publish('com.test.temp', [
        temp,
        humidity,
        componentId,
        componentType
     ], {}, { exclude_me: true });
</code>```

So I succeed in a handshake with the server using WebSocket:

```<code> var ws = new WebSocket('ws://1server address','example.json');

  ws.onopen = function () {
      console.log('websocket is connected ...')

      ws.send('connected')
  }

  ws.onmessage = function (ev) {
      console.log(ev);
  }
</code>```

But I could not see any data in the console.log(ev)

How can I get JSON data from the server??

答:
I find a way to get data from the crossbar.

I was supposed to use autobahn library.

This is my solution:

var connection = new autobahn.Connection({
    url : 'server url',
    realm: 'realm1'

  });

connection.onopen = function (session) {

```<code>console.log('websocket is connected ...')

session.subscribe('com.example.example', function(message) {
 console.log(message);

 }
</code>```

}

connection.open();

I hope this answer will be helpful to someone.

Body:
I got this as below from backend developer:

 session.publish('com.test.temp', [
        temp,
        humidity,
        componentId,
        componentType
     ], {}, { exclude_me: true });

So I succeed in a handshake with the server using WebSocket:

 var ws = new WebSocket('ws://1server address','example.json');

  ws.onopen = function () {
      console.log('websocket is connected ...')

      ws.send('connected')
  }

  ws.onmessage = function (ev) {
      console.log(ev);
  }

But I could not see any data in the console.log(ev)

How can I get JSON data from the server??

Body:
I find a way to get data from the crossbar.

I was supposed to use autobahn library.

This is my solution:

var connection = new autobahn.Connection({
    url : 'server url',
    realm: 'realm1'

  });

connection.onopen = function (session) {

console.log('websocket is connected ...')

session.subscribe('com.example.example', function(message) {
 console.log(message);

 }

}

connection.open();

I hope this answer will be helpful to someone.


问:
Install XGBoost for Pycharm VirtualEnv (Windows)
I'm trying to install XGBoost package for my PyCharm project on Windows. Although I found XGBoost package in Project Interpreter - Install (+) - Available Packages menu, following error occurred during installation:

Collecting xgboost   Using cached xgboost-0.6a2.tar.gz

No files/directories in
  C:\Users\\AppData\Local\Temp\pycharm-packaging\xgboost\pip-egg-info
  (from PKG-INFO)

I've found this answer regarding the installation XGBoost on Windows and it works for me.

However, when I then created a new PyCharm virtual environment, XGBoost is still not available, neither can I install it from Project Interpreter menu.

So the question is how to install XGBoost for PyCharm with VirtualEnv, running on Windows?

Thanks.

答:
I suggest that instead of using the PyCharm settings dialog to install the package, you install the XGBoost package into the virtual environment using the command line.

If you a) run into problems installing XGBoost into a virtual environment and b) installing XGBoost in the root python installation works OK, I suggest you create the virtual environment using the --system-site-packages option (giving the virtual environment access to the system site-packages).

Also, check out the excellent site Python Extension Packages for Windows by Christoph Gohlke. There you will find prebuilt packages for a lot of hard-to-build-on-windows Python packages, including XGBoost 0.6 for Python 3.5 and 3.6.

And if you continue to have problems with the stock python distro (the one on www.python.org), I suggest give Anaconda a try. This SO question deals with installing XGBoost on Anaconda.


问:
How to pass multidimensional array in collection view inside the tableview cell?
I have multidimensional array for example like following, how can I pass the array of my collection view on / of a table views / viewed cel ?

```<code>let array = [["abc " , " bce "] , ["a "] , ["abc " , " abce " , " a "] , []]
</code>```

I want first array object of first cell, second array object of second cell and continuous.

答:
You can implement like this way</p>

```<code>extension YourViewController : UICollectionViewDelegate,UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return array.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return array[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath)
        let string = array[indexPath.section][indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedString = array[indexPath.section][indexPath.item]
    }

}
</code>```

Body:
I have multidimensional array for example like following, how can I pass the array of my collection view on / of a table views / viewed cel ?

let array = [["abc " , " bce "] , ["a "] , ["abc " , " abce " , " a "] , []]

I want first array object of first cell, second array object of second cell and continuous.

Body:
You can implement like this way

extension YourViewController : UICollectionViewDelegate,UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return array.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return array[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath)
        let string = array[indexPath.section][indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedString = array[indexPath.section][indexPath.item]
    }

}


问:
Get date from coming day and specified date in Carbon?
In Carbon, I can do

```<code>Carbon::parse("This Sunday"); // This gives me coming date for Sunday
</code>```

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

答:
You could possibly do something like:
As mentioned in the official documentation

```<code>$sunday = Carbon::parse("This Sunday"); //you are able to retrieve this currently

$nextSunday = $sunday->addWeek();
</code>```

Body:
In Carbon, I can do

Carbon::parse("This Sunday"); // This gives me coming date for Sunday

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

Body:
You could possibly do something like:
As mentioned in the official documentation

$sunday = Carbon::parse("This Sunday"); //you are able to retrieve this currently

$nextSunday = $sunday->addWeek();


问:
Fetch new entities only
I thought Datastore's key was ordered by insertion date, but apparently I was wrong. I need to periodically look for new entities in the Datastore, fetch them and process them.

Until now, I would simply store the last fetched key and wrongly query for anything greater than it.

Is there a way of doing so?

Thanks in advance.

答:
Datastore automatically generated keys are generated with uniform distribution, in order to make search more performant. You will not be able to understand which entity where added last using keys.

Instead, you can try couple of different approaches.

Use Pub/Sub and architecture your app so another background task will consume this last added entities. On entities add in DB, you will just publish new Event into Pub/Sub with key id. You event listener (separate routine) will receive it.

Use names and generate you custom names. But, as you want to create sequentially growing names, this will case performance hit on even not big ranges of data. You can find more about this in Best Practices of Google Datastore.
https://cloud.google.com/datastore/docs/best-practices#keys

You can add additional creation time column, and still use automatic keys generation.

Title: Fetch new entities only


问:
Unable to enforce Propagation.MANDATORY on Spring Data CRUD methods
Any reason for this?

I've been using Spring data for years but I don't think I've ever unit tested one of their out-of-the-box CRUD methods before.

Why is it that the following interface definition has no effect on their transactional implementation for CRUD methods?

```<code>@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface MyRepository extends JpaRepository<MyEntity, Long> {

    Stream<MyEntity> findMyEntityByStatusEquals(Status status);
}
</code>```

If I call myRepository.save(new MyEntity()) from a test method, WITHOUT my test being wrapped in a transaction, it succeeds.

However, if I call myRepository.findMyEntityByStatusEquals("MY_STATUS") it fails stating that it needs to be wrapped in a transaction.

The latter case I expect, the former case terrifies me as I don't seem to be able to enforce it to be part of an existing transaction.

::Edit:: Turns out putting @Transactional at the top of the interface has no effect on Spring Data CRUD methods that have previously been marked as @Transactional. I always assumed it was also an override when specified on these interfaces.

答:
As stated by documentation here

CRUD methods on repository instances are transactional by default. For
reading operations the transaction configuration readOnly flag is set
to true, all others are configured with a plain @Transactional so that
default transaction configuration applies.

@Transactional has Propagation.REQUIRED as its default propagation type, so when you call the save method a new transaction just begin.

If you want force Propagation.MANDATORY even on built-in CRUD methods you have to override such methods, i.e

```<code>@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface MyRepository extends JpaRepository<MyEntity, Long> {

    Stream<MyEntity> findMyEntityByStatusEquals(Status status);

    @Transactional(propagation = Propagation.MANDATORY)
    public <MyEntity> MyEntity save(MyEntity entity) {
      super.save(entity);
    }
}
</code>```

hope this helps

Body:
Any reason for this?

I've been using Spring data for years but I don't think I've ever unit tested one of their out-of-the-box CRUD methods before.

Why is it that the following interface definition has no effect on their transactional implementation for CRUD methods?

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface MyRepository extends JpaRepository<MyEntity, Long> {

    Stream<MyEntity> findMyEntityByStatusEquals(Status status);
}

If I call myRepository.save(new MyEntity()) from a test method, WITHOUT my test being wrapped in a transaction, it succeeds.

However, if I call myRepository.findMyEntityByStatusEquals("MY_STATUS") it fails stating that it needs to be wrapped in a transaction.

The latter case I expect, the former case terrifies me as I don't seem to be able to enforce it to be part of an existing transaction.

::Edit:: Turns out putting @Transactional at the top of the interface has no effect on Spring Data CRUD methods that have previously been marked as @Transactional. I always assumed it was also an override when specified on these interfaces.

Body:
As stated by documentation here

CRUD methods on repository instances are transactional by default. For
reading operations the transaction configuration readOnly flag is set
to true, all others are configured with a plain @Transactional so that
default transaction configuration applies.

@Transactional has Propagation.REQUIRED as its default propagation type, so when you call the save method a new transaction just begin.

If you want force Propagation.MANDATORY even on built-in CRUD methods you have to override such methods, i.e

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface MyRepository extends JpaRepository<MyEntity, Long> {

    Stream<MyEntity> findMyEntityByStatusEquals(Status status);

    @Transactional(propagation = Propagation.MANDATORY)
    public <MyEntity> MyEntity save(MyEntity entity) {
      super.save(entity);
    }
}

hope this helps


问:
Source Code Protection
When you compile a program to publish with Visual Studio 2010, does that have any advanced methods to keep your program being decompiled to source code? Are there any methods you would use to encrypt yoursource code before compiling?</p>

答:
Visual Studio by default does not apply any form of enhancements nor modify the compiled binaries other than chosen optimization setting.
There are however protectors you can make use of.
Remember UPX?
Well upx is still a very viable method of encrypting your binaries altough of course it all depends on your needs.</p>

Title: Source Code Protection


问:
Runtime Error(Non Zero Exit Code) in CodeChef Program (JAVA)
Here's the question -
https://www.codechef.com/DEC17/problems/CPLAY

And here's my solution -

```<code>import java.util.Scanner;

class Penalty_Shoot_Out
{

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        //System.out.println("T: ");
        int T = sc.nextInt();
        sc.nextLine();
        while(T-->0)
        {
            String s = sc.nextLine();
            int l = s.length();
            s = " " + s;
            int A_score = 0, B_score = 0, A_shots = 0, B_shots = 0, flag = 0, A_shots_left = 5, B_shots_left = 5, shots_left = 0;
            Outer:for(int i=1; i<=20; i++)
            {
                char c = s.charAt(i);
                if(i%2==1)
                {
                    flag = 0;
                    A_shots++;
                    A_shots_left--;
                    if(c=='1')
                        A_score++;
                }
                else
                {
                    flag = 1;
                    B_shots++;
                    B_shots_left--;
                    if(c=='1')
                        B_score++;
                }
                if(i<=10)
                {
                    if(A_score<B_score)
                    {
                        if(B_score-A_score>A_shots_left)
                        {
                            System.out.println("TEAM-B " + i);
                            break Outer;
                        }
                    }
                    else
                    {
                        if(A_score-B_score>B_shots_left)
                        {
                           System.out.println("TEAM-A " + i);
                           break Outer;
                        }
                    }
                }
                else if(i>10 && i<=20)
                {
                    if(i%2==0)
                    {
                        if(A_score>B_score)
                            System.out.println("TEAM-A " + i);
                        else if(B_score>A_score)
                            System.out.println("TEAM-B " + i);
                        else
                            System.out.println("TIE");
                        break Outer;
                    }
                }
            }
        }
    }
}
</code>```

These are the exceptions -

Exception

```<code>in thread "main" java.util.NoSuchElementException

    at java.util.Scanner.throwFor(Scanner.java:862)

    at java.util.Scanner.next(Scanner.java:1485)

    at java.util.Scanner.nextInt(Scanner.java:2117)

    at java.util.Scanner.nextInt(Scanner.java:2076)

    at Penalty_Shoot_Out.main(Main.java:8)
</code>```

I'm getting the correct answer on my computer, but when I submit it online, I get the NZEC Runtime Error.

I tried Googling for solutions and most people said the error might have to do with the main function returning a wrong number or not returning a number. Some said it may be due to the use of a particular function or due to an exception that i am not handling during I/O. However, I haven't been able to figure it out.

I'd really appreciate it if someone could fix my code.

答:
You should put your solution in a try catch.

```<code>public static void main(String args[])
{
  try {
    Scanner sc = new Scanner(System.in);
    //System.out.println("T: ");
    int T = sc.nextInt();
    sc.nextLine();
    while(T-->0)
    {
       String s = sc.nextLine();
        int l = s.length();
        s = " " + s;
        int A_score = 0, B_score = 0, A_shots = 0, B_shots = 0, flag = 0,
            A_shots_left = 5, B_shots_left = 5, shots_left = 0;
        Outer:for(int i=1; i<=20; i++)
        {
            char c = s.charAt(i);
            if(i%2==1)
            {
                flag = 0;
                A_shots++;
                A_shots_left--;
                if(c=='1')
                    A_score++;
            }
            else
            {
                flag = 1;
                B_shots++;
                B_shots_left--;
                if(c=='1')
                    B_score++;
            }
            if(i<=10)
            {
                if(A_score<B_score)
                {
                    if(B_score-A_score>A_shots_left)
                    {
                        System.out.println("TEAM-B " + i);
                        break Outer;
                    }
                }
                else
                {
                    if(A_score-B_score>B_shots_left)
                    {
                       System.out.println("TEAM-A " + i);
                       break Outer;
                    }
                }
            }
            else if(i>10 && i<=20)
            {
                if(i%2==0)
                {
                    if(A_score>B_score)
                        System.out.println("TEAM-A " + i);
                    else if(B_score>A_score)
                        System.out.println("TEAM-B " + i);
                    else
                        System.out.println("TIE");
                    break Outer;
                }
            }
        }
    }
  } catch(Exception e) {
    return;
  }
}
</code>```

}

Body:
Here's the question -
https://www.codechef.com/DEC17/problems/CPLAY

And here's my solution -

import java.util.Scanner;

class Penalty_Shoot_Out
{

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        //System.out.println("T: ");
        int T = sc.nextInt();
        sc.nextLine();
        while(T-->0)
        {
            String s = sc.nextLine();
            int l = s.length();
            s = " " + s;
            int A_score = 0, B_score = 0, A_shots = 0, B_shots = 0, flag = 0, A_shots_left = 5, B_shots_left = 5, shots_left = 0;
            Outer:for(int i=1; i<=20; i++)
            {
                char c = s.charAt(i);
                if(i%2==1)
                {
                    flag = 0;
                    A_shots++;
                    A_shots_left--;
                    if(c=='1')
                        A_score++;
                }
                else
                {
                    flag = 1;
                    B_shots++;
                    B_shots_left--;
                    if(c=='1')
                        B_score++;
                }
                if(i<=10)
                {
                    if(A_score<B_score)
                    {
                        if(B_score-A_score>A_shots_left)
                        {
                            System.out.println("TEAM-B " + i);
                            break Outer;
                        }
                    }
                    else
                    {
                        if(A_score-B_score>B_shots_left)
                        {
                           System.out.println("TEAM-A " + i);
                           break Outer;
                        }
                    }
                }
                else if(i>10 && i<=20)
                {
                    if(i%2==0)
                    {
                        if(A_score>B_score)
                            System.out.println("TEAM-A " + i);
                        else if(B_score>A_score)
                            System.out.println("TEAM-B " + i);
                        else
                            System.out.println("TIE");
                        break Outer;
                    }
                }
            }
        }
    }
}

These are the exceptions -

Exception

in thread "main" java.util.NoSuchElementException

    at java.util.Scanner.throwFor(Scanner.java:862)

    at java.util.Scanner.next(Scanner.java:1485)

    at java.util.Scanner.nextInt(Scanner.java:2117)

    at java.util.Scanner.nextInt(Scanner.java:2076)

    at Penalty_Shoot_Out.main(Main.java:8)

I'm getting the correct answer on my computer, but when I submit it online, I get the NZEC Runtime Error.

I tried Googling for solutions and most people said the error might have to do with the main function returning a wrong number or not returning a number. Some said it may be due to the use of a particular function or due to an exception that i am not handling during I/O. However, I haven't been able to figure it out.

I'd really appreciate it if someone could fix my code.

Body:
You should put your solution in a try catch.

public static void main(String args[])
{
  try {
    Scanner sc = new Scanner(System.in);
    //System.out.println("T: ");
    int T = sc.nextInt();
    sc.nextLine();
    while(T-->0)
    {
       String s = sc.nextLine();
        int l = s.length();
        s = " " + s;
        int A_score = 0, B_score = 0, A_shots = 0, B_shots = 0, flag = 0,
            A_shots_left = 5, B_shots_left = 5, shots_left = 0;
        Outer:for(int i=1; i<=20; i++)
        {
            char c = s.charAt(i);
            if(i%2==1)
            {
                flag = 0;
                A_shots++;
                A_shots_left--;
                if(c=='1')
                    A_score++;
            }
            else
            {
                flag = 1;
                B_shots++;
                B_shots_left--;
                if(c=='1')
                    B_score++;
            }
            if(i<=10)
            {
                if(A_score<B_score)
                {
                    if(B_score-A_score>A_shots_left)
                    {
                        System.out.println("TEAM-B " + i);
                        break Outer;
                    }
                }
                else
                {
                    if(A_score-B_score>B_shots_left)
                    {
                       System.out.println("TEAM-A " + i);
                       break Outer;
                    }
                }
            }
            else if(i>10 && i<=20)
            {
                if(i%2==0)
                {
                    if(A_score>B_score)
                        System.out.println("TEAM-A " + i);
                    else if(B_score>A_score)
                        System.out.println("TEAM-B " + i);
                    else
                        System.out.println("TIE");
                    break Outer;
                }
            }
        }
    }
  } catch(Exception e) {
    return;
  }
}

}


问:
Router version issue in angularcli
@angular/cli: 1.4.9
node: 6.11.0
os:   win32 x64
npm : 3.10.10

the rxjs version in package.json file is "rxjs": "^5.4.2".

The same configuration is working on my collegues machine. without giving this error

import statement is like below :

import { Router } from '@angular/router';

Constructor statement is like below :

constructor( private router: Router) {

Routing statement is like below :

this.router.navigate(['policy']);

I am getting below error while using router in .ts  file to navigate from one html5  page to another.

Error coming is like below :

Uncaught (in promise): EmptyError: no elements in sequence
EmptyError: no elements in sequence
    at new EmptyError (EmptyError.js:28)
    at FirstSubscriber.webpackJsonp.../../../../rxjs/_esm5/operators/first.js.FirstSubscriber._complete (first.js:154)
    at FirstSubscriber.webpackJsonp.../../../../rxjs/_esm5/Subscriber.js.Subscriber.complete (Subscriber.js:122)
    at MergeMapSubscriber.webpackJsonp.../../../../rxjs/_esm5/operators/mergeMap.js.MergeMapSubscriber._complete (mergeMap.js:150)

答:
It's most likely an issue with the current version of rxjs
See https://github.com/ReactiveX/rxjs/issues/3151 for details.

// DLDR: Revert your rxjs to max. 5.5.2, that should do the trick

Title: Router version issue in angularcli


问:
How to plot points using Basemap
I have a numpy array precip_subset that has a shape of (31, 60, 48). precip_subset was created by merging 31 datasets; the first variable in the dataset represents the day, the 2nd is a representation of longitude, and the 3rd is a representation of latitude. There is a unique value for precipitation at each position in the dataset; for example, print(precip_subset[1,0,32]) will give me a value of 1.05.

I'll show what I have done so far with my code:

```<code>data_low = precip_subset[(precip_subset > 0) & (precip_subset < 3.14062)]
anomalies = []
for val in data_low:
    if val < 1:
        anomalies.append(val)
        print(anomalies)

data_low_indices1 = np.where((precip_subset > 0) & (precip_subset < 1))
data_low_indices2 = np.array(np.where((precip_subset > 0) & (precip_subset < 1))).T
anomalies_ind = []
for ind in data_low_indices2:
    anomalies_ind.append(ind)
    print(np.asarray(anomalies_ind))
</code>```

Basically, with this code I am able to get the values of precipitation and their indices in the original dataset, precip_subset. From here, I would like to plot this data with Basemap -- I would like to have a point on the map where an anomaly is found. precip_subset was created like so:

```<code>data_path = r"C:\Users\matth\Downloads\TRMM_3B42RT\3B42RT_Daily.201001.7.nc4"
f = Dataset(data_path)

latbounds = [ -31 , -19 ]
lonbounds = [ 131, 146 ]
lats = f.variables['lat'][:]
lons = f.variables['lon'][:]

# latitude lower and upper index
latli = np.argmin( np.abs( lats - latbounds[0] ) )
latui = np.argmin( np.abs( lats - latbounds[1] ) )

# longitude lower and upper index
lonli = np.argmin( np.abs( lons - lonbounds[0] ) )
lonui = np.argmin( np.abs( lons - lonbounds[1] ) )

precip_subset = f.variables['precipitation'][ : , lonli:lonui , latli:latui ]
</code>```

And this is what I have done so far to plot the data using Basemap:

```<code>m = Basemap(llcrnrlon=131.,llcrnrlat=-31,urcrnrlon=146.,urcrnrlat=-19.)
m.drawcoastlines()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1])
m.imshow(anomalies_ind)
plt.show()
</code>```

However, the image I get is not what I would like (see image below).

Does anyone know how I can plot anomalies_ind using Basemap, with a point where each anomaly is found?

答:
imshow just plots the data you give it as an image, overriding anything else. So is definitely not what you want. Since you haven't given any indication of the shape of anomalies_ind, I have put an example here. All you need to do is map the lats and lons to x/y pixel coordinates, and plot them. the 'o' parameter to plot just says to plot circles, rather than lines.

```<code>anomalies_ind = [(-29.027008, 135.547227),
                 (-22.774524, 137.824754)]

lats = np.array(anomalies_ind)[:, 0]
lons = np.array(anomalies_ind)[:, 1]

m = Basemap(llcrnrlon=131.,llcrnrlat=-31,urcrnrlon=146.,urcrnrlat=-19.)
m.drawcoastlines()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1])
#m.imshow(anomalies_ind)

x, y = m(lons, lats)
m.plot(x, y, 'o')

plt.show()
</code>```

Title: How to plot points using Basemap

Body:
I have a numpy array precip_subset that has a shape of (31, 60, 48). precip_subset was created by merging 31 datasets; the first variable in the dataset represents the day, the 2nd is a representation of longitude, and the 3rd is a representation of latitude. There is a unique value for precipitation at each position in the dataset; for example, print(precip_subset[1,0,32]) will give me a value of 1.05.

I'll show what I have done so far with my code:

data_low = precip_subset[(precip_subset > 0) & (precip_subset < 3.14062)]
anomalies = []
for val in data_low:
    if val < 1:
        anomalies.append(val)
        print(anomalies)

data_low_indices1 = np.where((precip_subset > 0) & (precip_subset < 1))
data_low_indices2 = np.array(np.where((precip_subset > 0) & (precip_subset < 1))).T
anomalies_ind = []
for ind in data_low_indices2:
    anomalies_ind.append(ind)
    print(np.asarray(anomalies_ind))

Basically, with this code I am able to get the values of precipitation and their indices in the original dataset, precip_subset. From here, I would like to plot this data with Basemap -- I would like to have a point on the map where an anomaly is found. precip_subset was created like so:

data_path = r"C:\Users\matth\Downloads\TRMM_3B42RT\3B42RT_Daily.201001.7.nc4"
f = Dataset(data_path)

latbounds = [ -31 , -19 ]
lonbounds = [ 131, 146 ]
lats = f.variables['lat'][:]
lons = f.variables['lon'][:]

# latitude lower and upper index
latli = np.argmin( np.abs( lats - latbounds[0] ) )
latui = np.argmin( np.abs( lats - latbounds[1] ) )

# longitude lower and upper index
lonli = np.argmin( np.abs( lons - lonbounds[0] ) )
lonui = np.argmin( np.abs( lons - lonbounds[1] ) )

precip_subset = f.variables['precipitation'][ : , lonli:lonui , latli:latui ]

And this is what I have done so far to plot the data using Basemap:

m = Basemap(llcrnrlon=131.,llcrnrlat=-31,urcrnrlon=146.,urcrnrlat=-19.)
m.drawcoastlines()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1])
m.imshow(anomalies_ind)
plt.show()

However, the image I get is not what I would like (see image below).

Does anyone know how I can plot anomalies_ind using Basemap, with a point where each anomaly is found?

Body:
imshow just plots the data you give it as an image, overriding anything else. So is definitely not what you want. Since you haven't given any indication of the shape of anomalies_ind, I have put an example here. All you need to do is map the lats and lons to x/y pixel coordinates, and plot them. the 'o' parameter to plot just says to plot circles, rather than lines.

anomalies_ind = [(-29.027008, 135.547227),
                 (-22.774524, 137.824754)]

lats = np.array(anomalies_ind)[:, 0]
lons = np.array(anomalies_ind)[:, 1]

m = Basemap(llcrnrlon=131.,llcrnrlat=-31,urcrnrlon=146.,urcrnrlat=-19.)
m.drawcoastlines()
m.drawparallels(np.arange(-90., 120., 30.), labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-180., 181., 45.), labels=[0, 0, 0, 1])
#m.imshow(anomalies_ind)

x, y = m(lons, lats)
m.plot(x, y, 'o')

plt.show()


问:
Regex capture all words in a line before the last 2
I have a bunch of line data I need to capture like so:

```<code>Level production data TD Index
Total Agriculture\Production data TS Index
</code>```

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!

答:
Code

See regex in use here

```<code>.*(?= \S+ \S+)
</code>```

Alternatively: .*(?= [\w\/]+ [\w\/]+) replacing \S with what you define as your valid word character set.

You can also add + after the spaces if there is a possibility of more than 1 space being present as such: .*(?= +\S+ +\S+)

Usage

See code in use here

```<code>import re

r = r".*(?= \S+ \S+)"

l = [
    "Level production data TD Index",
    "Total Agriculture\\Production data TS Index"
]

for s in l:
    m = re.match(r, s)
    if m:
        print m.group(0)
</code>```

Explanation

.* Match any character any number of times

(?= \S+ \S+) Positive lookahead ensuring what follows matches

 Match a literal space

\S+ Match any non-whitespace character one or more times

 Match a literal space

\S+ Match any non-whitespace character one or more times

Body:
I have a bunch of line data I need to capture like so:

Level production data TD Index
Total Agriculture\Production data TS Index

I need to capture everything before the last two words, for example in this case my regex output should be Level production data for the first match.  How can I do this while also assuming varying number of words before the TD Index. Thanks!

Body:
Code

See regex in use here

.*(?= \S+ \S+)

Alternatively: .*(?= [\w\/]+ [\w\/]+) replacing \S with what you define as your valid word character set.

You can also add + after the spaces if there is a possibility of more than 1 space being present as such: .*(?= +\S+ +\S+)

Usage

See code in use here

import re

r = r".*(?= \S+ \S+)"

l = [
    "Level production data TD Index",
    "Total Agriculture\\Production data TS Index"
]

for s in l:
    m = re.match(r, s)
    if m:
        print m.group(0)

Explanation

.* Match any character any number of times

(?= \S+ \S+) Positive lookahead ensuring what follows matches

 Match a literal space

\S+ Match any non-whitespace character one or more times

 Match a literal space

\S+ Match any non-whitespace character one or more times


问:
Konva JS. Change Image position, rotate
I'm adding an image.

```<code>circle = new Image ();
circle.src = '/img/logo.png';
circle.onload = function () {
     anyimage = new Konva.Image ({
          x: 150,
          y: 150,
          image: circle,
          width: 106,
          height: 118
     });
     layer.add (anyimage);
     stage.add (layer);
};
</code>```

How to get and change the position and angle of this picture?
How to change these settings later. By events. For example, clicking on the buttons.
Method this.setX(),this.rotare(), this.x= not work for image obj.

答:
The position and size are as you have set in the new Konva.Image() call. Rotation is demonstrated in this example and below in the working snippet. Basically there is a rotation point set by the 'offset' property of the shape. By default this is at the top left of the image rectangle. You apply the shape's rotate() function setting the single parameter to the amount of degrees to rotate by, with rotation happening around the shapes offset(x,y) position.

See snippet below for a playpen.

Note: I have raised a question with the author over the apparent unexpected behaviour that means when you change the offset position, intending to change the center of rotation, the shape is physically moved.

// Add a stage for the shapes
var stage = new Konva.Stage({
      container: 'container',
      width: 1600,
      height: 400
    });

// add a layer
var layer = new Konva.Layer();
stage.add(layer);

// add a rect to demonstrate rotation
var r = new Konva.Rect({
        x: 60,
        y: 30,
        width: 50,
        height: 50,
        fill: 'red',
        opacity: 0.5,
        strokeWidth: 0})
layer.add(r);

// add a spot to mark the rotate pt
var c = new Konva.Circle({
      x: 45,
      y: 45,
      radius: 4,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4})
layer.add(c);
stage.draw();

// event for plus & minus buttons
$('#plus').on('click', function(evt){
   evt.preventDefault()
   r.rotate(10)
   stage.draw();
})

$('#minus').on('click', function(evt){
   evt.preventDefault()
   r.rotate(-10)
   stage.draw();
})

// function to set rotate point and shape
function setPos(pos){

   r.setAttr('offsetX', pos.x);
   r.setAttr('offsetY', pos.y);
   c.position({
      x: r.x(),
      y: r.y()
    });
    c.moveToTop();
    sayPos();
      stage.draw();
}

$('#ctr').on('click', function(evt){
   evt.preventDefault()
   setPos({x:25, y:25});
})

$('#topLeft').on('click', function(evt){
   evt.preventDefault()
   setPos({x:0, y:0});
})

$('#topRight').on('click', function(evt){
   evt.preventDefault()
   setPos({x:50, y:0});
})

$('#botCtr').on('click', function(evt){
   evt.preventDefault()
   setPos({x:25, y:50});
})

function sayPos(){
  $('#info').html('Rotate pt=' + r.offsetX() + ", " + r.offsetY());
}

// call the setPos() and sayPos() funcs on load.
setPos({x:0, y:0});
sayPos();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p
{
  padding: 4px;

}
#container
{
  background-color: silver;
  overflow: hidden;
}
div
{
padding: 4px;
}</code>```

Click row 1 buttons to set rotate pt and row 2 buttons to rotate by 10 degrees

  <button id='topLeft'>Move rotate pt to top left</button>
  <button id='ctr'>Move rotate pt to center</button>
  <button id='topRight'>Move rotate pt to top right</button>
  <button id='botCtr'>Move rotate pt to bottom center</button>

  <button id='plus'>+10</button>
  <button id='minus'>-10</button>
  Info:

    ```

Title: Konva JS. Change Image position, rotate

Body:
I'm adding an image.

circle = new Image ();
circle.src = '/img/logo.png';
circle.onload = function () {
     anyimage = new Konva.Image ({
          x: 150,
          y: 150,
          image: circle,
          width: 106,
          height: 118
     });
     layer.add (anyimage);
     stage.add (layer);
};

How to get and change the position and angle of this picture?
How to change these settings later. By events. For example, clicking on the buttons.
Method this.setX(),this.rotare(), this.x= not work for image obj.

Body:
The position and size are as you have set in the new Konva.Image() call. Rotation is demonstrated in this example and below in the working snippet. Basically there is a rotation point set by the 'offset' property of the shape. By default this is at the top left of the image rectangle. You apply the shape's rotate() function setting the single parameter to the amount of degrees to rotate by, with rotation happening around the shapes offset(x,y) position.

See snippet below for a playpen.

Note: I have raised a question with the author over the apparent unexpected behaviour that means when you change the offset position, intending to change the center of rotation, the shape is physically moved.

// Add a stage for the shapes
var stage = new Konva.Stage({
      container: 'container',
      width: 1600,
      height: 400
    });

// add a layer
var layer = new Konva.Layer();
stage.add(layer);

// add a rect to demonstrate rotation
var r = new Konva.Rect({
        x: 60,
        y: 30,
        width: 50,
        height: 50,
        fill: 'red',
        opacity: 0.5,
        strokeWidth: 0})
layer.add(r);

// add a spot to mark the rotate pt
var c = new Konva.Circle({
      x: 45,
      y: 45,
      radius: 4,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4})
layer.add(c);
stage.draw();

// event for plus & minus buttons
$('#plus').on('click', function(evt){
   evt.preventDefault()
   r.rotate(10)
   stage.draw();
})

$('#minus').on('click', function(evt){
   evt.preventDefault()
   r.rotate(-10)
   stage.draw();
})

// function to set rotate point and shape
function setPos(pos){

   r.setAttr('offsetX', pos.x);
   r.setAttr('offsetY', pos.y);
   c.position({
      x: r.x(),
      y: r.y()
    });
    c.moveToTop();
    sayPos();
      stage.draw();
}

$('#ctr').on('click', function(evt){
   evt.preventDefault()
   setPos({x:25, y:25});
})

$('#topLeft').on('click', function(evt){
   evt.preventDefault()
   setPos({x:0, y:0});
})

$('#topRight').on('click', function(evt){
   evt.preventDefault()
   setPos({x:50, y:0});
})

$('#botCtr').on('click', function(evt){
   evt.preventDefault()
   setPos({x:25, y:50});
})

function sayPos(){
  $('#info').html('Rotate pt=' + r.offsetX() + ", " + r.offsetY());
}

// call the setPos() and sayPos() funcs on load.
setPos({x:0, y:0});
sayPos();

p
{
  padding: 4px;

}
#container
{
  background-color: silver;
  overflow: hidden;
}
div
{
padding: 4px;
}

<div id='info1'></div>
<div id='info2'></div>

<div>Click row 1 buttons to set rotate pt and row 2 buttons to rotate by 10 degrees</div>
<div>
  <button id='topLeft'>Move rotate pt to top left</button>
  <button id='ctr'>Move rotate pt to center</button>
  <button id='topRight'>Move rotate pt to top right</button>
  <button id='botCtr'>Move rotate pt to bottom center</button>
</div>
<div>
  <button id='plus'>+10</button>
  <button id='minus'>-10</button>
  <span id='info'>Info:</span>
</div>
  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>


问:
Servlet controller - Redirect with parameters
I'm using Spring MVC web app: Servlet + JSP + Hibernate. This is a part from my CustomerController.java

```<code>@RequestMapping(value="/CustomerList", method = RequestMethod.GET)
public ModelAndView customerList() {
    ModelAndView model = new ModelAndView();
    model.setViewName("Customer.List"); // for Tiles View
    model.addObject("listCustomer", DAO_Customer.getListCustomer());
    return model;
}

@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, Model model) {
    boolean isSuccess = DAO_Customer.deleteCustomer(id);
    if (!isSuccess) {
        model.addAttribute("error", "Failed");
    }
    model.addAttribute("success", "Successed");

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

and here is the code in CustomerList.jsp file to display:

```<code>...
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${not empty error}">
    <p>${error}</p>
</c:if>
<c:if test="${not empty success}">
    <p>${success}</p>
</c:if>
...
</code>```

I want to redirect to /CustomerList and include parameters error + success.

The problem is, when I run, it return /CustomerList?success=Successed and nothing show up expect the default customer list

I search a lot but really don't know how to do what I want. Thanks everyone for read and help.

答:
You can try with RedirectAttributes#addAttribute.

```<code>@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
  boolean isSuccess = DAO_Customer.deleteCustomer(id);
  if (!isSuccess) {
    redirectAttributes.addAttribute("error", "Failed");
  } else{ //also required
    redirectAttributes.addAttribute("success", "Successed");
  }
  return "redirect:/CustomerList";
}
</code>```

In this case, the url will turn into /CustomerList?success=Successed if successful.

And you can access param value with EL as follows:

```<code>${param.success} or ${param.error}
</code>```

Also you can use RedirectAttributes#addFlashAttribute.

```<code>redirectAttributes.addFlashAttribute("success", "Successed");
</code>```

Then you can access directly as ${success} or ${error}.

Body:
I'm using Spring MVC web app: Servlet + JSP + Hibernate. This is a part from my CustomerController.java

@RequestMapping(value="/CustomerList", method = RequestMethod.GET)
public ModelAndView customerList() {
    ModelAndView model = new ModelAndView();
    model.setViewName("Customer.List"); // for Tiles View
    model.addObject("listCustomer", DAO_Customer.getListCustomer());
    return model;
}

@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, Model model) {
    boolean isSuccess = DAO_Customer.deleteCustomer(id);
    if (!isSuccess) {
        model.addAttribute("error", "Failed");
    }
    model.addAttribute("success", "Successed");

    return "redirect:/CustomerList";
}

and here is the code in CustomerList.jsp file to display:

...
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${not empty error}">

${error}

</c:if>
<c:if test="${not empty success}">

${success}

</c:if>
...

I want to redirect to /CustomerList and include parameters error + success.

The problem is, when I run, it return /CustomerList?success=Successed and nothing show up expect the default customer list

I search a lot but really don't know how to do what I want. Thanks everyone for read and help.

Body:
You can try with RedirectAttributes#addAttribute.

@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
  boolean isSuccess = DAO_Customer.deleteCustomer(id);
  if (!isSuccess) {
    redirectAttributes.addAttribute("error", "Failed");
  } else{ //also required
    redirectAttributes.addAttribute("success", "Successed");
  }
  return "redirect:/CustomerList";
}

In this case, the url will turn into /CustomerList?success=Successed if successful.

And you can access param value with EL as follows:

${param.success} or ${param.error}

Also you can use RedirectAttributes#addFlashAttribute.

redirectAttributes.addFlashAttribute("success", "Successed");

Then you can access directly as ${success} or ${error}.


问:
Is it possible to define instructions to be executed at the end of compilation? (Crystal lang)
Let's say a Crystal project is using different shards. And each shard wants to do cleanup at the end of compilation of the overall project. Is it possible using Macros?

Something like this for example:

```<code>{% at_end %}
  {% system("rm 'tmp files'") %}
{% end %}
</code>```

答:
If you need to share data between multiple macros, you can use Hash or Array, and access them through a Constant which associated AST node is accessible from macros.

Here is an example demonstrating this (live at https://carc.in/#/r/372k):

```<code>STORAGE = [] of _

macro add(node)
  {% STORAGE << node %}
end

macro list
  {% for elem in STORAGE %}
    {% puts "Elem: #{elem}" %}
  {% end %}
end

add 1
add 2
add "hello"
add :world
add({a: 1, b: 2})
add 3 + 4
add a_call(arg1, 2)

list
</code>```

The important parts here is:

```<code>STORAGE = [] of _
</code>```

Here I'm declaring an array of a certain type (which is non relevant in this case, as the array is only accessed through macros, you can't use this type (_) in normal code). The macro system only needs to know that it is an array.

```<code>macro add(node)
  {% STORAGE << node %}
end
</code>```

Then I create a macro that will be able to mutate the array AST node (which is type ArrayLiteral in the macro system).
Note that it allows you to store any kind of AST node, from simple nodes like NumberLiteral or SymbolLiteral, to complex nodes like a Call, a Def or even a ClassDef.

```<code>macro list
  {% for elem in STORAGE %}
    {% puts "Elem: #{elem}" %}
  {% end %}
end
</code>```

And finally I create a macro that will simply print (at compile time) the content of the STORAGE array.

The same can be done with a HashLiteral:

```<code>STORAGE = {} of _ => _
</code>```

And in the same way as explained above, you can use any kind of AST nodes as the key or the value.

Note that the Constants you use in the macro system can also be seen by normal code, and it's possible to have name clash (what if the user wants to use a constant STORAGE too for his own code?).
To minimize this possibility (if this is not wanted), I suggest you to put your constants in a special module like MyShard::MacroStorage::SomeInterestingNodes or use some complicated naming pattern like M____ACRO_Storage____01234 (<-- this is unlikely to be used by the user ;) )

Body:
Let's say a Crystal project is using different shards. And each shard wants to do cleanup at the end of compilation of the overall project. Is it possible using Macros?

Something like this for example:

{% at_end %}
  {% system("rm 'tmp files'") %}
{% end %}

Body:
If you need to share data between multiple macros, you can use Hash or Array, and access them through a Constant which associated AST node is accessible from macros.

Here is an example demonstrating this (live at https://carc.in/#/r/372k):

STORAGE = [] of _

macro add(node)
  {% STORAGE << node %}
end

macro list
  {% for elem in STORAGE %}
    {% puts "Elem: #{elem}" %}
  {% end %}
end

add 1
add 2
add "hello"
add :world
add({a: 1, b: 2})
add 3 + 4
add a_call(arg1, 2)

list

The important parts here is:

STORAGE = [] of _

Here I'm declaring an array of a certain type (which is non relevant in this case, as the array is only accessed through macros, you can't use this type (_) in normal code). The macro system only needs to know that it is an array.

macro add(node)
  {% STORAGE << node %}
end

Then I create a macro that will be able to mutate the array AST node (which is type ArrayLiteral in the macro system).
Note that it allows you to store any kind of AST node, from simple nodes like NumberLiteral or SymbolLiteral, to complex nodes like a Call, a Def or even a ClassDef.

macro list
  {% for elem in STORAGE %}
    {% puts "Elem: #{elem}" %}
  {% end %}
end

And finally I create a macro that will simply print (at compile time) the content of the STORAGE array.

The same can be done with a HashLiteral:

STORAGE = {} of _ => _

And in the same way as explained above, you can use any kind of AST nodes as the key or the value.

Note that the Constants you use in the macro system can also be seen by normal code, and it's possible to have name clash (what if the user wants to use a constant STORAGE too for his own code?).
To minimize this possibility (if this is not wanted), I suggest you to put your constants in a special module like MyShard::MacroStorage::SomeInterestingNodes or use some complicated naming pattern like M____ACRO_Storage____01234 (<-- this is unlikely to be used by the user ;) )


问:
how to make this mysql sub query work
```<code>SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC
</code>```

<p>// error is : AND jumlah > 1</p>

答:
try:</p>

```<code>SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN ( SELECT noreg FROM register_keluar AND c.idunit LIKE '20%')
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC
</code>```

Title: how to make this mysql sub query work

Body:
SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN (

SELECT noreg
FROM register_keluar
)
AND (
c.idunit LIKE '20%'
)
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC

// error is : AND jumlah > 1

Body:
try:

SELECT c.noreg AS noreg, count( * ) AS jumlah
FROM kamar a, reservasi b, register c, identitas_psn d, sub_unit_kamar e
WHERE a.idkamar = b.kamar
AND b.noreg = c.id_reg_lengkap
AND c.norm = d.norm
AND c.idunit = e.id_subunit
AND c.noreg NOT
IN ( SELECT noreg FROM register_keluar AND c.idunit LIKE '20%')
AND jumlah > 1
GROUP BY noreg
ORDER BY jumlah DESC


问:
Apache Ignite - how to check if Key already exists?
What is the best approach to check if Key exists in a cache already and if does not - create a new one:

```<code>cache.put("key3", 1);
</code>```

I want to increase a Value by 1 if key already exists and if it does not - set it to 1.

答:
The simplest method seems to be to use getAndPutIfAbsent().

I'm still a bit unclear about how optimistic and pessimistic transactions would lock the non-existence of the object when using the other methods, in order to prevent overwriting an object just created in concurrent transaction.

Body:
What is the best approach to check if Key exists in a cache already and if does not - create a new one:

cache.put("key3", 1);

I want to increase a Value by 1 if key already exists and if it does not - set it to 1.