问:
How to create POJO from the web service that returns dataset(<Object> any)
Sorry if the below is stupid question, I tried many sites to get the clear response, but since I'm a novice in web service I couldn't understand anything.

I have been given a WSDL file that looks up the server and returns the response in below format

```<code><soap:envelop>
    ...
    ..
    <Aresponse>
        <XXXDAtaset>
            <xs:schema>
                <xs:element>
                    <xs:choice>
                        .....
                        .....(Elements are here)

                    </xs:choice>
                </xs:element>
            </xs:schema>
        </XXXDAtaset>
        <diffgr:diffgram>
            <dataset rows>
                -- values are here
            </dataset rows>
        </diffgr:diffgram>
    </Aresponse>
    ..
</soap:envelop>
</code>```

I don't have any POJO to store these values (POJO was not even created when creating client from WSDL). Initial WSDL has <s:any> for this response.

How will I create POJO for this SOAP message? I don't know if I have to ask the WSDL provider or any JAXB tools available out there to generate the POJO for this.

I tried this link How to create java object from 'anyType' returned from service using JAXB? but there it seems they already have some POJO to store the response. In my case, I don't have one.

答:
Ask your provider for a sample request response soap xml.

Strip it off the soap envelope,header,body

You can strip off the namespace too and place it like

<someTag xmlns=""> instead of <xs:someTag>
    where xs="given namespace"

use tool/api like xsd generator to convert your bare minimum xml to  pojo

In SOAP protocol header and envelope are rarely changed in a production, as they contain namespace and credentials mainly. So you can write a helper method to append/remove these 'SOAP  components' during marshall/unmarshall

This should help you get started in the right direction.

Body:
Sorry if the below is stupid question, I tried many sites to get the clear response, but since I'm a novice in web service I couldn't understand anything.

I have been given a WSDL file that looks up the server and returns the response in below format

<soap:envelop>
    ...
    ..
    <Aresponse>
        <XXXDAtaset>
            <xs:schema>
                <xs:element>
                    <xs:choice>
                        .....
                        .....(Elements are here)

                    </xs:choice>
                </xs:element>
            </xs:schema>
        </XXXDAtaset>
        <diffgr:diffgram>
            <dataset rows>
                -- values are here
            </dataset rows>
        </diffgr:diffgram>
    </Aresponse>
    ..
</soap:envelop>

I don't have any POJO to store these values (POJO was not even created when creating client from WSDL). Initial WSDL has <s:any> for this response.

How will I create POJO for this SOAP message? I don't know if I have to ask the WSDL provider or any JAXB tools available out there to generate the POJO for this.

I tried this link How to create java object from 'anyType' returned from service using JAXB? but there it seems they already have some POJO to store the response. In my case, I don't have one.


来源: stackexchange

问:
Bluemix API connect configuration
WE have our REST services deployed using bluemix container groups. Can some one tell me how to configure access to these APIs through Bluemix API Connect? I Created product, catalog. Also imported my swagger in catalog. I can see the APIs listed. but not able to access them. Can someone guide?</p>

答:
on Bluemix to call your api , you need to "publish" your product to a portal. First of all prepare your Portal:
Go to Dashboard -- > Your Catalog -- > Settings -- > Enable Portal and select Portal-Delegated-User-Registry.

After some time , you will be accessing your portal . Subscribe new user through that portal. Portal GUI is very helpful. You will be able to learn by yourself how to call your API.

Good luck!

ContentLicense: CC BY-SA 3.0

Title: Bluemix API connect configuration


问:
Creating a secondary index page with identical sections as primary index page but different content?
I'm attempting to create a secondary index page for a theme that I'm working on. It would have the same sections as the primary index page, but with different content. I don't mind hardcoding this instead of it being editable from theme editor.

I've created a new index template called secondary, and copied the code from index.liquid into it. Everything shows up fine.

Then I tried to create a new block in the settings_data.json, right under content_for_index called content_for_secondary, but trying to call it in my new page template isn't working.

I've looked all over for documentation but I can't seem to find exactly how Shopify is handling sections in the settings_data.json and how I can create a new array of sections to call in an alternate template.

Has anyone had any experience with this?

答:
You might create a page template, for example called secondary_home.

Then, duplicate available sections for homepage (do not use the same or content will be the same), and include them in your new template.

Create a page using the template you created.
Load page in "Customize theme" then set settings for each sections.

Please note that this is only possible with statics sections as dynamic ones are only available for home.


问:
replace more than white space with some value in python
I want to replace more than one white spaces from string with "@".
If one white space is there it should be intact but if there is more than one consecutive whitespace then it will keep one and append @. For example

```<code>s = "Hello how  are   you."
</code>```

would become

```<code>"Hello how @are @@you"
</code>```

答:
Edit: Having looked at the source of your question, my answer didn't fix it. I couldn't see the extra spaces in your source string. A regular expression as sg.sysel suggests will do the job nicely.

In case you did want to do it yourself with a loop:

```<code>def addats(s):
    i = 0
    r = ''
    for c in s:
        if c == ' ':
            if i > 0:
                r += '@'
            else:
                r += ' '
            i += 1
        else:
            r += c
            i = 0
    return r
</code>```

Note that for a real application, you should use something mutable like a list instead of a string for r there, but this should solve your immediate problem.

Body:
I want to replace more than one white spaces from string with "@".
If one white space is there it should be intact but if there is more than one consecutive whitespace then it will keep one and append @. For example

s = "Hello how  are   you."

would become

"Hello how @are @@you"

Body:
Edit: Having looked at the source of your question, my answer didn't fix it. I couldn't see the extra spaces in your source string. A regular expression as sg.sysel suggests will do the job nicely.

In case you did want to do it yourself with a loop:

def addats(s):
    i = 0
    r = ''
    for c in s:
        if c == ' ':
            if i > 0:
                r += '@'
            else:
                r += ' '
            i += 1
        else:
            r += c
            i = 0
    return r

Note that for a real application, you should use something mutable like a list instead of a string for r there, but this should solve your immediate problem.


问:
How can I monkey-patch an instance method in Perl?
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

```<code>sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;
</code>```

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

答:
Edit: This was an incorrect attempt at a solution that I'm keeping for posterity. Look at the upvoted/accepted answers. :-)

Ah, I just realized that the syntax needs a little bit of adjustment:

```<code>$agent->{get_basic_credentials} = _user_agent_get_basic_credentials_patch;
</code>```

Without the {} delimiters it looks like a method invocation (which would not be a valid l-value).

I'd still like to know how the instance method gets bound/looked up via this syntax. TIA!

OwnerDisplayName: cdleary

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to monkey-patch (duck-punch :-) a LWP::UserAgent instance, like so:

sub _user_agent_get_basic_credentials_patch {
  return ($username, $password);
}

my $agent = LWP::UserAgent->new();
$agent->get_basic_credentials = _user_agent_get_basic_credentials_patch;

This isn't the right syntax -- it yields:

Can't modify non-lvalue subroutine
  call at [module] line [lineno].

As I recall (from Programming Perl), dispatch lookup is performed dynamically based on the blessed package (ref($agent), I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.

I know that I can subclass the UserAgent, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)

LastEditorDisplayName: cdleary

Body:
Edit: This was an incorrect attempt at a solution that I'm keeping for posterity. Look at the upvoted/accepted answers. :-)

Ah, I just realized that the syntax needs a little bit of adjustment:

$agent->{get_basic_credentials} = _user_agent_get_basic_credentials_patch;

Without the {} delimiters it looks like a method invocation (which would not be a valid l-value).

I'd still like to know how the instance method gets bound/looked up via this syntax. TIA!


问:
Additional partial classes for a Form
We have a big Form class that we like to split into peaces using partial class approach

That could be done by manually modifying a project file, and adding MainFormPN.vb entry

```<code><Compile Include="MainForm.vb">
  <SubType>Form</SubType>
</Compile>
<Compile Include="MainForm.Designer.vb">
  <DependentUpon>MainForm.vb</DependentUpon>
  <SubType>Form</SubType>
</Compile>
<Compile Include="MainFormPN.vb">
  <DependentUpon>MainForm.vb</DependentUpon>
</Compile>
</code>```

The issue with this approach is when double click on this item in VS2008 IDE it shows new empty form, not MainForm UI. It looks like VS2008 does not support multiple partial classes for a Forms. Is it possible to do that?

答: Another possible approach to would be to encapsulate groups of functionality into user controls.  This will encapsulate logic, make the code easier to manage (if done right), and allow you the same effect without the goofiness of VS and partial form classes in terms of the GUI designer.</p>

Title: Additional partial classes for a Form

Body:
We have a big Form class that we like to split into peaces using partial class approach

That could be done by manually modifying a project file, and adding MainFormPN.vb entry

<Compile Include="MainForm.vb">
  <SubType>Form</SubType>
</Compile>
<Compile Include="MainForm.Designer.vb">
  <DependentUpon>MainForm.vb</DependentUpon>
  <SubType>Form</SubType>
</Compile>
<Compile Include="MainFormPN.vb">
  <DependentUpon>MainForm.vb</DependentUpon>
</Compile>

The issue with this approach is when double click on this item in VS2008 IDE it shows new empty form, not MainForm UI. It looks like VS2008 does not support multiple partial classes for a Forms. Is it possible to do that?


问:
javascript bootstrap-multiselect get all selected values on button click
I want to get all selected values of bootstrap-multiselect on button click.

My JSP page code is given below

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('#ddlPermission').multiselect({
            buttonWidth : '100%',
            maxHeight : 100,
            includeSelectAllOption : true,
            dropRight : true
        });
    });

    function myFunction() {
        var allVal=$("ddlPermission").val();
        alert(allVal);
        return false;
    }
</script>
<body>
    <select id="ddlPermission" multiple="multiple" name="permission_ddl">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>
    <input type="submit" name="btnSubmit" id="btnSubmit" onclick="myFunction()" class="button active" value="Submit">
</body>
</code>```

I am using Java JSP.

答:
Working fiddle.

You're missing the id sign # in the following line :

```<code>var allVal=$("ddlPermission").val();
</code>```

Should be :

```<code>var allVal=$("#ddlPermission").val();
</code>```

Hope this helps.

Body:
I want to get all selected values of bootstrap-multiselect on button click.

My JSP page code is given below

    <select id="ddlPermission" multiple="multiple" name="permission_ddl">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        <option value="D">D</option>
    </select>
    <input type="submit" name="btnSubmit" id="btnSubmit" onclick="myFunction()" class="button active" value="Submit">

I am using Java JSP.

Body:
Working fiddle.

You're missing the id sign # in the following line :

var allVal=$("ddlPermission").val();

Should be :

var allVal=$("#ddlPermission").val();

Hope this helps.


问:
How to hide overlay on mouse hover
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

答:
If you want to remove overlay, remove transform property from .upper class

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div></code>```

Title: How to hide overlay on mouse hover

Body:
Here is my code, what i want is to hide overlay after mouse hover, and what is happening is its staying active until i remove mouse hover on the image. is there any one can solve this problem

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; transform: translate(-50%, -50%); width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}

 heading

Body:
If you want to remove overlay, remove transform property from .upper class

.upper {position: absolute; top: 50%; bottom: 0; left: 50%; width: 0; height: 0; overflow: hidden; background: #ddd; opacity: 0.5; transition: .2s ease; border-radius: 100%;}
.maine:hover .upper {width: 150%; height: 150%;}
.maine {position: relative; overflow: hidden;}
.upper:after {width 0; height: 0;}

<div class="col-md-2">
  <div class="maine">
    <img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" class="img-responsive">
    <div class="upper"> heading </div>
</div>
</div>


问:
Lift/Scala: How to redirect to a page and add a cookie?
I need to redirect user to the homepage and add a cookie.
Following code only redirects but doesnt add a cookie.

```<code>S.addCookie(HTTPCookie("foo", "bar"))
S.redirectTo("/")
</code>```

Please advise. Thanks.

```<code>object Auth extends RestHelper {
  def init() {
    LiftRules.dispatch.append(Auth)
  }

  serve {
    case "auth" :: "xxvvvxx" :: Nil Get request => {
      val firstName = request.param("first_name").openOrThrowException("First Name not available")
      val session = request.param("session").openOrThrowException("Session not available")
      S.addCookie(HTTPCookie("session", session))
      S.redirectTo("/")
    }
  }
}
</code>```

答:
S has also the following redirect method (documentation here)

```<code>def redirectTo(where: String, func: () ⇒ Unit): Nothing
</code>```

That takes a function to be executed after the redirect.

So you can also do something like this

```<code>S.redirectTo("/", () => S.addCookie(HTTPCookie("session", session).setPath("/").setMaxAge(999999)))
</code>```

Body:
I need to redirect user to the homepage and add a cookie.
Following code only redirects but doesnt add a cookie.

S.addCookie(HTTPCookie("foo", "bar"))
S.redirectTo("/")

Please advise. Thanks.

object Auth extends RestHelper {
  def init() {
    LiftRules.dispatch.append(Auth)
  }

  serve {
    case "auth" :: "xxvvvxx" :: Nil Get request => {
      val firstName = request.param("first_name").openOrThrowException("First Name not available")
      val session = request.param("session").openOrThrowException("Session not available")
      S.addCookie(HTTPCookie("session", session))
      S.redirectTo("/")
    }
  }
}

Body:
S has also the following redirect method (documentation here)

def redirectTo(where: String, func: () ⇒ Unit): Nothing

That takes a function to be executed after the redirect.

So you can also do something like this

S.redirectTo("/", () => S.addCookie(HTTPCookie("session", session).setPath("/").setMaxAge(999999)))


问:
Specifying a font in AutoComplete TextBox
Has anyone managed to modify the default font size for a AutoComplete TextBox, Windows Forms.</p>

答:
No, the underline Windows API does not have an option to change the font size. If you need to customize the suggest list's appearance you need to implement autocomplete by yourself.

Suggested reading:AUTOCOMPLETEOPTIONS


问:
Using GSON to parse Json into a JAVA Object where the Json Elements may vary
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

```<code>    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }
</code>```

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

```<code>public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}
</code>```

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

```<code>Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
</code>```

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON

答:
First I believe your JSON should look like this:

```<code>{
  "events": [
    {
      "name": "event0",
      "a": "abc",
      "b": "def"
    },
    {
      "name": "event1",
      "a": "abc",
      "b": "def",
      "c": "mno"
    }
  ]
}
</code>```

This will need two classes for your model:

```<code>public List<Event> events = null;

public class Event {
public String name;
public String a;
public String b;
public String c;

}
</code>```

And then then with GSON

```<code>Events events = gson.fromJson(jsonData, Events.class);
</code>```

Also I recommend to always use an online validator for JSON so you are sure your JSON structure is correct before coding against it.
https://jsonlint.com/
Or for formate the JSON:
http://jsonprettyprint.com/

Also this website can create the Java classes for you from either a JSON Schema or by using an example file.
http://www.jsonschema2pojo.org/

Body:
I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:

    {
        "event0" : {
        "a" : "abc",
        "b" : "def"
        },

        "event1" : {
        "a" : "ghi",
        "b" : "jkl",
        "c" : "mno"
        }
    }

I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:

public class Event {
    private String a;
    private String b;
    private String c;

    public Event() {}

}

The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.

Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:

Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);

But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.

I am fairly new to JSON parsing, and might have missed something in the following answers:

Using Gson to convert Json into Java Object

Mapping JSON into POJO using Gson

Using gson to parse json to java object

Parse JSON into a java object

How to parse a json file into a java POJO class using GSON

Body:
First I believe your JSON should look like this:

{
  "events": [
    {
      "name": "event0",
      "a": "abc",
      "b": "def"
    },
    {
      "name": "event1",
      "a": "abc",
      "b": "def",
      "c": "mno"
    }
  ]
}

This will need two classes for your model:

public List<Event> events = null;

public class Event {
public String name;
public String a;
public String b;
public String c;

}

And then then with GSON

Events events = gson.fromJson(jsonData, Events.class);

Also I recommend to always use an online validator for JSON so you are sure your JSON structure is correct before coding against it.
https://jsonlint.com/
Or for formate the JSON:
http://jsonprettyprint.com/

Also this website can create the Java classes for you from either a JSON Schema or by using an example file.
http://www.jsonschema2pojo.org/


问:
How to increase the size of icons in jqgrid?
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css</p>

```<code>.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}
</code>```

答:
Another possible solution is to increase the font-size - see the classes

```<code>.ui-jqgrid .ui-jqgrid-view
</code>```

and increase the font size you want.

Since you use Guriddo jqGrid 5.2.1 you can get quick and professional response in our public forum

Body:
How should I increase the size of icons(add,delete..) in jqgrid?I have written following code in ui.jqgrid.css

.ui-jqgrid .ui-jqgrid-pager .ui-pg-div  span.ui-icon,
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div  span.ui-icon{float:left;margin: 2px; width:18px;}
.ui-jqgrid .ui-jqgrid-toppager {border-left: 0 none !important;border-right: 0 none !important; border-top: 0 none
!important; margin: 0 !important; padding: 0 !important; position: relative;white-space: nowrap;overflow: hidden;}

Body:
Another possible solution is to increase the font-size - see the classes

.ui-jqgrid .ui-jqgrid-view

and increase the font size you want.

Since you use Guriddo jqGrid 5.2.1 you can get quick and professional response in our public forum


问:
Guard let construction, still getting fatal error: Index out of range
I am trying to parse some data with this code:

```<code>func findDate(data: String?) -> String {
    guard let date: String? = (data!.componentsSeparatedByString("T"))[0] else{
        return "20000101"
    }
    return date!
}
</code>```

I tried the guard structure to prevent errors when there is no data found, or it has a different structure, but I still get the error when I run it:

fatal error: Index out of range

Does somebody know how to fix this?

答:
There are two issues here:

1) Trying to access an index of an array that isn't large enough doesn't produce nil, it just crashes. For example, this code will crash:

```<code>let strings: [String] = []
guard let firstString = strings[0] else {
    // couldn't find firstString
}
</code>```

Instead, use the first method:

```<code>let strings: [String] = []
guard let firstString = strings.first else {
    // couldn't find firstString
}
</code>```

first attempts to access the first element of the array, and it returns nil if the array doesn't have a first element.

2) The purpose of guard let is to guarantee that the value you get out isn't nil. So your date value should be of type String, not String?, and you shouldn't have to force-unwrap it. For example:

```<code>let strings: [String] = ["one", "two", "three"]
guard let firstString = strings.first else {
    // no first string
}
print(firstString) // firstString is not nil, no need to unwrap it
</code>```

Body:
I am trying to parse some data with this code:

func findDate(data: String?) -> String {
    guard let date: String? = (data!.componentsSeparatedByString("T"))[0] else{
        return "20000101"
    }
    return date!
}

I tried the guard structure to prevent errors when there is no data found, or it has a different structure, but I still get the error when I run it:

fatal error: Index out of range

Does somebody know how to fix this?

Body:
There are two issues here:

1) Trying to access an index of an array that isn't large enough doesn't produce nil, it just crashes. For example, this code will crash:

let strings: [String] = []
guard let firstString = strings[0] else {
    // couldn't find firstString
}

Instead, use the first method:

let strings: [String] = []
guard let firstString = strings.first else {
    // couldn't find firstString
}

first attempts to access the first element of the array, and it returns nil if the array doesn't have a first element.

2) The purpose of guard let is to guarantee that the value you get out isn't nil. So your date value should be of type String, not String?, and you shouldn't have to force-unwrap it. For example:

let strings: [String] = ["one", "two", "three"]
guard let firstString = strings.first else {
    // no first string
}
print(firstString) // firstString is not nil, no need to unwrap it


问:
Move up cache bar from down to header
I'm trying to move up the cache bar at the webpage: http://www.skandicinkasso.de/ -  cant move the element because it is at the bottom of the "DOM"

I have been trying remove that positioning, and put the element inline where i wanted it, but i cant do that way.

i want to move the bar to here: http://prntscr.com/fsqb5d

答:
Isn't that enough?  </p>

```<code>    .ginger_container.bottom {
      border-top: 1px solid #cccccc !important;
      top: 125px;
      height: 28px;
     }
</code>```

Title: Move up cache bar from down to header

Body:
Isn't that enough?

    .ginger_container.bottom {
      border-top: 1px solid #cccccc !important;
      top: 125px;
      height: 28px;
     }


问:
Datatables - Show a specific row at the top of the table
I have Datatables running fine on one of my projects. I'm trying to display a certain row at the top of the table if it contains a certain string.

Is there any way to do this as I cannot find anything in the datatables documentation.

答:
add a hidden column ,put a higher value in the specific row and use "aaSortingFixed". (I think in the new version is "orderFixed")

```<code> <table>
  <thead>
    <th>
      <td class="hidden"></td>
      <td>name</td>
      <td>age</td>
      <td>salary</td>
    </th>
  </thead>
  <tbody>
    <tr>
      <td class="hidden">100</td>
      <td>Taylor Murphy</td>
      <td>26</td>
      <td>$62k - $68k</td>
    </tr>
    <tr>
      <td class="hidden">0</td>
      <td>Jared Henderson</td>
      <td>26</td>
      <td>$59k - $64k</td>
    </tr>
    <tr>
      <td class="hidden">0</td>
      <td>Rolando Yates</td>
      <td>26</td>
      <td>$49k - $53k</td>
    </tr>
  </tbody>
</table>
</code>```

here 100 is the higher value which we want stick it on top

```<code>$('table').DataTable( {
    "aaSortingFixed": [[0,'desc']]
});
</code>```

now we can reOrder the table but the row with 100 value will be always on the top

Body:
add a hidden column ,put a higher value in the specific row and use "aaSortingFixed". (I think in the new version is "orderFixed")

 <table>
  <thead>
    <th>
      <td class="hidden"></td>
      <td>name</td>
      <td>age</td>
      <td>salary</td>
    </th>
  </thead>
  <tbody>
    <tr>
      <td class="hidden">100</td>
      <td>Taylor Murphy</td>
      <td>26</td>
      <td>$62k - $68k</td>
    </tr>
    <tr>
      <td class="hidden">0</td>
      <td>Jared Henderson</td>
      <td>26</td>
      <td>$59k - $64k</td>
    </tr>
    <tr>
      <td class="hidden">0</td>
      <td>Rolando Yates</td>
      <td>26</td>
      <td>$49k - $53k</td>
    </tr>
  </tbody>
</table>

here 100 is the higher value which we want stick it on top

$('table').DataTable( {
    "aaSortingFixed": [[0,'desc']]
});

now we can reOrder the table but the row with 100 value will be always on the top


问:
Loop through an array column in order to find the required values python
I have a minimum and a maximum value, i also have a 70X3 array. I would like to find all the values from the second column of the array which are within the range of the min and max value and export all 3 columns of the array for those values.

For example

```<code>A=[2,3,4
   3,5,6
   5,5,5
   5,6,7
   10,11,22
   3,50,6]
</code>```

Max value is 11 and min is 5 the result of the matrix would be something like

```<code>B=[3,5,6
   5,5,5
   5,6,7
   10,11,22]
</code>```

Up till now i what i did is :

```<code>for i in MatrixA[:,1]):
    if i<maximum and i>minimum:
        aa.append(i)
aa=np.asarray(aa)
</code>```

But this only finds the range of values i need from the second column and not the corresponding values from column 1 and 3

Body:
I have a minimum and a maximum value, i also have a 70X3 array. I would like to find all the values from the second column of the array which are within the range of the min and max value and export all 3 columns of the array for those values.

For example

A=[2,3,4
   3,5,6
   5,5,5
   5,6,7
   10,11,22
   3,50,6]

Max value is 11 and min is 5 the result of the matrix would be something like

B=[3,5,6
   5,5,5
   5,6,7
   10,11,22]

Up till now i what i did is :

for i in MatrixA[:,1]):
    if i<maximum and i>minimum:
        aa.append(i)
aa=np.asarray(aa)

But this only finds the range of values i need from the second column and not the corresponding values from column 1 and 3

Body:
With simple numpy expression:

import numpy as np
a = np.array([[2,3,4],[3,5,6], [5,5,5], [5,6,7],[10,11,22], [3,50,6]])
b = a[(a[:,1] >= 5) & (a[:,1] <= 11)]

print(b)

The output:

[[ 3  5  6]
 [ 5  5  5]
 [ 5  6  7]
 [10 11 22]]

a[:,1] - considering values from specified axis (1 axis, 2nd column)


问:
How to share gradle cache with docker containers
We run gradle builds within docker containers (the reason for that is the build requires software we don't want to install on the host; node, wine etc. Not even java or gradle is installed on the host).

Launching each container with an empty cache is annoying slow.

I've set up gradle-4.0's http build cache. That avoided the need to java-compile in most cases. The performance gain is though quite low, because build-time is dominated by downloading dependencies. gradlew --parallel helped to mitigate that a bit, but to really boost the build, downloading should be avoided altogether.

Sharing ~/.gradle as a docker volume is problematic, because it will cause contention when containers run in parallel (https://github.com/gradle/gradle/issues/851).

So, what else can be done to avoid downloading the same artifacts over and over again?

答: You could build a docker image containing a cache, then use this image to run the building containers.</p>


问:
Firebase: How to know if a user used the app within 4 weeks
Using Firebase as a backend for my mobile app, how can I get the information (on the client side) if a user was using my mobile-app within the last 4 weeks or if he didn't?
I somehow need to get the date of last usage (last read, or write operation, last login...)

I know there is the information of "last sign-in" in the admin SDK, however I'm not sure if this is supposed to be integrated in the app itself.

答:
you can add lastOnline field to your user entity and change it everytime the user quit the application :

```<code>DatabaseReference userLastOnlineRef = FirebaseDatabse.getInstance().getReference("users/joe/lastOnline");
userLastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);
</code>```

link

Body:
you can add lastOnline field to your user entity and change it everytime the user quit the application :

DatabaseReference userLastOnlineRef = FirebaseDatabse.getInstance().getReference("users/joe/lastOnline");
userLastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);

link


问:
Custom buttons in different APIs
I did a custom button class for making square buttons. Buttons works fine in Nougat, but not showing in Lollipop and marshmallow. What is wrong with my code?

Java class:

```<code>public class SquareButton extends ToggleButton {

        public SquareButton(Context context) {
            super(context);
        }

        public SquareButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int size = width > height ? height : width;
            setMeasuredDimension(size, size);

        }
    }
</code>```

XML:

```<code>    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="ru.energyhouse.energyhouse.presenter.Light.MainMenuLightFragment"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:id="@+id/main_menu_light_icon_IV"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline9"
        app:srcCompat="@drawable/light_lightoff_big_ic" />

    <TextView
        android:id="@+id/main_menu_light_icon_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorPrimary"
        app:layout_constraintLeft_toLeftOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintRight_toRightOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintTop_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.5" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline9"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <HorizontalScrollView
        android:id="@+id/main_menu_light_scroll"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="16dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_menu_light_icon_TV"
        app:layout_constraintVertical_bias="0.0">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="2">

            <LinearLayout
                android:id="@+id/main_menu_light_firstRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_bright_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_soft_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_manual_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="24dp"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/main_menu_light_secondRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_allOff_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_backLight_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

        </LinearLayout>

    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

Nougat: enter image description here

Lollipop: enter image description here

UPD.

if set width 200dp - it works. I need width like height and height - match_parent.

答:
You could use simple button with buttonshape.xml as background of Button

```<code><Button
android:text="Button"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/buttonshape"
/>
</code>```

paste this code in drawables as buttonshape.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="20dp"
/>
<solid
android:color="#FFFFF"
/>
<size
android:width="200dp"
android:height="200dp"
/>
</shape>
</code>```

Title: Custom buttons in different APIs

Body:
I did a custom button class for making square buttons. Buttons works fine in Nougat, but not showing in Lollipop and marshmallow. What is wrong with my code?

Java class:

public class SquareButton extends ToggleButton {

        public SquareButton(Context context) {
            super(context);
        }

        public SquareButton(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            int size = width > height ? height : width;
            setMeasuredDimension(size, size);

        }
    }

XML:

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="ru.energyhouse.energyhouse.presenter.Light.MainMenuLightFragment"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <ImageView
        android:id="@+id/main_menu_light_icon_IV"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        android:cropToPadding="false"
        android:scaleType="fitCenter"
        app:layout_constraintBottom_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline9"
        app:srcCompat="@drawable/light_lightoff_big_ic" />

    <TextView
        android:id="@+id/main_menu_light_icon_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorPrimary"
        app:layout_constraintLeft_toLeftOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintRight_toRightOf="@+id/main_menu_light_icon_IV"
        app:layout_constraintTop_toTopOf="@+id/guideline11"
        app:layout_constraintHorizontal_bias="0.5" />

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline9"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <HorizontalScrollView
        android:id="@+id/main_menu_light_scroll"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="16dp"
        android:overScrollMode="never"
        android:scrollbars="none"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_menu_light_icon_TV"
        app:layout_constraintVertical_bias="0.0">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="2">

            <LinearLayout
                android:id="@+id/main_menu_light_firstRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_bright_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_soft_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_manual_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="24dp"
                    android:layout_weight="1"
                    android:background="@drawable/scenes_click"
                    android:paddingTop="45dp"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/main_menu_light_secondRow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal">

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_allOff_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

                <ru.energyhouse.energyhouse.model.SquareButton
                    android:id="@+id/main_menu_light_backLight_Btn"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:background="@drawable/scenes_click"
                    android:layout_weight="1"
                    android:text="@null"
                    android:textOff="@null"
                    android:textOn="@null" />

            </LinearLayout>

        </LinearLayout>

    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>

Nougat: enter image description here

Lollipop: enter image description here

UPD.

if set width 200dp - it works. I need width like height and height - match_parent.

Body:
You could use simple button with buttonshape.xml as background of Button

<Button
android:text="Button"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/buttonshape"
/>

paste this code in drawables as buttonshape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="20dp"
/>
<solid
android:color="#FFFFF"
/>
<size
android:width="200dp"
android:height="200dp"
/>
</shape>


问:
How to remove elements from queue in javascript?
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

```<code>var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) +"</span>");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}
</code>```

Input:

```<code><div class="text">Phone</div>
</code>```

Output:

```<code>Pho
</code>```

you can check the Jsfiddle

Can any one help me here

答:
Another way, use for-loop:</p>

```<code>var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) +"</span>");
}
$(".text").text("");

// change here
for (var j = queue.length; j >= 0; j--) {
  $(".text").append(queue.shift());
}
</code>```

Body:
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("" + input.charAt(i) +"");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}

Input:

Phone

Output:

Pho

you can check the Jsfiddle

Can any one help me here

Body:
Another way, use for-loop:

var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) +"</span>");
}
$(".text").text("");

// change here
for (var j = queue.length; j >= 0; j--) {
  $(".text").append(queue.shift());
}


问:
The std::pair in the std::map is returned as const
My example code is

```<code>class A
{
    int a = 0;
public:
    void setA(const int value)
    {
        a = value;
    }
};

std::map<std::string, std::set<A>> Map{{"A", {}}};
Map.rbegin()->second.rbegin()->setA(2);
</code>```

I get the following error: "Member function 'setA' not viable: 'this' argument has type 'const A', but function is not marked const"

My question is why rbegin() returns a const pointer to A? Or why is the std:pair's second a const in the std::map?

答:
Basically, rbegin() returns a reverse iterator which points to an object of type A which is stored in the std::set in a const manner.

The reason behind such behaviour is quite simple: it is necessary to protect std::set from inadvertent changes of elements which are stored inside.

You should remember, that std::set stores its elements in a tree-like data structure to ensure fast search/insert/remove operations. Possible changes of elements inside std::set might lead to wrong elements comparison and corruption of data structure, that is why all iterators return by begin()/end() methods and their analogues expose elements in a const fashion.

Body:
My example code is

class A
{
    int a = 0;
public:
    void setA(const int value)
    {
        a = value;
    }
};

std::map<std::string, std::set> Map{{"A", {}}};
Map.rbegin()->second.rbegin()->setA(2);

I get the following error: "Member function 'setA' not viable: 'this' argument has type 'const A', but function is not marked const"

My question is why rbegin() returns a const pointer to A? Or why is the std:pair's second a const in the std::map?


问:
ConcurrentHashMap: avoid extra object creation with "putIfAbsent"?
I am aggregating multiple values for keys in a multi-threaded environment. The keys are not known in advance. I thought I would do something like this:

```<code>class Aggregator {
    protected ConcurrentHashMap<String, List<String>> entries =
                            new ConcurrentHashMap<String, List<String>>();
    public Aggregator() {}

    public void record(String key, String value) {
        List<String> newList =
                    Collections.synchronizedList(new ArrayList<String>());
        List<String> existingList = entries.putIfAbsent(key, newList);
        List<String> values = existingList == null ? newList : existingList;
        values.add(value);
    }
}
</code>```

The problem I see is that every time this method runs, I need to create a new instance of an ArrayList, which I then throw away (in most cases). This seems like unjustified abuse of the garbage collector. Is there a better, thread-safe way of initializing this kind of a structure without having to synchronize the record method? I am somewhat surprised by the decision to have the putIfAbsent method not return the newly-created element, and by the lack of a way to defer instantiation unless it is called for (so to speak).

答:
The approach with putIfAbsent has the fastest execution time, it is from 2 to 50 times faster than the "lambda" approach in evironments with high contention. The Lambda isn't the reason behind this "powerloss", the issue is the compulsory synchronisation inside of computeIfAbsent prior to the Java-9 optimisations.

the benchmark:

```<code>import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentHashMapTest {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsentLamda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsentLamda() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
                        count.incrementAndGet();

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

}
</code>```

The results:

```<code>Test testPutIfAbsent average time per run: 115.756501 ns
Test testComputeIfAbsentLamda average time per run: 276.9667055 ns
Test testPutIfAbsent average time per run: 134.2332435 ns
Test testComputeIfAbsentLamda average time per run: 223.222063625 ns
Test testPutIfAbsent average time per run: 119.968893625 ns
Test testComputeIfAbsentLamda average time per run: 216.707419875 ns
Test testPutIfAbsent average time per run: 116.173902375 ns
Test testComputeIfAbsentLamda average time per run: 215.632467375 ns
Test testPutIfAbsent average time per run: 112.21422775 ns
Test testComputeIfAbsentLamda average time per run: 210.29563725 ns
Test testPutIfAbsent average time per run: 120.50643475 ns
Test testComputeIfAbsentLamda average time per run: 200.79536475 ns
</code>```

Body:
I am aggregating multiple values for keys in a multi-threaded environment. The keys are not known in advance. I thought I would do something like this:

class Aggregator {
    protected ConcurrentHashMap<String, List<String>> entries =
                            new ConcurrentHashMap<String, List<String>>();
    public Aggregator() {}

    public void record(String key, String value) {
        List<String> newList =
                    Collections.synchronizedList(new ArrayList<String>());
        List<String> existingList = entries.putIfAbsent(key, newList);
        List<String> values = existingList == null ? newList : existingList;
        values.add(value);
    }
}

The problem I see is that every time this method runs, I need to create a new instance of an ArrayList, which I then throw away (in most cases). This seems like unjustified abuse of the garbage collector. Is there a better, thread-safe way of initializing this kind of a structure without having to synchronize the record method? I am somewhat surprised by the decision to have the putIfAbsent method not return the newly-created element, and by the lack of a way to defer instantiation unless it is called for (so to speak).

Body:
The approach with putIfAbsent has the fastest execution time, it is from 2 to 50 times faster than the "lambda" approach in evironments with high contention. The Lambda isn't the reason behind this "powerloss", the issue is the compulsory synchronisation inside of computeIfAbsent prior to the Java-9 optimisations.

the benchmark:

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class ConcurrentHashMapTest {
    private final static int numberOfRuns = 1000000;
    private final static int numberOfThreads = Runtime.getRuntime().availableProcessors();
    private final static int keysSize = 10;
    private final static String[] strings = new String[keysSize];
    static {
        for (int n = 0; n < keysSize; n++) {
            strings[n] = "" + (char) ('A' + n);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int n = 0; n < 20; n++) {
            testPutIfAbsent();
            testComputeIfAbsentLamda();
        }
    }

    private static void testPutIfAbsent() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.get(s);
                        if (count == null) {
                            count = new AtomicInteger(0);
                            AtomicInteger prevCount = map.putIfAbsent(s, count);
                            if (prevCount != null) {
                                count = prevCount;
                            }
                        }
                        count.incrementAndGet();
                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

    private static void testComputeIfAbsentLamda() throws InterruptedException {
        final AtomicLong totalTime = new AtomicLong();
        final ConcurrentHashMap<String, AtomicInteger> map = new ConcurrentHashMap<String, AtomicInteger>();
        final Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
        for (int i = 0; i < numberOfThreads; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long start, end;
                    for (int n = 0; n < numberOfRuns; n++) {
                        String s = strings[random.nextInt(strings.length)];
                        start = System.nanoTime();

                        AtomicInteger count = map.computeIfAbsent(s, (k) -> new AtomicInteger(0));
                        count.incrementAndGet();

                        end = System.nanoTime();
                        totalTime.addAndGet(end - start);
                    }
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("Test " + Thread.currentThread().getStackTrace()[1].getMethodName()
                + " average time per run: " + (double) totalTime.get() / numberOfThreads / numberOfRuns + " ns");
    }

}

The results:

Test testPutIfAbsent average time per run: 115.756501 ns
Test testComputeIfAbsentLamda average time per run: 276.9667055 ns
Test testPutIfAbsent average time per run: 134.2332435 ns
Test testComputeIfAbsentLamda average time per run: 223.222063625 ns
Test testPutIfAbsent average time per run: 119.968893625 ns
Test testComputeIfAbsentLamda average time per run: 216.707419875 ns
Test testPutIfAbsent average time per run: 116.173902375 ns
Test testComputeIfAbsentLamda average time per run: 215.632467375 ns
Test testPutIfAbsent average time per run: 112.21422775 ns
Test testComputeIfAbsentLamda average time per run: 210.29563725 ns
Test testPutIfAbsent average time per run: 120.50643475 ns
Test testComputeIfAbsentLamda average time per run: 200.79536475 ns


答:
```<code>     SELECT  *
       FROM log_customer
      WHERE customer_id = 2
        AND log_id = (Select Max(Log_id)
                        FROM log_Customer
                       WHERE customer_id = 2)
</code>```

That should do the trick

Edit without the Where:

```<code>     SELECT  *
       FROM log_customer
      WHERE log_id = (Select Max(Log_id)
                        FROM log_Customer
                       WHERE customer_id = 2)
</code>```

Title: what will be the simple mysql query for this

Body:
I want to get the customer info where customer id should be 2 and the log_id should be maximum value
i tried below query but it is fetching first record found.

What will be the simple query

mysql> select * from log_customer where customer_id =2 group by customer_id having max(log_id);
+--------+------------+-------------+---------------------+-----------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at | store_id |
+--------+------------+-------------+---------------------+-----------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL      |        1 |
+--------+------------+-------------+---------------------+-----------+----------+
1 row in set (0.00 sec)

mysql> select * from log_customer where customer_id =2 limit 5;
+--------+------------+-------------+---------------------+---------------------+----------+
| log_id | visitor_id | customer_id | login_at            | logout_at           | store_id |
+--------+------------+-------------+---------------------+---------------------+----------+
|      2 |         56 |           2 | 2010-02-19 19:34:45 | NULL                |        1 |
|      3 |        114 |           2 | 2010-02-23 17:31:55 | NULL                |        1 |
|     31 |       1854 |           2 | 2010-03-08 18:31:28 | 2010-03-08 18:56:49 |        1 |
|     32 |       1992 |           2 | 2010-03-09 01:12:43 | NULL                |        1 |
|     33 |       2304 |           2 | 2010-03-09 14:42:39 | NULL                |        1 |
+--------+------------+-------------+---------------------+---------------------+----------+

Please do not suggest order by log_id desc I don't want to get in this way

Body:
     SELECT  *
       FROM log_customer
      WHERE customer_id = 2
        AND log_id = (Select Max(Log_id)
                        FROM log_Customer
                       WHERE customer_id = 2)

That should do the trick

Edit without the Where:

     SELECT  *
       FROM log_customer
      WHERE log_id = (Select Max(Log_id)
                        FROM log_Customer
                       WHERE customer_id = 2)


问:
Difference in dense rank and row number in spark
I tried to understand the difference between dense rank and row number.Each new window partition both is starting from 1. Does rank of a row is not always start from 1 ? Any help would be appreciated </p>

答:
The difference is when there are "ties" in the ordering column. Check the example below:

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val df = Seq(("a", 10), ("a", 10), ("a", 20)).toDF("col1", "col2")

val windowSpec = Window.partitionBy("col1").orderBy("col2")

df
  .withColumn("rank", rank().over(windowSpec))
  .withColumn("dense_rank", dense_rank().over(windowSpec))
  .withColumn("row_number", row_number().over(windowSpec)).show

+----+----+----+----------+----------+
|col1|col2|rank|dense_rank|row_number|
+----+----+----+----------+----------+
|   a|  10|   1|         1|         1|
|   a|  10|   1|         1|         2|
|   a|  20|   3|         2|         3|
+----+----+----+----------+----------+
```

Note that the value "10" exists twice in col2 within the same window (col1 = "a"). That's when you see a difference between the three functions.

Body:
The difference is when there are "ties" in the ordering column. Check the example below:

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val df = Seq(("a", 10), ("a", 10), ("a", 20)).toDF("col1", "col2")

val windowSpec = Window.partitionBy("col1").orderBy("col2")

df
  .withColumn("rank", rank().over(windowSpec))
  .withColumn("dense_rank", dense_rank().over(windowSpec))
  .withColumn("row_number", row_number().over(windowSpec)).show

+----+----+----+----------+----------+
|col1|col2|rank|dense_rank|row_number|
+----+----+----+----------+----------+
|   a|  10|   1|         1|         1|
|   a|  10|   1|         1|         2|
|   a|  20|   3|         2|         3|
+----+----+----+----------+----------+

Note that the value "10" exists twice in col2 within the same window (col1 = "a"). That's when you see a difference between the three functions.


问:
GDB commits suicide (kills debugged process out of a sudden)
I'm running a very large app (binary has 2GB, mostly because of debug symbols) through GDB (version 7.12, Ubuntu 14.04) so I can catch all crashes and have full backtraces + coredumps:
ulimit -c unlimited
and bt / bt full / info thread / generate-core-file after crash.

However, rarely I get some strange behaviour: app instantly closes with Program terminated with signal SIGKILL, Killed. in log, however I'm 100% positive nothing else from the system kills it, the one responsible being GDB for this. When this happens, it doesn't generate any backtrace / coredump / etc.

As far as I saw until now, this happens at big (1day) uptimes. Whenever a normal crash happens at ~1 day uptime (I'm not talking about the kill situation, but normal crash) and GDB generates the backtrace + coredump, the coredump size is ~100GB. So only thing to assume for now is GDB is consuming too much memory to handle it. Unfortunately I don't know the exact memory usage when this happens (since it's unexpected), but the swap file is almost empty, which most likely means it didn't really run out of memory.

Thoughts on how to debug this situation?

答:
binary has 2GB

You are likely running out of memory and you app was likely killed by OOM killer. To confirm this look at dmesg output for oom-killer and Killed process messages.

but the swap file is almost empty, which most likely means it didn't
  really run out of memory

This depends on vm.swappiness value in proc. Try to increase this parameter to increase how aggressively the kernel will swap memory pages. See man proc:

```<code>   /proc/sys/vm/swappiness
          The value in this file controls how aggressively the kernel
          will swap memory pages.  Higher values increase
          aggressiveness, lower values decrease aggressiveness.  The
          default value is 60.
</code>```

Body:
binary has 2GB

You are likely running out of memory and you app was likely killed by OOM killer. To confirm this look at dmesg output for oom-killer and Killed process messages.

but the swap file is almost empty, which most likely means it didn't
  really run out of memory

This depends on vm.swappiness value in proc. Try to increase this parameter to increase how aggressively the kernel will swap memory pages. See man proc:

   /proc/sys/vm/swappiness
          The value in this file controls how aggressively the kernel
          will swap memory pages.  Higher values increase
          aggressiveness, lower values decrease aggressiveness.  The
          default value is 60.


问:
C# remote watchdog
We have a number of services (mostly console applications) running across several remote computers.

I need to implement some form of a watchdog to make sure all these services are running as expected.

Some services are executed via Windows Task Scheduler, and some are long-running apps.

What would be the best way of logging that those applications are run? I don't want to modify my running services.

I have administrator access to all machines.

A few options comes to mind:

For the long running applications:
Use psexec and retrieve a list of running processes and make sure my application is in that list.

For tasks invoked by task scheduler:
Use psexec and query schtasks and find out when my services was run and what the return code was.

Do you have any other ideas of doing this?

For the record, this will be implemented in C#/WPF.

EDIT:

Ok, I solved this in a pretty straight forward way. Thanks for your input.

Source: http://pastebin.com/fr6dDMp5

答: As I stated in my question, i solved this in a pretty straight forward way using Process.GetProcesses(string machineName) which can get processes on a remote machine. Source here: http://pastebin.com/fr6dDMp5

Title: C# remote watchdog


问:
SQL monthly statement using recursive cte
I am trying to create a monthly bank account statement from a transaction table which has all history records.
I would like have opening balance as the first row and then the current months transaction with the updated balance at that time using recursive cte.
I know this can be done by table update too but recursion is what i am looking for.

the table structure would be like:

```<code>declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)
</code>```

So in here there is transaction for month 6 and 7.
The opening balance of current month would be sum of all transactions in June which will be used as anchor to get recursive balance.
Now i would like the select query to have date,tran_id,cust_id,credit,debit,balance as the result set.

So if table has data like:

```<code>date                   tran_id  cust_id tran_type   amount
2017-06-06 22:05:10.703 1   1   c   700
2017-06-12 22:05:10.703 2   1   d   100
2017-06-20 22:05:10.703 3   1   c   200
2017-06-26 22:05:10.703 4   1   d   450
2017-07-08 16:34:24.817 5   1   d   200
2017-07-09 16:34:24.817 6   1   d   200
2017-07-10 16:34:24.817 7   1   c   500
2017-07-11 16:34:24.817 8   1   d   300
2017-07-12 16:34:24.817 9   1   d   200
2017-06-18 22:05:10.703 12  1   d   100

The monthly statement for month 7 should be like:
opening balance of 250

date                     tran_id    cust_id credit  debit   balance
2017-07-08 16:40:56.810     5        1      NULL     200    50
2017-07-09 16:40:56.810     6        1      NULL     200    -150
2017-07-10 16:40:56.810     7        1      500      NULL   350
2017-07-11 16:40:56.810     8        1      NULL     300    -50
2017-07-12 16:40:56.810     9        1      NULL     200    -250
</code>```

i have tried using recursive cte and sum windowed  function but it does not give continuous balance just a row by row balance.

Also using aggregate functions in a cte is a no no so stuck at that too.

```<code>;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),

cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2
</code>```

OR

```<code>;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)
</code>```

what am i missing?

答:
Just use a cumulative sum:

```<code>select t.*,
       sum(case when tran_type = 'c' then amount else - amount end) over
           (partition by cust_id order by date) as balance
from @temp t;
</code>```

You can then select a range using a subquery or CTE:

```<code>select t.*
from (select t.*,
             sum(case when tran_type = 'c' then amount else - amount end) over
                 (partition by cust_id order by date) as balance
      from @temp t
     ) t
where . . .
</code>```

You need a subquery for the where, so it doesn't affect the cumulative sum.

EDIT:

In SQL Server 2008, you can use cross apply:

```<code>select t.*,
       t2.balance
from @temp t cross apply
     (select sum(case when t2.tran_type = 'c' then t2.amount else - t2.amount end) as balance
      from @temp t2
      where t2.cust_id = t.cust_id and t2.date <= t.date
     ) t2;
</code>```

Body:
I am trying to create a monthly bank account statement from a transaction table which has all history records.
I would like have opening balance as the first row and then the current months transaction with the updated balance at that time using recursive cte.
I know this can be done by table update too but recursion is what i am looking for.

the table structure would be like:

declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)

So in here there is transaction for month 6 and 7.
The opening balance of current month would be sum of all transactions in June which will be used as anchor to get recursive balance.
Now i would like the select query to have date,tran_id,cust_id,credit,debit,balance as the result set.

So if table has data like:

date                   tran_id  cust_id tran_type   amount
2017-06-06 22:05:10.703 1   1   c   700
2017-06-12 22:05:10.703 2   1   d   100
2017-06-20 22:05:10.703 3   1   c   200
2017-06-26 22:05:10.703 4   1   d   450
2017-07-08 16:34:24.817 5   1   d   200
2017-07-09 16:34:24.817 6   1   d   200
2017-07-10 16:34:24.817 7   1   c   500
2017-07-11 16:34:24.817 8   1   d   300
2017-07-12 16:34:24.817 9   1   d   200
2017-06-18 22:05:10.703 12  1   d   100

The monthly statement for month 7 should be like:
opening balance of 250

date                     tran_id    cust_id credit  debit   balance
2017-07-08 16:40:56.810     5        1      NULL     200    50
2017-07-09 16:40:56.810     6        1      NULL     200    -150
2017-07-10 16:40:56.810     7        1      500      NULL   350
2017-07-11 16:40:56.810     8        1      NULL     300    -50
2017-07-12 16:40:56.810     9        1      NULL     200    -250

i have tried using recursive cte and sum windowed  function but it does not give continuous balance just a row by row balance.

Also using aggregate functions in a cte is a no no so stuck at that too.

;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),

cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2

OR

;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)

what am i missing?

Body:
Just use a cumulative sum:

select t.*,
       sum(case when tran_type = 'c' then amount else - amount end) over
           (partition by cust_id order by date) as balance
from @temp t;

You can then select a range using a subquery or CTE:

select t.*
from (select t.*,
             sum(case when tran_type = 'c' then amount else - amount end) over
                 (partition by cust_id order by date) as balance
      from @temp t
     ) t
where . . .

You need a subquery for the where, so it doesn't affect the cumulative sum.

EDIT:

In SQL Server 2008, you can use cross apply:

select t.*,
       t2.balance
from @temp t cross apply
     (select sum(case when t2.tran_type = 'c' then t2.amount else - t2.amount end) as balance
      from @temp t2
      where t2.cust_id = t.cust_id and t2.date <= t.date
     ) t2;


问:
Using Linq to filter an array with bool properties true in to another array
I have an array of type Brick with each brick having an isBroken bool property. How can I use Linq to filter all bricks with isBroken = true into a new array?

答:
Use Where to filter the list of bricks and ToArray to materialize the result into a new array.

```<code>var result = MyBricksArray.Where(x => x.isBroken).ToArray();
</code>```

Body:
Use Where to filter the list of bricks and ToArray to materialize the result into a new array.

var result = MyBricksArray.Where(x => x.isBroken).ToArray();


问:
Ascending order with three integers for C++
```<code>#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " << b;
    }
    else if (((a == a) && (b >= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }
    else if (((a >= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " << b;
    }
    else if (((a > c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " << a;
    }
    else if (((a >= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}
</code>```

<p>For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?   </p>

答:
If I understand correctly your question, you can alternatively use std::sort found in algorithm header.

```<code>int vals[] { 3, 1, 2 };
std::sort(vals, vals + 3);
cout << vals[0] << vals[1] << vals[2]; // prints 123
</code>```

Body:
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int c;

    cout << "Please input three integers:" << endl;
    cout << ">> ";
    cin >> a >> b >> c;
    cout << endl;

    if (((a == a) && (b > a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << c << " " <= a)) && (c >= a))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << a << " " << b << " " << c;
    }
    else if (((a > b) && (b == b)) && (c >= b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " <= b) && (b == b)) && (c < b))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << a << " " < c) && (b >= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << c << " " << b << " " <= c) && (b <= c)) && (c == c))
    {
        cout << "Input three integer numbers in ascending order:" << endl;
        cout << b << " " << c << " " << a;
    }

    return 0;
}

For this assignment, I used 1, 2, and 3 for entering the integer.
My question is why these input (1, 2, 3) and (2, 1, 3) and (3, 2, 1)
don't ascended properl?

Body:
If I understand correctly your question, you can alternatively use std::sort found in algorithm header.

int vals[] { 3, 1, 2 };
std::sort(vals, vals + 3);
cout << vals[0] << vals[1] << vals[2]; // prints 123


问:
Trying to use a numericupdown not in a void
I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.

```<code>int number1 = Convert.ToInt32(numericUpDown1.Value);
</code>```

I want to define it before I call any events so I can use it everywhere. Thanks

答:
Create a static class and set your property number1 to a static property.

```<code>public static class KeySets
{
    public static int Number1 { get; set; }
}
</code>```

then set property

```<code>KeySets.Number1 = Convert.ToInt32(numericUpDown1.Value);
</code>```

then you can use it every where.

Body:
I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.

int number1 = Convert.ToInt32(numericUpDown1.Value);

I want to define it before I call any events so I can use it everywhere. Thanks

Body:
Create a static class and set your property number1 to a static property.

public static class KeySets
{
    public static int Number1 { get; set; }
}

then set property

KeySets.Number1 = Convert.ToInt32(numericUpDown1.Value);

then you can use it every where.


问:
Convert "pt" to "px" using regular expression
In WYSIWYG editor, I have

```<code><TABLE style="WIDTH: 162pt; BORDER-COLLAPSE: collapse" border=0 cellSpacing=0 cellPadding=0 width=216>
</code>```

I can convert this to

```<code><TABLE style="WIDTH: 162px; BORDER-COLLAPSE: collapse" border=0 cellSpacing=0 cellPadding=0 width=216>
</code>```

using

```<code>"wysiwygdata".replace(/pt/g ,"px");
</code>```

Is there any way to change associated value of pt to the value of px using regex.

162pt might be 162*96/72px.

Looking for your help.

答:
You can use a regular expression for this, where you feed a function into String#replace:

```<code>s = /* ...the data... */;
s = s.replace(/([0-9]+)pt/g, function(match, group0) {

    return Math.round(parseInt(group0, 10) * 96 / 72) + "px";
});
</code>```

Live example

When you supply a function for the second argument of replace, it gets called for each match, with the complete match as the first argument, and then the value of any capture groups for subsequent arguments; the return value is used as the replacement. So above I'm using a capture group to capture the number, and then doing the math and returning the new string.

You might need or want to adjust the regex a bit to make sure it fits your data (possible spaces between the number and the units, possibly the i flag so it matches "PT" as well as "pt", etc.), but that's the fundamental approach.

Body:
In WYSIWYG editor, I have

I can convert this to

using

"wysiwygdata".replace(/pt/g ,"px");

Is there any way to change associated value of pt to the value of px using regex.

162pt might be 162*96/72px.

Looking for your help.

Body:
You can use a regular expression for this, where you feed a function into String#replace:

s = /* ...the data... */;
s = s.replace(/([0-9]+)pt/g, function(match, group0) {

    return Math.round(parseInt(group0, 10) * 96 / 72) + "px";
});

Live example

When you supply a function for the second argument of replace, it gets called for each match, with the complete match as the first argument, and then the value of any capture groups for subsequent arguments; the return value is used as the replacement. So above I'm using a capture group to capture the number, and then doing the math and returning the new string.

You might need or want to adjust the regex a bit to make sure it fits your data (possible spaces between the number and the units, possibly the i flag so it matches "PT" as well as "pt", etc.), but that's the fundamental approach.


问:
CSS/LESS translate with calc percent & pixels
I need to translate an element -50% + a certain fixed value.
So far I tried this in LESS:

```<code>transform: translateX(calc(~'(100% + 15px)'););
</code>```

But the compiler tells me:

"SyntaxtError: expected ')' got ';'

What am I doing wrong?
Thank you for any suggestion

答:
that write an example </p>

```<code>transform: translateX(calc(~'(100% + 15px)')); /* calc doesnt work on transform*/

so use
transform: translateX(100%) translateX(+15px);
</code>```

Body:
I need to translate an element -50% + a certain fixed value.
So far I tried this in LESS:

transform: translateX(calc(~'(100% + 15px)'););

But the compiler tells me:

"SyntaxtError: expected ')' got ';'

What am I doing wrong?
Thank you for any suggestion

Body:
that write an example

transform: translateX(calc(~'(100% + 15px)')); /* calc doesnt work on transform*/

so use
transform: translateX(100%) translateX(+15px);


问:
i want to sorting hashmap (decending) in java
I want to sort this HashMap:

```<code>HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();

TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);
</code>```

In value reverse sorting.

If the values are the same, I will use key as the next condition.
Value is reverse but key is not.

答:
Why don't you get the entrySet from the map and try sorting it by using creating a comparator according to your need. When it's sorted just create a new instance of map and iterate the sorted set into the map. Its a little costly but does what you need.

If you find any problems implementing this. Tell me I will give you the code. :)

Body:
I want to sort this HashMap:

HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();

TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);

In value reverse sorting.

If the values are the same, I will use key as the next condition.
Value is reverse but key is not.