问:
RANDOM 0, 1, -1 IN VERILOG
I would like to generate random decimal number 0, 1 or -1 in verilog, that I can add it to my basic signal and get some noise on it with it.
I tried with

```<code>reg [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= {$random}%2;
</code>```

but it doesnt work the way I want.

Could someone give me advice what to do?

Thanks

答:
How about:

```<code>reg signed [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= $signed($urandom_range(0,2))-1;
</code>```

If SIGNAL_noise_ii is required to represent a "random decimal number 0, 1 or -1", it would seem a good idea to make it signed.

$urandom_range(min,max) generates a random unsigned integer in the range min to max inclusive.

So, let's used $signed to make that integer signed and then let's subtract 1 from it. Literals with no base (such as 1) are signed in Verilog by default. We need to make everything on the right hand side of the assignment signed, because if mix signed and unsigned quantities in Veriog, unsigned arithmetic is done.

https://www.edaplayground.com/x/3tCK

Title: RANDOM 0, 1, -1 IN VERILOG

Body:
I would like to generate random decimal number 0, 1 or -1 in verilog, that I can add it to my basic signal and get some noise on it with it.
I tried with

reg [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= {$random}%2;

but it doesnt work the way I want.

Could someone give me advice what to do?

Thanks

Body:
How about:

reg signed [1:0] SIGNAL_noise_ii;
SIGNAL_noise_ii <= $signed($urandom_range(0,2))-1;

If SIGNAL_noise_ii is required to represent a "random decimal number 0, 1 or -1", it would seem a good idea to make it signed.

$urandom_range(min,max) generates a random unsigned integer in the range min to max inclusive.

So, let's used $signed to make that integer signed and then let's subtract 1 from it. Literals with no base (such as 1) are signed in Verilog by default. We need to make everything on the right hand side of the assignment signed, because if mix signed and unsigned quantities in Veriog, unsigned arithmetic is done.

https://www.edaplayground.com/x/3tCK


来源: stackexchange

问:
Looping inside an object
I had encountered something unclear to me in the for loop:

```<code>var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};
</code>```

I'm looping through this object with this loop:

```<code>var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '<li>' +
        '<a href = "' + info.links[key] +
        '">' + key + '</a>' +
        '</li>';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;
</code>```

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?

答:
var means that you're declaring a new variable, key is the name you give this variable.

Since you're looping through everthing in info.links you want to be able to call each var individually

ContentLicense: CC BY-SA 3.0

Title: Looping inside an object

Body:
I had encountered something unclear to me in the for loop:

var info = {
"full_name" : "John Doe",
"title" : "FrontEnd",
"links" : {
    "blog"     : "JohnDoe.com",
    "facebook" : "http://facebook.com/JohnDoe",
        "youtube"  : "http://www.youtube.com/JohnDoe",
        "twitter"  : "http://twitter.com/JohnDoe"
    }
};

I'm looping through this object with this loop:

var output = "";

for (var key in info.links ) {
    if (info.links.hasOwnProperty(key)) {
        output += '
' +
        '' + key + '' +
        '
';
        console.log(key);
    }
}
var update = document.getElementById('links');
update.innerHTML = output;

And my question is, what is var key in this loop and why it works when there is no var key in scope of this loop? In this case var key becomes blog, facebook etc. inside info.links object. But why?


问:
Adding active class to toggle jquery
Trying to toggle 'active' class to link (.read-more-toggle) that is making panel reveal / hide.

I've got the slideToggle bit working fine. I just need to make the toggle link add class active on click and then remove on click again.

```<code>$(".read-more-toggle").on("click", function () {
    $('.read-more-content').slideToggle( "slow" );
});
</code>```

Here's a working JSFiddle: https://jsfiddle.net/ndgnsx60/2/

Thanks

答:
Just toggle the class "active" on click aswell.</p>

```<code>$(".read-more-toggle").on("click", function () {
    $('.read-more-content').slideToggle( "slow" );
    $(".read-more-toggle").toggleClass("active");
});
</code>```

Title: Adding active class to toggle jquery

Body:
Trying to toggle 'active' class to link (.read-more-toggle) that is making panel reveal / hide.

I've got the slideToggle bit working fine. I just need to make the toggle link add class active on click and then remove on click again.

$(".read-more-toggle").on("click", function () {
    $('.read-more-content').slideToggle( "slow" );
});

Here's a working JSFiddle: https://jsfiddle.net/ndgnsx60/2/

Thanks

Body:
Just toggle the class "active" on click aswell.

$(".read-more-toggle").on("click", function () {
    $('.read-more-content').slideToggle( "slow" );
    $(".read-more-toggle").toggleClass("active");
});


问:
how to make the following scala immutable
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)
</code>```

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}
</code>```

How do I implement it in immutable way?

答:
You can do it with a one-liner:

def sendMessage: Unit =
  groups.reduce(_ ++ _).toStream.distinct.foreach(sendMessage)
```

<hr>

<p>Expanded version for learning purpose:</p>

<pre class="lang-scala prettyprint-override"><code>val students: Iterator[Student] = groups.reduce(_ ++ _)
val sStudents: Stream[Student] = students.toStream
val dStudents: Stream[Student] = sStudents.distinct
def sendMessage: Unit = sStudents.foreach(sendMessage)
</code>```

Body:
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}

How do I implement it in immutable way?

Body:
You can do it with a one-liner:

def sendMessage: Unit =
  groups.reduce(_ ++ _).toStream.distinct.foreach(sendMessage)

Expanded version for learning purpose:

val students: Iterator[Student] = groups.reduce(_ ++ _)
val sStudents: Stream[Student] = students.toStream
val dStudents: Stream[Student] = sStudents.distinct
def sendMessage: Unit = sStudents.foreach(sendMessage)


问:
Disable all breakpoints without current breakpoint in Intellij IDEA
I used Intellij IDEA CE version 2016.3.4 and I have simple question about breakpoints.

Is it possible to disable all breakpoints except one (current one) and without editing all other? Maybe there is any "one click" option ?

Example:

```<code>+ means Enabled breakpoint
- means Disabled breakpoint

(Before)
[+] Breakpoint1
[+] Breakpoint2 - current
[+] Breakpoint3
[+] Breakpoint4

(After mute/disable all without current)
[-] Breakpoint1
[+] Breakpoint2 - current
[-] Breakpoint3
[-] Breakpoint4
</code>```

答: The shortest solution i can think of is Ctrl+Shift+F8 ( Cmd+Shift+F8 for mac ) to open All breakpoints window. Then Ctrl+A ( Cmd+A ) to select all of them and Space to disable all. After that you can enable your current breakpoint.

Body:
I used Intellij IDEA CE version 2016.3.4 and I have simple question about breakpoints.

Is it possible to disable all breakpoints except one (current one) and without editing all other? Maybe there is any "one click" option ?

Example:

+ means Enabled breakpoint
- means Disabled breakpoint

(Before)
[+] Breakpoint1
[+] Breakpoint2 - current
[+] Breakpoint3
[+] Breakpoint4

(After mute/disable all without current)
[-] Breakpoint1
[+] Breakpoint2 - current
[-] Breakpoint3
[-] Breakpoint4


问:
Calculating available bandwidth
I need write a code in C++ in Windows , to calculate available bandwidth.
I'm currently planing to use spruce algorithm.
i wanted to know is there any code available for this algorithm in windows .
or is there any other technique to get the internet bandwidth.</p>

答:
Searching for "spruce algorithm" gives me this result http://iris.csail.mit.edu/spruce/ :

Spruce is a tool for measuring available bandwidth over Internet paths.
  Download source code

It's GPLv2 and written in C - should be easily portable to C++.

ContentLicense: CC BY-SA 2.5

Title: Calculating available bandwidth


问:
What happens to the cost of the nodes when the graph is converted to its corresponding Line Graph?
I have a graph G. I want to convert the graph to its corresponding Line Graph. The graph G has cost associated with its nodes. I want to know how what happens to the cost of the nodes when the graph is converted to the Line Graph.

答:
Given a graph (with the cost associated to each vertex in () brackets:

```<code>1 (8) ------ 2 (7)
 |  \         |
 |   \        |
 |   3 (9)    |
 |   /        |
 |  /         |
4 (6) ------ 5 (10)
</code>```

You can associate costs to the dual graph by giving the edges in the dual the cost associated with the vertex:

```<code>          (8)
  [1,2] ------- [1,3]
    | \         /   \
    |  \ (8)   /(8)  \ (9)
    |   \     /       \
(7) |    [1,4] ----- [3,4]
    |         \  (6)  /
    |      (6) \     / (6)
    |           \   /
  [2,5] ------- [4,5]
          (10)
</code>```

So the connection [1,4] to [3,4] goes through the vertex 4 which has an associated cost of 6 so the edge in the dual representing this gets a cost of 6.

Body:
Given a graph (with the cost associated to each vertex in () brackets:

1 (8) ------ 2 (7)
 |  \         |
 |   \        |
 |   3 (9)    |
 |   /        |
 |  /         |
4 (6) ------ 5 (10)

You can associate costs to the dual graph by giving the edges in the dual the cost associated with the vertex:

          (8)
  [1,2] ------- [1,3]
    | \         /   \
    |  \ (8)   /(8)  \ (9)
    |   \     /       \
(7) |    [1,4] ----- [3,4]
    |         \  (6)  /
    |      (6) \     / (6)
    |           \   /
  [2,5] ------- [4,5]
          (10)

So the connection [1,4] to [3,4] goes through the vertex 4 which has an associated cost of 6 so the edge in the dual representing this gets a cost of 6.


问:
How to convert column of arrays of strings to strings?
I have a column, which is of type array < string > in spark tables. I am using SQL to query these spark tables. I wanted to convert the array < string > into string.

When used the below syntax:

```<code>select cast(rate_plan_code  as string) as new_rate_plan  from
customer_activity_searches group by rate_plan_code
</code>```

rate_plan_code column  has following values:

```<code>["AAA","RACK","SMOBIX","SMOBPX"]
["LPCT","RACK"]
["LFTIN","RACK","SMOBIX","SMOBPX"]
["LTGD","RACK"]
["RACK","LEARLI","NHDP","LADV","LADV2"]
</code>```

following are populated in the new_rate_plan column:

```<code>org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@e4273d9f
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@c1ade2ff
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@4f378397
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@d1c81377
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@552f3317
</code>```

Cast seem to work when I am converting decimal to int or int to double, but not in this case. Curious why the cast is not not working here.
Greatly appreciate your help.

答:
In Spark 2.1+ to do the concatenation of the values in a single Array column you can use the following:

concat_ws standard function

map operator

a user-defined function (UDF)

concat_ws Standard Function

Use concat_ws function.

concat_ws(sep: String, exprs: Column*): Column Concatenates multiple input string columns together into a single string column, using the given separator.

```<code>val solution = words.withColumn("codes", concat_ws(" ", $"rate_plan_code"))
scala> solution.show
+--------------+-----------+
|         words|      codes|
+--------------+-----------+
|[hello, world]|hello world|
+--------------+-----------+
</code>```

map Operator

Use map operator to have full control of what and how should be transformed.

map[U](func: (T) ⇒ U): Dataset[U] Returns a new Dataset that contains the result of applying func to each element.

```<code>scala> codes.show(false)
+---+---------------------------+
|id |rate_plan_code             |
+---+---------------------------+
|0  |[AAA, RACK, SMOBIX, SMOBPX]|
+---+---------------------------+

val codesAsSingleString = codes.as[(Long, Array[String])]
  .map { case (id, codes) => (id, codes.mkString(", ")) }
  .toDF("id", "codes")

scala> codesAsSingleString.show(false)
+---+-------------------------+
|id |codes                    |
+---+-------------------------+
|0  |AAA, RACK, SMOBIX, SMOBPX|
+---+-------------------------+

scala> codesAsSingleString.printSchema
root
 |-- id: long (nullable = false)
 |-- codes: string (nullable = true)
</code>```

Body:
I have a column, which is of type array < string > in spark tables. I am using SQL to query these spark tables. I wanted to convert the array < string > into string.

When used the below syntax:

select cast(rate_plan_code  as string) as new_rate_plan  from
customer_activity_searches group by rate_plan_code

rate_plan_code column  has following values:

["AAA","RACK","SMOBIX","SMOBPX"]
["LPCT","RACK"]
["LFTIN","RACK","SMOBIX","SMOBPX"]
["LTGD","RACK"]
["RACK","LEARLI","NHDP","LADV","LADV2"]

following are populated in the new_rate_plan column:

org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@e4273d9f
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@c1ade2ff
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@4f378397
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@d1c81377
org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@552f3317

Cast seem to work when I am converting decimal to int or int to double, but not in this case. Curious why the cast is not not working here.
Greatly appreciate your help.

Body:
In Spark 2.1+ to do the concatenation of the values in a single Array column you can use the following:

concat_ws standard function

map operator

a user-defined function (UDF)

concat_ws Standard Function

Use concat_ws function.

concat_ws(sep: String, exprs: Column*): Column Concatenates multiple input string columns together into a single string column, using the given separator.

val solution = words.withColumn("codes", concat_ws(" ", $"rate_plan_code"))
scala> solution.show
+--------------+-----------+
|         words|      codes|
+--------------+-----------+
|[hello, world]|hello world|
+--------------+-----------+

map Operator

Use map operator to have full control of what and how should be transformed.

map[U](func: (T) ⇒ U): Dataset[U] Returns a new Dataset that contains the result of applying func to each element.

scala> codes.show(false)
+---+---------------------------+
|id |rate_plan_code             |
+---+---------------------------+
|0  |[AAA, RACK, SMOBIX, SMOBPX]|
+---+---------------------------+

val codesAsSingleString = codes.as[(Long, Array[String])]
  .map { case (id, codes) => (id, codes.mkString(", ")) }
  .toDF("id", "codes")

scala> codesAsSingleString.show(false)
+---+-------------------------+
|id |codes                    |
+---+-------------------------+
|0  |AAA, RACK, SMOBIX, SMOBPX|
+---+-------------------------+

scala> codesAsSingleString.printSchema
root
 |-- id: long (nullable = false)
 |-- codes: string (nullable = true)


问:
if statement not working in shell script
Below is my script and the val1 value is 3 and val2 value is 0 , but by default the condition checks the if statement.  Not going to else condition. Can anyone help show where I missed or did something wrong here?

```<code>op1=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
op2=$(top -bn1 | grep "load average" | awk '{print$12}' |sed -e 's/,//g')
val2=${op2%.*}
val1=${op1%.*}
echo $val1
echo $val2

if [ val1 > 50 ] || [ val2 > 50 ] ; then

  echo -e "CPU Percentage on $HOSTNAME is  $op1  and Current  Load is  $op2  Which are higher than 50% usage. Kindly Login to $HOSTNAME and examine  the process. If apache process consume the more space kindly execute the following command to restart all the SWLB's. \n\n Host Name    : $HOSTNAME   \n User ID          : inauat \n Path              :/inautilus/xjp/ers/servers \n Script Name : apache_all.sh  \n\n Note: If the SWLB restart doesn't resolve the problem, contact Unix support  to investigate further. "| mutt -s " $HOSTNAME CPU Status Alert  " "test@testdomain.com" -c "test@testdomain@inautix.co.in"

else
    echo  'CPU load appears normal.'
fi
</code>```

答:
Change the if statement as below:

```<code>if [ "$val1" -gt 50 ] || [ "$val2" -gt 50 ] ; then
#your code here
fi
</code>```

Body:
Below is my script and the val1 value is 3 and val2 value is 0 , but by default the condition checks the if statement.  Not going to else condition. Can anyone help show where I missed or did something wrong here?

op1=$(top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g')
op2=$(top -bn1 | grep "load average" | awk '{print$12}' |sed -e 's/,//g')
val2=${op2%.*}
val1=${op1%.*}
echo $val1
echo $val2

if [ val1 > 50 ] || [ val2 > 50 ] ; then

  echo -e "CPU Percentage on $HOSTNAME is  $op1  and Current  Load is  $op2  Which are higher than 50% usage. Kindly Login to $HOSTNAME and examine  the process. If apache process consume the more space kindly execute the following command to restart all the SWLB's. \n\n Host Name    : $HOSTNAME   \n User ID          : inauat \n Path              :/inautilus/xjp/ers/servers \n Script Name : apache_all.sh  \n\n Note: If the SWLB restart doesn't resolve the problem, contact Unix support  to investigate further. "| mutt -s " $HOSTNAME CPU Status Alert  " "test@testdomain.com" -c "test@testdomain@inautix.co.in"

else
    echo  'CPU load appears normal.'
fi

Body:
Change the if statement as below:

if [ "$val1" -gt 50 ] || [ "$val2" -gt 50 ] ; then
#your code here
fi


问:
Web Dynpro ABAP in Mac OS
I'm using sap gui in macbook os x. Whenever I execute the web dynpro programs, the browser will be opened and  is keep on loading and it never ends. How can I fix this issue?</p>

答:
Though your Safari version seems actual, I assume your MacOS version is not supported by SAP, as PAM lists only versions from 10.11.

SAP issues PAM (Product Availability Matrix) sheets where you can match your Browser, Platform and Product versions and check for inconsistencies. Netweaver 7.4 PAM can be found here.

Probably, your MacOS version is too old for SAP and you should try to update. However, personally I feel that problem lies elsewhere and you should ask for help of experienced BASIS. Maybe your WDA uses certain feature that is not supported by Safari or WDA in general.

Additionally you can check:

Note 1634749 concerning Safari support for Web Dynpro ABAP (version for non-S-users).

Note 1098009  for general Web Dynpro ABAP browser limitations

Browser supporting page from SAP.

Title: Web Dynpro ABAP in Mac OS


问:
Dot at start and end using regex
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

```<code>/^[^\.].*[^\.]$/;
</code>```

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."

答:
The correct regex for

my requirement is that I can have at most one dot ('.') in the string
  and that can't be at the start and end

is

```<code>/^([^\.]|([^\.]*.?[^\.]))$/
</code>```

/^([^\.]|([^\.].*[^\.]))$/ or /^[^\.].*[^\.]$/ accepts String
  containing more than 1 dot . Hence it will also accept X..X too.

Please check working snippet also

    validateString("XX.X");
    validateString("X.X");
    validateString("X...X");
    validateString("X");
    validateString("X.X.X");

    validateString(".XX");

    validateString("XX.");

    function validateString(str){
      console.log(/^([^\.]|([^\.]*.?[^\.]))$/.test(str));
    }```

Title: Dot at start and end using regex

Body:
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

/^[^\.].*[^\.]$/;

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."

Body:
The correct regex for

my requirement is that I can have at most one dot ('.') in the string
  and that can't be at the start and end

is

/^([^\.]|([^\.]*.?[^\.]))$/

/^([^\.]|([^\.].*[^\.]))$/ or /^[^\.].*[^\.]$/ accepts String
  containing more than 1 dot . Hence it will also accept X..X too.

Please check working snippet also

    validateString("XX.X");
    validateString("X.X");
    validateString("X...X");
    validateString("X");
    validateString("X.X.X");

    validateString(".XX");

    validateString("XX.");

    function validateString(str){
      console.log(/^([^\.]|([^\.]*.?[^\.]))$/.test(str));
    }


问:
Android Facebook "You have already authorised appname"
I have integrated the Facebook SDK into my Android app (authenticating to Firebase). I am requesting "email" and "public_profile" permissions. I am testing this on a phone without the Facebook app, so the following is happening in Chrome through facebook.com.

The first time the user clicks the LoginButton he is asked to accept permissions. After doing so he is returned to my app and authentication is successful.

After that, however, when the user clicks the LoginButton again, he is shown a screen saying "You have already authorised ..."

I want this step to be skipped ff the user already did authorised my app, but how?

答:
please have a look at the following documentation page from Facebook

https://developers.facebook.com/docs/facebook-login/permissions/requesting-and-revoking

You will find at the bottom of the page how to delete permissions for an User (Revoking Permissions). This can even executed when the User is not logged in.


问:
best way to handle resources
I was kind of stuck trying to pass the resources to a subclass used on my Activity. I solved it in two ways, but not sure if one or both will lead to possible memory leaks. So here is what I have so far:

-myactivity (the activity class)

-global (global class to the package, I'm using to to save global accesible variables)

-subclass (the subclass where I want to use a drawable resource)

a)

```<code>public class global{
    public static Resources appRes;
    ....
}

public class myactivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        global.resApp = this.getResources();
        ...
    }

    private void somewhere(){
        subclass tmp = new subclass();
        tmp.subclasmethod();
    }
}

public class subclass{
    public subclass(){...}

    public void subclassmethod(){
        Bitmap bmp = BitmapFactory.decodeResource(Global.appRes, R.drawable.myres);
        ...
    }
}
</code>```

b)

```<code>public class myactivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    private void somewhere(){
        subclass tmp = new subclass(this.getContext());
        tmp.subclasmethod();
    }
}

public class subclass{
    Context context;

    public subclass(Context context){
        this.context = context
        ...
    }

    public void subclassmethod(){
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.myres);
        ...
    }
}
</code>```

Thanks in advance for you feedback.

答:
If you want a global class to store application-wide values, you should at least not use your option a. Instead, take a look at the Application class, which is meant to help you with exactly this:

Base class for those who need to
  maintain global application state.

Otherwise, the alternative you suggest in option b is an OK way to do it. At least if all you need is to pass along a reference to your application context so that you can access the resources.

Title: best way to handle resources

Body:
I was kind of stuck trying to pass the resources to a subclass used on my Activity. I solved it in two ways, but not sure if one or both will lead to possible memory leaks. So here is what I have so far:

-myactivity (the activity class)

-global (global class to the package, I'm using to to save global accesible variables)

-subclass (the subclass where I want to use a drawable resource)

a)

public class global{
    public static Resources appRes;
    ....
}

public class myactivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        global.resApp = this.getResources();
        ...
    }

    private void somewhere(){
        subclass tmp = new subclass();
        tmp.subclasmethod();
    }
}

public class subclass{
    public subclass(){...}

    public void subclassmethod(){
        Bitmap bmp = BitmapFactory.decodeResource(Global.appRes, R.drawable.myres);
        ...
    }
}

b)

public class myactivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    private void somewhere(){
        subclass tmp = new subclass(this.getContext());
        tmp.subclasmethod();
    }
}

public class subclass{
    Context context;

    public subclass(Context context){
        this.context = context
        ...
    }

    public void subclassmethod(){
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.myres);
        ...
    }
}

Thanks in advance for you feedback.


问:
How to force image (cache) update in README.rst on GitHub
In one of my project I'm using an external image link to display a screenshot via the GitHub page, which automatically parses the README.rst

GitHub page of ROyWeb

I updated this screenshot on my web server several times in the last weeks and I just realised that it is not updated on the GitHub page since... well I think it never updated ;-)
GitHub somehow downloaded the image and loads it from it's cache servers.

Within the README.rst, there is clearly the correct link:

Actual link to the ROyWeb screenshot

Which you can confirm, when you load the raw file:

raw README.txt on GitHub

But when I check the URL of the displayed image on the GitHub page, I get:

GitHub cached screenshot of ROyWeb

Does anyone know how to force a "recache"?

答:
I had a look at what shields.io does.

It sets this header (Source):

```<code>Cache-Control: max-age=2592000
</code>```

Body:
I had a look at what shields.io does.

It sets this header (Source):

Cache-Control: max-age=2592000


问:
HTML buttons with overflow SVG background
I am trying to achieve the following: I am using bootstrap, standard btn class.

So far I the background image is kind of in the correct position, but it gets cut off. I've tried overflow: visible; etc...

```<code>.btn {
  background: url('../images/button.svg') no-repeat;
  background-repeat: no-repeat;
  background-position: left;
  padding-left: 80px;
}

<button class="btn btn-default btn-lg">GET A FREE QUOTE <i class="fa fa-chevron-right" aria-hidden="true"></i></button>
</code>```

Thanks for any help

答:
.btn_button, .btn_button:hover, .btn_button:focus{
  background: orange;
  color: blue;
  margin-left: -10px;
  margin-top: 3px;
  width: 150px;
  outline: none;
}
.round_div{
  display: flex;
}
.round2:before{
    content: "\25cf";
    font-size: 14px;
    padding: 0px 3px;
    border: 4px solid #000;
    border-radius: 50%;
}
.round1{
    border: 10px solid orange;
    border-radius: 50%;
}
.glyphicon_right_arrow{
    color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="col-xs-12 form-group"></div>
<div class="col-xs-12">
<div class="round_div">
<div class="">
<div class="round">
<div class="round1">
<span class="round2"></span>
</div>
</div>
</div>
<div class="">
  <button class="btn btn_button" value="">MORE ABOUT US
<span class="glyphicon glyphicon-chevron-right glyphicon_right_arrow"></span></button>
</div>
</div>
</div></code>```

Body:
I am trying to achieve the following: I am using bootstrap, standard btn class.

So far I the background image is kind of in the correct position, but it gets cut off. I've tried overflow: visible; etc...

.btn {
  background: url('../images/button.svg') no-repeat;
  background-repeat: no-repeat;
  background-position: left;
  padding-left: 80px;
}

<button class="btn btn-default btn-lg">GET A FREE QUOTE </button>

Thanks for any help

Body:
.btn_button, .btn_button:hover, .btn_button:focus{
  background: orange;
  color: blue;
  margin-left: -10px;
  margin-top: 3px;
  width: 150px;
  outline: none;
}
.round_div{
  display: flex;
}
.round2:before{
    content: "\25cf";
    font-size: 14px;
    padding: 0px 3px;
    border: 4px solid #000;
    border-radius: 50%;
}
.round1{
    border: 10px solid orange;
    border-radius: 50%;
}
.glyphicon_right_arrow{
    color: #fff;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="col-xs-12 form-group"></div>
<div class="col-xs-12">
<div class="round_div">
<div class="">
<div class="round">
<div class="round1">
<span class="round2"></span>
</div>
</div>
</div>
<div class="">
  <button class="btn btn_button" value="">MORE ABOUT US
<span class="glyphicon glyphicon-chevron-right glyphicon_right_arrow"></span></button>
</div>
</div>
</div>


问:
how to intercept all requests in spring REST controllers?
I have a bunch of controllers like:

```<code>@RestController
public class AreaController {
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<Area> get(@RequestParam(value = "id", required = true) Serializable id) { ... }
}
</code>```

and I need to intercept all the requests that reach them,

I created an interceptor like this example:

http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

but it never enters :(

because I'm using only annotations, i don't have a XML to define the interceptor,
what I've found its to set it like this:

```<code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test.app")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ControllerInterceptor getControllerInterceptor() {
        ControllerInterceptor c = new ControllerInterceptor();
        return c;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getControllerInterceptor());
        super.addInterceptors(registry);
    }

}
</code>```

what am i doing wrong or am i missing something?

答:
your Interceptor class ControllerInterceptor isn't an application context managed bean. Make sure you put @Component annotation on ControllerInterceptor  and add it's package to @ComponentScan. So, let's say your ControllerInterceptor resides in package com.xyz.interceptors like:

```<code>package com.xyz.interceptors;  //this is your package

@Component //put this annotation here
public class ControllerInterceptor extends HandlerInterceptorAdapter{
 // code here
}
</code>```

and your AppConfig becomes:

```<code>@ComponentScan(basePackages = { "com.test.app", "com.xyz.interceptors" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ...
}
</code>```

Body:
I have a bunch of controllers like:

@RestController
public class AreaController {
    @RequestMapping(value = "/area", method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<Area> get(@RequestParam(value = "id", required = true) Serializable id) { ... }
}

and I need to intercept all the requests that reach them,

I created an interceptor like this example:

http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/

but it never enters :(

because I'm using only annotations, i don't have a XML to define the interceptor,
what I've found its to set it like this:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test.app")
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ControllerInterceptor getControllerInterceptor() {
        ControllerInterceptor c = new ControllerInterceptor();
        return c;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getControllerInterceptor());
        super.addInterceptors(registry);
    }

}

what am i doing wrong or am i missing something?

Body:
your Interceptor class ControllerInterceptor isn't an application context managed bean. Make sure you put @Component annotation on ControllerInterceptor  and add it's package to @ComponentScan. So, let's say your ControllerInterceptor resides in package com.xyz.interceptors like:

package com.xyz.interceptors;  //this is your package

@Component //put this annotation here
public class ControllerInterceptor extends HandlerInterceptorAdapter{
 // code here
}

and your AppConfig becomes:

@ComponentScan(basePackages = { "com.test.app", "com.xyz.interceptors" })
public class AppConfig extends WebMvcConfigurerAdapter {
// ...
}


问:
Laravel eager loading combine where for multiple tables
I have problem with Laravel eager loading, I want to search many to one related tables.

I have two models, Book and Author.
I have relation belongsTo (in Book model) and hasMany (in Author model).

```<code>Books: id, title, description, author, tags, type
Author: id, name, birth, tags, type
</code>```

(this is not the real columns, I have a lot of columns, this is only for example)

I must to use models for searching, I can't use DB or raw queries for the relations.

So, my question is how can I search by parent table into Model->with() function ?

```<code>Model->with('author', function($query) use($search) {
    $query->where('author.name', '=', $search);
    $query->orWhere('book.title', '=', $search);
});
</code>```

The important thing is that I need to get Books, and I must to be able to use $book->author (or on $results->toArray() to get all Book data with Author data in ->author property)

I hope that you understand me what I want to ask.

Best regards

答:
Use with to eager load the author and whereHas to filter the records.

```<code>Book::with('author', function($query) use($search) {
    $query->where('name', '=', $search);
})->whereHas('author', function($query) use($search) {
    $query->where('name', '=', $search);
})
 ->where('title', '=', $search)
 ->get();
</code>```

Body:
I have problem with Laravel eager loading, I want to search many to one related tables.

I have two models, Book and Author.
I have relation belongsTo (in Book model) and hasMany (in Author model).

Books: id, title, description, author, tags, type
Author: id, name, birth, tags, type

(this is not the real columns, I have a lot of columns, this is only for example)

I must to use models for searching, I can't use DB or raw queries for the relations.

So, my question is how can I search by parent table into Model->with() function ?

Model->with('author', function($query) use($search) {
    $query->where('author.name', '=', $search);
    $query->orWhere('book.title', '=', $search);
});

The important thing is that I need to get Books, and I must to be able to use $book->author (or on $results->toArray() to get all Book data with Author data in ->author property)

I hope that you understand me what I want to ask.

Best regards

Body:
Use with to eager load the author and whereHas to filter the records.

Book::with('author', function($query) use($search) {
    $query->where('name', '=', $search);
})->whereHas('author', function($query) use($search) {
    $query->where('name', '=', $search);
})
 ->where('title', '=', $search)
 ->get();


问:
Two characters in a for loop not comparing properly
I narrowed down my problem to if($reqFnameArr[$i] == $fnameArr[$i]) I don't know why it's not comparing properly those two variables contain single characters from the split. Because when I try to output $finUsername is stays empty.

```<code>//fetch firstname in Database
$fname = User::select('first_name')->where('username', $request->username)
                  ->where('first_name', '!=', $request->first_name)->get();
$fnameArr = str_split($fname);
//request firstname
$reqFname = $request->first_name;
$reqFnameArr = str_split($reqFname);
//final username
$finUsername = '';
for($i = 0; $i < strlen($reqFname); $i++) {
  if($reqFnameArr[$i] == $fnameArr[$i]) {
  $finUsername .= $reqFnameArr[$i];
  }
}
</code>```

EDIT
I am saving finUsername to a database after comparing the arrays

```<code>  $user = User::create($request->all());

              $user->update(['role_id' => $request->role]);
              $user->save();
              $user->update(['username' => $finUsername]);
              $user->save();

              $roleName = $user->role()->name;

              return response()->json(['user' => $user, 'roleName' => $roleName,'manager_exists'=>'0']);
</code>```

答:
Its comparing. I have done some R&D. You can test this way.

```<code>$fname ='Hello1'; $reqFname ='Hello2';

 $fnameArr = str_split($fname);

          //request firstname //   $reqFname = $request->first_name;
          $reqFnameArr = str_split($reqFname); //print_r($reqFnameArr); //print_r($fnameArr);
          //final username
          $finUsername = '';

          for($i = 0; $i < strlen($reqFname); $i++) {
            // echo $reqFnameArr[$i].'  '.$fnameArr[$i];die;
            if($reqFnameArr[$i] == $fnameArr[$i]) {
              //  echo 'coming here';
              $finUsername.= $reqFnameArr[$i];
            }
          } echo $finUsername;
</code>```

Let me know if you have any other issue.

Body:
I narrowed down my problem to if($reqFnameArr[$i] == $fnameArr[$i]) I don't know why it's not comparing properly those two variables contain single characters from the split. Because when I try to output $finUsername is stays empty.

//fetch firstname in Database
$fname = User::select('first_name')->where('username', $request->username)
                  ->where('first_name', '!=', $request->first_name)->get();
$fnameArr = str_split($fname);
//request firstname
$reqFname = $request->first_name;
$reqFnameArr = str_split($reqFname);
//final username
$finUsername = '';
for($i = 0; $i < strlen($reqFname); $i++) {
  if($reqFnameArr[$i] == $fnameArr[$i]) {
  $finUsername .= $reqFnameArr[$i];
  }
}

EDIT
I am saving finUsername to a database after comparing the arrays

  $user = User::create($request->all());

              $user->update(['role_id' => $request->role]);
              $user->save();
              $user->update(['username' => $finUsername]);
              $user->save();

              $roleName = $user->role()->name;

              return response()->json(['user' => $user, 'roleName' => $roleName,'manager_exists'=>'0']);

Body:
Its comparing. I have done some R&D. You can test this way.

$fname ='Hello1'; $reqFname ='Hello2';

 $fnameArr = str_split($fname);

          //request firstname //   $reqFname = $request->first_name;
          $reqFnameArr = str_split($reqFname); //print_r($reqFnameArr); //print_r($fnameArr);
          //final username
          $finUsername = '';

          for($i = 0; $i < strlen($reqFname); $i++) {
            // echo $reqFnameArr[$i].'  '.$fnameArr[$i];die;
            if($reqFnameArr[$i] == $fnameArr[$i]) {
              //  echo 'coming here';
              $finUsername.= $reqFnameArr[$i];
            }
          } echo $finUsername;

Let me know if you have any other issue.


问:
How to guarantee azure queue FIFO
I understand that MS Azure Queue service document http://msdn.microsoft.com/en-us/library/windowsazure/dd179363.aspx says first out (FIFO) behavior is not guaranteed.

However, our application is such that ALL the messages have to be read and processed in FIFO order. Could anyone please suggest how to achieve a guaranteed FIFO using Azure Queue Service?

Thank you.

答:
You just need to follow below steps to ensure Message ordering.:

1) Create a Queue with session enabled=false.
2) While saving message in the queue, provide the session id like below:-

```<code>var message = new BrokeredMessage(item);
message.SessionId = "LB";
Console.WriteLine("Response from Central Scoring System : " + item);
client.Send(message);
</code>```

3) While creating receiver for reviving message:-

```<code>queueClient.OnMessage(s =>
{
    var body = s.GetBody<string>();
    var messageId = s.MessageId;
    Console.WriteLine("Message Body:" + body);
    Console.WriteLine("Message Id:" + messageId);
});
</code>```

4) While having the same session id, it would automatically ensure order and give the ordered message.

Thanks!!

Title: How to guarantee azure queue FIFO

Body:
You just need to follow below steps to ensure Message ordering.:

1) Create a Queue with session enabled=false.
2) While saving message in the queue, provide the session id like below:-

var message = new BrokeredMessage(item);
message.SessionId = "LB";
Console.WriteLine("Response from Central Scoring System : " + item);
client.Send(message);

3) While creating receiver for reviving message:-

queueClient.OnMessage(s =>
{
    var body = s.GetBody<string>();
    var messageId = s.MessageId;
    Console.WriteLine("Message Body:" + body);
    Console.WriteLine("Message Id:" + messageId);
});

4) While having the same session id, it would automatically ensure order and give the ordered message.

Thanks!!


问:
Remove Scriptlet <%some text here%> tags from string in C#
How Can we remove all the scriptlet tags i.e. <% some text here %> from a string. Example string: this is a string <% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.

答:
you can try this regex:

<%[^%>]*%>

Explanation:
Regex finds all string that starts with <% and followed by (any character except for %>) and ends with %>.

Use it like this:

string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);

Tests:

```<code>sample1: "This is a string <%with_tag%> and tag <%new_tag%>."
result1: "This is a string  and tag ."

sample2: "This is a string <%with_tag%>tag%> and tag <%new_tag%>."
result2: "This is a string tag%> and tag ."
</code>```

Also, please note that this does not clear up the extra <space> especially when there are lots of consecutive tags.

```<code>sampleStr: "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>."
result: "This is a string tag%> and     tag      ."
</code>```

on which you can use another Regex (if performance really shouldn't matter):

result = new Regex("\s{2,}").Replace(result, " ");

so:

```<code>string sampleStr = "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%>.";
string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);
result = new Regex("\s{2,}").Replace(result, " ");
</code>```

If you consider performance, you should check this post.

Body:
you can try this regex:

<%[^%>]*%>

Explanation:
Regex finds all string that starts with <% and followed by (any character except for %>) and ends with %>.

Use it like this:

string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);

Tests:

sample1: "This is a string <%with_tag%> and tag <%new_tag%>."
result1: "This is a string  and tag ."

sample2: "This is a string <%with_tag%>tag%> and tag <%new_tag%>."
result2: "This is a string tag%> and tag ."

Also, please note that this does not clear up the extra <space> especially when there are lots of consecutive tags.

sampleStr: "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>."
result: "This is a string tag%> and     tag      ."

on which you can use another Regex (if performance really shouldn't matter):

result = new Regex("\s{2,}").Replace(result, " ");

so:

string sampleStr = "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%>.";
string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);
result = new Regex("\s{2,}").Replace(result, " ");

If you consider performance, you should check this post.


问:
Disable dynamically generated buttons in jquery
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

```<code><script>
    function getData(){
        $('input[name="articles"]:checked').map(function() {
            var content =  JSON.parse(decodeURIComponent(this.value));
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+name+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
            $('.box').html(content);
        });
        $('.remove').click(function(){
            $(this).parents('.parent').remove();
        });
        resetEvents();
    }
function addName(){
    var name= $("#articleTitle").val();
    content +='<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+Count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
        $('.box').html(content);
        $('.removeArticle').click(function(){
        $(this).parents('.parent').remove();
    });

}
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
function resetEvents() {
    $(".top-btn, .down-btn").unbind('click');
    handleEvents();
    $('.down-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertAfter($(toMove1).next());
        handleEvents();
    });
    $('.top-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertBefore($(toMove1).prev());
        handleEvents();
    });
}
</script>
</code>```

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

答:
For dynamically generated elements use delegated event handlers like this:</p>

```<code>$("body").on("click", selector, function() {
     //actions to do
});
</code>```

Body:
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

Body:
For dynamically generated elements use delegated event handlers like this:

$("body").on("click", selector, function() {
     //actions to do
});


问:
How to get the distinct count in a Pandas groupby
I would like to get the distinct count of products per order_number. I managed to get the total_product count (thanks to the help of another SO user), but I can't figure out the distinct count.

This is what I have:

```<code>data['total_productcount'] = data.groupby(['order_number'])['order_number'].transform('size')
</code>```

And it gives:

```<code>order_number          product_id      total_productcount
171-1046037-0511522   4260179734731   5
171-1046037-0511522   4054673034394   5
171-1046037-0511522   4054673001235   5
171-1046037-0511522   4054673005752   5
171-1046037-0511522   5011385960075   5
171-1046037-0511522   5011385960075   5
</code>```

This is the dataframe, that I would like to generate (including: distict_productcount)

```<code>order_number          product_id      total_productcount   distict_productcount
171-1046037-0511522   4260179734731   5                    1
171-1046037-0511522   4054673034394   5                    1
171-1046037-0511522   4054673001235   5                    1
171-1046037-0511522   4054673005752   5                    1
171-1046037-0511522   5011385960075   5                    1
171-1046037-0511522   5011385960075   5                    2
</code>```

How can I generate "distict_productcount" ?

答:
```<code>data.groupby('order_number').product_id.nunique()
</code>```

You can get a new column by either using transform or join

via transform

```<code>s = data.groupby('order_number').product_id.transform('nunique')
df = df.assign(distinct_productcount=s)
</code>```

via join

```<code>s = data.groupby('order_number').product_id.nunique()
df = df.join(s.rename('distinct_productcount'), on='order_number')
</code>```

Body:
I would like to get the distinct count of products per order_number. I managed to get the total_product count (thanks to the help of another SO user), but I can't figure out the distinct count.

This is what I have:

data['total_productcount'] = data.groupby(['order_number'])['order_number'].transform('size')

And it gives:

order_number          product_id      total_productcount
171-1046037-0511522   4260179734731   5
171-1046037-0511522   4054673034394   5
171-1046037-0511522   4054673001235   5
171-1046037-0511522   4054673005752   5
171-1046037-0511522   5011385960075   5
171-1046037-0511522   5011385960075   5

This is the dataframe, that I would like to generate (including: distict_productcount)

order_number          product_id      total_productcount   distict_productcount
171-1046037-0511522   4260179734731   5                    1
171-1046037-0511522   4054673034394   5                    1
171-1046037-0511522   4054673001235   5                    1
171-1046037-0511522   4054673005752   5                    1
171-1046037-0511522   5011385960075   5                    1
171-1046037-0511522   5011385960075   5                    2

How can I generate "distict_productcount" ?

Body:
data.groupby('order_number').product_id.nunique()

You can get a new column by either using transform or join

via transform

s = data.groupby('order_number').product_id.transform('nunique')
df = df.assign(distinct_productcount=s)

via join

s = data.groupby('order_number').product_id.nunique()
df = df.join(s.rename('distinct_productcount'), on='order_number')


问:
Android with Nexus 6 -- how to avoid decreased OpenSL audio thread priority relating to app focus?
I'm encountering a strange problem when trying to implement low-latency streaming audio playback on a Nexus 6 running Android 6.0.1 using OpenSL ES.

My initial attempt seemed to be suffering from starvation issues, so I added some basic timing benchmarks in the buffer completion callback function.  What I've found is that audio plays back fine if I continually tap the screen while my app is open, but if I leave it alone for a few seconds, the callback starts to take much longer.  I'm able to reproduce this behavior consistently.  A couple of things to note:

"a few seconds" ~= 3-5 seconds, not long enough to trigger a screen change

My application's activity sets FLAG_KEEP_SCREEN_ON, so no screen changes should occur anyway

I have taken no action to try to increase the audio callback thread's priority, since I was under the impression that Android reserves high priority for these threads already

The behavior occurs on my Nexus 6 (Android 6.0.1), but not on a Galaxy S6 I also have available (Android 5.1.1).

The symptoms I'm seeing really seem like the OS kicks down the audio thread priority after a few seconds of non-interaction with the phone.  Is this right?  Is there any way I can avoid this behavior?

答:
Force resampling to native device sample rate on Android 6.

Use the device's native sample rate of 48000. For example:

SLDataFormat_PCM dataFormat;

dataFormat.samplesPerSec = 48000;


答:
I really don't understand what you are trying to do here. Why the php string comparing functions are not used. But to answer your question:

That code of yours does output the common part of two strings sure enough. Take a look at this simple demonstration:

```<code><?php

$fname = 'Hello1';
$fnameArr = str_split($fname);

$reqFname = 'Hello2';
$reqFnameArr = str_split($reqFname);

//final username
$finUsername = '';

for($i = 0; $i < strlen($reqFname); $i++) {
    if($reqFnameArr[$i] == $fnameArr[$i]) {
        $finUsername .= $reqFnameArr[$i];
    }
}
var_dump($finUsername);
</code>```

The output is:

string(5) "Hello"

So most likely your real issue is that your attempt to fetch those two names does not deliver the values you claim, but most likely at least one empty string or something that evaluates to that when converted.

Title: Two characters in a for loop not comparing properly

Body:
I really don't understand what you are trying to do here. Why the php string comparing functions are not used. But to answer your question:

That code of yours does output the common part of two strings sure enough. Take a look at this simple demonstration:

<?php

$fname = 'Hello1';
$fnameArr = str_split($fname);

$reqFname = 'Hello2';
$reqFnameArr = str_split($reqFname);

//final username
$finUsername = '';

for($i = 0; $i < strlen($reqFname); $i++) {
    if($reqFnameArr[$i] == $fnameArr[$i]) {
        $finUsername .= $reqFnameArr[$i];
    }
}
var_dump($finUsername);

The output is:

string(5) "Hello"

So most likely your real issue is that your attempt to fetch those two names does not deliver the values you claim, but most likely at least one empty string or something that evaluates to that when converted.


问:
Target word using jQuery and add style
So, this could be a simple question, but my jQuery skills are just not quite up there (yet). I'm trying to target a specific word on a web page and add a style to it. The word I'm trying to target appears multiple times on the page. I googled around some and found this:

```<code><script>
    var divContent = document.getElementById("styled").innerHTML;
    divContent = divContent.replace("Bevestigd","<span class='styled'>Bevestigd</span>");
    divContent = divContent.replace("Geannuleerd","<span class='styled-r'>Geannuleerd</span>");
    divContent = divContent.replace("Pending","<span class='styled-p'>Pending</span>");
    document.getElementById("styled").innerHTML = divContent;
</script>
</code>```

This works, kind of... It only targets the first time it encounters the word and doesn't repeat it self. I found numerous pieces of code to target a word on a page but this one seems to work the best... Is there any one that could help me out?

Is there a foreach function I'm missing?

I also tried this code:

```<code>$('body').html(
    function(i,h){
        return h.replace(/(Nike)/g,'<span class="nike tm">$1</span>');
    });
</code>```

which seems a bit simpler but that didn't work... Maybe someone has a snippet for this or something?

答:
This is your js code done on jquery. Check out this jsfiddle

```<code>$('#styled').html(function(i,v){
       v=v.replace(/Bevestigd/g,'<span class="styled">Bevestigd</span>');
       v=v.replace(/Geannuleerd/g,'<span class="styled-r">Geannuleerd</span>');
       v=v.replace(/Pending/g,'<span class="styled-p">Pending</span>');
       return v;
    });
</code>```

This is done with regex.
We can extend it further.

eg. To make the search case insensitive use /Bevestigd/gi instead of /Bevestigd/g.

Title: Target word using jQuery and add style

Body:
So, this could be a simple question, but my jQuery skills are just not quite up there (yet). I'm trying to target a specific word on a web page and add a style to it. The word I'm trying to target appears multiple times on the page. I googled around some and found this:

This works, kind of... It only targets the first time it encounters the word and doesn't repeat it self. I found numerous pieces of code to target a word on a page but this one seems to work the best... Is there any one that could help me out?

Is there a foreach function I'm missing?

I also tried this code:

$('body').html(
    function(i,h){
        return h.replace(/(Nike)/g,'$1');
    });

which seems a bit simpler but that didn't work... Maybe someone has a snippet for this or something?

Body:
This is your js code done on jquery. Check out this jsfiddle

$('#styled').html(function(i,v){
       v=v.replace(/Bevestigd/g,'<span class="styled">Bevestigd</span>');
       v=v.replace(/Geannuleerd/g,'<span class="styled-r">Geannuleerd</span>');
       v=v.replace(/Pending/g,'<span class="styled-p">Pending</span>');
       return v;
    });

This is done with regex.
We can extend it further.

eg. To make the search case insensitive use /Bevestigd/gi instead of /Bevestigd/g.


问:
How to check two arrays of objects by propery id and if there is mach add property from one to anothe
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

```<code>var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];
</code>```

I have searched for similar questions but could not find any or did not see that.

答:
Checkout Here on how to search in objects and arrays at the sometime, without necessarily knowing the depth of the object or array

var o = {
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "arr":[1,2,3],
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
};

//called with every property and it's value
function process(key,value,path) {
  var log = 'key: ' +key + ", value: "+value+", path: "+path;
    console.log(log);
    var node = document.createElement("LI");
    var textnode = document.createTextNode(log);
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}

function traverse(o,path,func) {
    for (var i in o) {

        if (o[i] !== null && typeof(o[i])=="object") {
            //going on step down in the object tree!!
            o[i].path = path+'/'+i;
            traverse(o[i],o[i].path,func);
        }else if(i !== 'path'){
         func.apply(this,[i,o[i], path+'/'+i]);
        }

    }
}

//that's all... no magic, no bloated framework
traverse(o,'root',process);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="myList">

</ul></code>```

Body:
How to compare two arrays of objects by id and then if id's match add property cr with value to matching object in the array arr.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

var arr1 =[{
    id:1,
    cr:1313
}, {
    id:2,
    cr:304
}];

I have searched for similar questions but could not find any or did not see that.

Body:
Checkout Here on how to search in objects and arrays at the sometime, without necessarily knowing the depth of the object or array

var o = {
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "arr":[1,2,3],
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
};

//called with every property and it's value
function process(key,value,path) {
  var log = 'key: ' +key + ", value: "+value+", path: "+path;
    console.log(log);
    var node = document.createElement("LI");
    var textnode = document.createTextNode(log);
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}

function traverse(o,path,func) {
    for (var i in o) {

        if (o[i] !== null && typeof(o[i])=="object") {
            //going on step down in the object tree!!
            o[i].path = path+'/'+i;
            traverse(o[i],o[i].path,func);
        }else if(i !== 'path'){
         func.apply(this,[i,o[i], path+'/'+i]);
        }

    }
}

//that's all... no magic, no bloated framework
traverse(o,'root',process);

<ul id="myList">

</ul>


问:
How do I delete joomla template?
I installed a new template for my joomla site but after that I have no access template manager. It only becomes a completely white page in Firefox and Opera says that "currently unable to handle the request." Is there any way to delete a template outside of the webadmin interface?</p>

答:
You can delete through your ftp client like filezilla. Open filezilla, login to your server and the delete the template. May be the template comes with some plugins or else how can just by installing it started showing error unless you use that template. Possibility is: i) You might have installed a template for older version. ii) You might have installed a plugin with the template that was autopublished. iii) You messed up some setting files.

I suggest you to open file manager, go to templates and then delete that particular template. Also when asking please ask providing all details like name of template, link of template etc.

Title: How do I delete joomla template?


问:
Button inside iframe click functionality changes height of that parent iframe(cross domain)
on click change in height to 500px;

```<code><iframe src="test.html" frameborder="0" scrolling="no" id="myIframe" class="chat-box width-350" style="height:300px;"></iframe>
</code>```

iframe height is set to 300px

test.html

```<code><a href="javascript:void(0)" class="clickhere">button</a>
</code>```

when clicking on "clickhere" will change in height of iframe.

答:
Try this

for test.html

```<code><a href="javascript:void(0)" class="clickhere">button</a>
<script type="text/javascript">
var parentIframe = window.parent.document.getElementById('myIframe');
var clickButton = document.getElementsByClassName('clickhere')[0];

clickButton.addEventListener("click", function(){
  parentIframe.style.height = '500px';
  console.log(parentIframe);
});
</script>
</code>```

Body:
on click change in height to 500px;

iframe height is set to 300px

test.html

button

when clicking on "clickhere" will change in height of iframe.

Body:
Try this

for test.html

<a href="javascript:void(0)" class="clickhere">button</a>
<script type="text/javascript">
var parentIframe = window.parent.document.getElementById('myIframe');
var clickButton = document.getElementsByClassName('clickhere')[0];

clickButton.addEventListener("click", function(){
  parentIframe.style.height = '500px';
  console.log(parentIframe);
});
</script>


问:
How can I find android ndk 1.5 r1 installation file?
I cannot find the old Android ndk 1.5 r1 installation file anywhere on the web (right now its r4b)? I think google dropped it becuase it shouldnt be needed anymore. Does anyone know where I can find it?

/Br Johannes

答:
It's not needed anymore.
The newer versions include everything the old versions had.</p>


问:
Echo file URL from Laravel storage
Im using this code in my laravel view to echo a files path, but its coming up in chrome dev tools with a 404 response.

image) }}">

which echos this onto the page

http://localhost:8000/storage/public/bd0e2f7f.png

The file lives there and this is the correct name for the file so im not entirely sure why its coming up with a 404!

答:
Simple solution can be:

```<code><img src="{{ Storage::url($post->image) }}">
</code>```

Reference here .

I am assuming you have included Storage as you also used it in your code, if not then use this:

```<code><img src="{{ \Illuminate\Support\Facades\Storage::url($post->image) }}">
</code>```

Title: Echo file URL from Laravel storage

Body:
Simple solution can be:

<img src="{{ Storage::url($post->image) }}">

Reference here .

I am assuming you have included Storage as you also used it in your code, if not then use this:

<img src="{{ \Illuminate\Support\Facades\Storage::url($post->image) }}">


问:
Check if an object exists in other objects' sub-objects within an array
I have kind of this Array :

```<code>array = [
     {
      a:0,
      b:{x:1,y:2}
     },
     {
      c:0,
      b:{x:3,y:2}},
    ]
</code>```

And I have a new object like this

```<code>{
 e:0,
 b:{x:2,y:5}
}
</code>```

I want to test whether the objects in array have the same nested b object or not, if so I'll push the new object there, if it already exists, I'll replace the whole object with the newer one.
Any help how could I achieve that please (Lodash, ES6..),
I'm using Typescript btw.

答:
You can simply use Array.prototype.some() method with your array to test if there's any matching b object with the searched object, your code will be:

```<code>function checkIfObjectExists(array, obj) {
  return array.some(function(element) {
    return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b);
  });
}
</code>```

This is a working snippet:

function checkIfObjectExists(array, obj) {
  return array.some(function(element) {
    return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b);
  });
}

array = [{
    a: 0,
    b: {
      x: 1,
      y: 2
    }
  },
  {
    c: 0,
    b: {
      x: 3,
      y: 2
    }
  },
];

var searched = {
  e: 0,
  b: {
    x: 2,
    y: 5
  }
};

//Check an existing userId
console.log(checkIfObjectExists(array, searched));

//Check a non existing userId
console.log(checkIfObjectExists(array, {
  a: 0,
  b: {
    x: 1,
    y: 2
  }
}));```

Body:
I have kind of this Array :

array = [
     {
      a:0,
      b:{x:1,y:2}
     },
     {
      c:0,
      b:{x:3,y:2}},
    ]

And I have a new object like this

{
 e:0,
 b:{x:2,y:5}
}

I want to test whether the objects in array have the same nested b object or not, if so I'll push the new object there, if it already exists, I'll replace the whole object with the newer one.
Any help how could I achieve that please (Lodash, ES6..),
I'm using Typescript btw.

Body:
You can simply use Array.prototype.some() method with your array to test if there's any matching b object with the searched object, your code will be:

function checkIfObjectExists(array, obj) {
  return array.some(function(element) {
    return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b);
  });
}

This is a working snippet:

function checkIfObjectExists(array, obj) {
  return array.some(function(element) {
    return (typeof obj.b === typeof element.b) && JSON.stringify(obj.b) === JSON.stringify(element.b);
  });
}

array = [{
    a: 0,
    b: {
      x: 1,
      y: 2
    }
  },
  {
    c: 0,
    b: {
      x: 3,
      y: 2
    }
  },
];

var searched = {
  e: 0,
  b: {
    x: 2,
    y: 5
  }
};

//Check an existing userId
console.log(checkIfObjectExists(array, searched));

//Check a non existing userId
console.log(checkIfObjectExists(array, {
  a: 0,
  b: {
    x: 1,
    y: 2
  }
}));


问:
awk BEGIN compare multiple variables in if statement
I'm trying to compare some floats/version numbers in bash for which i'm using awk BEGIN with if statement.
I was able to do comparison and get proper output when i'm using 2 variables.
But in case of 3 variables i'm not able to get the output.

Objective:

What i want to achieve is if the input is between two values 4.8.0 & 4.10.0, ( i.e., 4.8.0 <= inp < 4.10.0 ) then output 1 else output 0.

CODE Block

Below is what i wrote:

```<code>inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1<n2) printf (0); else if (n1<n3) printf (1); else printf (0);}'`
</code>```

another way i tried is comparing with multiple conditions

```<code>inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1>n2 && n1<n3) printf (1); else printf (0);}'`
</code>```

Queries:
Please help on how can i achieve same using awk BEGIN if?
Also if there is any other way by which i can compare float inputs?

答:
If your sort supports version sort, you can use this quick mechanism:

```<code>if [ $(printf "%s\n" 4.8.0 "$inp" 4.10.0 | sort -V | awk NR==2 ) == "$inp" ]; then
    : Do something
fi
</code>```

Body:
I'm trying to compare some floats/version numbers in bash for which i'm using awk BEGIN with if statement.
I was able to do comparison and get proper output when i'm using 2 variables.
But in case of 3 variables i'm not able to get the output.

Objective:

What i want to achieve is if the input is between two values 4.8.0 & 4.10.0, ( i.e., 4.8.0 <= inp < 4.10.0 ) then output 1 else output 0.

CODE Block

Below is what i wrote:

inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1<n2) printf (0); else if (n1<n3) printf (1); else printf (0);}'`

another way i tried is comparing with multiple conditions

inp=4.9.4
out=`awk -v n1=$inp -v n2=4.8.0 -v n3=4.10.0 \
  'BEGIN {if (n1>n2 && n1<n3) printf (1); else printf (0);}'`

Queries:
Please help on how can i achieve same using awk BEGIN if?
Also if there is any other way by which i can compare float inputs?

Body:
If your sort supports version sort, you can use this quick mechanism:

if [ $(printf "%s\n" 4.8.0 "$inp" 4.10.0 | sort -V | awk NR==2 ) == "$inp" ]; then
    : Do something
fi


问:
how to make the following scala immutable
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)
</code>```

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}
</code>```

How do I implement it in immutable way?

答:
It looks like what you are looking for is all unique Students in the nested collection.

A very simple way to do this is by flattening the collection and converting it to a Set; here is an example with Ints:

```<code>scala> val groups = List(Iterator(1,2,3), Iterator(3,4,5))
groups: List[Iterator[Int]] = List(non-empty iterator, non-empty iterator)

scala> val unique: Set[Int] = groups.flatten.toSet
unique: Set[Int] = Set(5, 1, 2, 3, 4)
</code>```

A problem here is that the toSet methods actually copies your list. To avoid this, you can use this little trick (you can read more about collection.breakOut and CanBuildFrom here):

```<code>scala> val unique: Set[Int] = groups.flatMap(identity)(collection.breakOut)
unique: Set[Int] = Set(5, 1, 2, 3, 4)
</code>```

However, the source of mutability here is the usage of an Iterator which will be consumed anyway, there mutating and breaking referential transparency.

Body:
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}

How do I implement it in immutable way?

Body:
It looks like what you are looking for is all unique Students in the nested collection.

A very simple way to do this is by flattening the collection and converting it to a Set; here is an example with Ints:

scala> val groups = List(Iterator(1,2,3), Iterator(3,4,5))
groups: List[Iterator[Int]] = List(non-empty iterator, non-empty iterator)

scala> val unique: Set[Int] = groups.flatten.toSet
unique: Set[Int] = Set(5, 1, 2, 3, 4)

A problem here is that the toSet methods actually copies your list. To avoid this, you can use this little trick (you can read more about collection.breakOut and CanBuildFrom here):

scala> val unique: Set[Int] = groups.flatMap(identity)(collection.breakOut)
unique: Set[Int] = Set(5, 1, 2, 3, 4)

However, the source of mutability here is the usage of an Iterator which will be consumed anyway, there mutating and breaking referential transparency.


问:
Unable to establish SSL connection, how do I fix my SSL cert?
I'm trying to wget to my own box, and it can't be an internal address in the wget (so says another developer).

When I wget, I get this:

```<code>wget http://example.com
--2013-03-01 15:03:30--  http://example.com/
Resolving example.com... 172.20.0.224
Connecting to example.com|172.20.0.224|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://www.example.com/ [following]
--2013-03-01 15:03:30--  https://www.example.com/
Resolving www.example.com... 172.20.0.224
Connecting to www.example.com|172.20.0.224|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
</code>```

I believe it is because I do not have the certificate setup properly. Using openssl:

```<code>openssl s_client -connect example.com:443
CONNECTED(00000003)
15586:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:
</code>```

While if I do the same command on another site, it shows the entire cert.

Perhaps the ssl cert was never setup in the conf file on Apache for that domain?

If so, what should I be specifying in the virtualhost? Is there any alternative other than specifying --no-check-certificate because I don't want to do that?

答:
I  meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

```<code>LoadModule ssl_module modules/mod_ssl.so
Listen 443
</code>```

Body:
I'm trying to wget to my own box, and it can't be an internal address in the wget (so says another developer).

When I wget, I get this:

wget http://example.com
--2013-03-01 15:03:30--  http://example.com/
Resolving example.com... 172.20.0.224
Connecting to example.com|172.20.0.224|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://www.example.com/ [following]
--2013-03-01 15:03:30--  https://www.example.com/
Resolving www.example.com... 172.20.0.224
Connecting to www.example.com|172.20.0.224|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.

I believe it is because I do not have the certificate setup properly. Using openssl:

openssl s_client -connect example.com:443
CONNECTED(00000003)
15586:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:588:

While if I do the same command on another site, it shows the entire cert.

Perhaps the ssl cert was never setup in the conf file on Apache for that domain?

If so, what should I be specifying in the virtualhost? Is there any alternative other than specifying --no-check-certificate because I don't want to do that?

Body:
I  meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

LoadModule ssl_module modules/mod_ssl.so
Listen 443


问:
Wordpress - Exclude most recent post from loop
I'm making a blog page where the most recent post is featured and displayed differently from the other posts. I'm doing that with WP_Query->query('showposts=1'); and it's working fine. I also have wp_reset_postdata(); after the end of the while loop.

Next, I have another loop where I want to show 9 posts without the most recent one. I'm using the following code found on wpbeginner.com:

```<code>query_posts('posts_per_page=9&offset=1');
if(have_posts()) :
...
</code>```

It seemed to be working fine until I checked the older posts page - it displays the same posts! I tried to add sorting by date, wp_reset_postdata(); and some other solutions, but nothing worked.

Am I missing something, or is this method flawed?

答:
Its happening as because you have changed the query through query_posts functions. Please use WP_QUERY instead of it.

```<code> $args = array(
         'post_type'=> 'post',
         'offset'=>1,
 );
 $query=new WP_Query($args);
 while ( $query->have_posts() ) : $query->the_post();

    echo get_the_ID();

 endhwhile; endif;
</code>```

hope it will work for you.

Body:
I'm making a blog page where the most recent post is featured and displayed differently from the other posts. I'm doing that with WP_Query->query('showposts=1'); and it's working fine. I also have wp_reset_postdata(); after the end of the while loop.

Next, I have another loop where I want to show 9 posts without the most recent one. I'm using the following code found on wpbeginner.com:

query_posts('posts_per_page=9&offset=1');
if(have_posts()) :
...

It seemed to be working fine until I checked the older posts page - it displays the same posts! I tried to add sorting by date, wp_reset_postdata(); and some other solutions, but nothing worked.

Am I missing something, or is this method flawed?

Body:
Its happening as because you have changed the query through query_posts functions. Please use WP_QUERY instead of it.

 $args = array(
         'post_type'=> 'post',
         'offset'=>1,
 );
 $query=new WP_Query($args);
 while ( $query->have_posts() ) : $query->the_post();

    echo get_the_ID();

 endhwhile; endif;

hope it will work for you.


问:
python error where __str__ returns a NoneType
```<code>class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)

class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')

a = Map()
print(a)
</code>```

I am trying to make a class that defines a grid where each place in the grid has a character, but when I run the code I get an error that tells me that __str__ returns a NoneType. I know I am not yet handeling file imput when initiating Map but that isn't the problem here, here is the output I got.

```<code>{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status
</code>```

I am also confused why the print in __str__ from Map refered me to the __main__.Pixel objects instead of using they __str__ method, but that is probably just my lack of knowlage

what am I missing?

答:
You should use __repr__. Also in Map.__str__, you are not returning anything.For ex

```<code>In [10]: class Test:
   ....:     def __str__(self):
   ....:         return "str"
   ....:     def __repr__(self):
   ....:         return "repr"
   ....:

In [11]: t=Test()

In [12]: t
Out[12]: repr

In [13]: print(t)
str
</code>```

Body:
class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)

class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')

a = Map()
print(a)

I am trying to make a class that defines a grid where each place in the grid has a character, but when I run the code I get an error that tells me that __str__ returns a NoneType. I know I am not yet handeling file imput when initiating Map but that isn't the problem here, here is the output I got.

{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status

I am also confused why the print in __str__ from Map refered me to the __main__.Pixel objects instead of using they __str__ method, but that is probably just my lack of knowlage

what am I missing?

Body:
You should use __repr__. Also in Map.__str__, you are not returning anything.For ex

In [10]: class Test:
   ....:     def __str__(self):
   ....:         return "str"
   ....:     def __repr__(self):
   ....:         return "repr"
   ....:

In [11]: t=Test()

In [12]: t
Out[12]: repr

In [13]: print(t)
str


问:
Error "not mutually convertible in Unicode program" when adding line to table
I'm trying to add data from a internal table to a custom one.

```<code> DATA: BEGIN OF TMP_CTRYGRP_T OCCURS 1000,
  CTYGR TYPE /SAPSLL/CTYGR,
  TEXT1 TYPE /SAPSLL/TEXT60,
  END OF TMP_CTRYGRP_T.

SELECT ctygr, text1 FROM /SAPSLL/CTYGPT INTO TABLE @DATA(lt_countryGroupsTable)

LOOP AT lt_countryGroupsTable ASSIGNING FIELD-SYMBOL(<ls_countryGroups>).
  APPEND <ls_countryGroups> TO TMP_CTRYGRP_T.
ENDLOOP.
</code>```

Then I want to add the line in a custom Table Type ZZ_T_TAB

So I've tried to create a field-symbol of this table, creating an internal table from it, but none of the solutions I've tried was permitting me to add lines in that Custom table (even if the one in the program had the lines).

The problem I mainly encountered was:

are not mutually convertible in a Unicode program.

So my questions are:

Why does that error happen? Googling it didn't provide me an understandable answer

For the moment I'm using an internal table limited to 1000 rows. But I don't really know by advance the number of lines the search could provide. Is there any way to improve that?

How to add lines from any solution to my ZZ_T_TAB then? And afterwards how could I add other fields in the same table, for the rows already existing?

As some of you maybe understood, I'm quite a rookie in ABAP.
So if there's any useful link to understand all of that I would be happy if you can share it with me.

答:
Why does that error happen? Googling it didn't provide me an
  understandable answer

You cannot use APPEND with non-identical structures. You have to "convert" it before. Look up for the command MOVE-CORRESPODING in ABAP help (F1 on command in editor).

For the moment I'm using an internal table limited to 1000 rows. But I
  don't really know by advance the number of lines the search could
  provide. Is there any way to improve that?

Do not use OCCURS extension it is deprecated (as lausek wrote), old syntax.

How then to add lines from any solution to my ZZ_T_TAB ? And
  afterwards how could I add other fields in the same table, for the
  rows already existing?

You can modify a DB table various ways.:

1, Use UPDATE statement to directly update a field value.

2, Use MODIFY statement to modify field values from a (for example) pre-selected
structure.

Look up the UPDATE and MODIFY command in ABAP help, there are really helpful code examples.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add data from a internal table to a custom one.

 DATA: BEGIN OF TMP_CTRYGRP_T OCCURS 1000,
  CTYGR TYPE /SAPSLL/CTYGR,
  TEXT1 TYPE /SAPSLL/TEXT60,
  END OF TMP_CTRYGRP_T.

SELECT ctygr, text1 FROM /SAPSLL/CTYGPT INTO TABLE @DATA(lt_countryGroupsTable)

LOOP AT lt_countryGroupsTable ASSIGNING FIELD-SYMBOL(<ls_countryGroups>).
  APPEND <ls_countryGroups> TO TMP_CTRYGRP_T.
ENDLOOP.

Then I want to add the line in a custom Table Type ZZ_T_TAB

So I've tried to create a field-symbol of this table, creating an internal table from it, but none of the solutions I've tried was permitting me to add lines in that Custom table (even if the one in the program had the lines).

The problem I mainly encountered was:

are not mutually convertible in a Unicode program.

So my questions are:

Why does that error happen? Googling it didn't provide me an understandable answer

For the moment I'm using an internal table limited to 1000 rows. But I don't really know by advance the number of lines the search could provide. Is there any way to improve that?

How to add lines from any solution to my ZZ_T_TAB then? And afterwards how could I add other fields in the same table, for the rows already existing?

As some of you maybe understood, I'm quite a rookie in ABAP.
So if there's any useful link to understand all of that I would be happy if you can share it with me.


问:
Get absolute path to workspace directory in Jenkins Pipeline plugin
I'm currently doing some evaluation on the Jenkins Pipeline plugin (formerly know as Workflow plugin).
Reading the documentation I found out that I currently cannot retriev the workspace path using
env.WORKSPACE:

The following variables are currently unavailable inside a workflow script:

NODE_LABELS

WORKSPACE

SCM-specific variables such as SVN_REVISION

Is there any other way how to get the absolute path to the current workspace? I need this running some test which in turn gets some parameter (absolute path to some executable file).
I already tried using new File("").absolutePath() inside a @NonCPS section but looks like the non-CPS stuff gets always executed on the master.

Does anybody have a clue how to get this path without running some batch script which stores the path into some file which later on can be read in again?

答:
Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

```<code>node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}
</code>```

Body:
Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}