问:
Cannot change or get Session from Controller
i am working on a project on ASP.NET MVC, and i need to use Session to store some data.

This is the code:

HomeController.cs

```<code>public class HomeController : Controller
{
    public HomeController()
    {
    }

    public void ChangeValue(){
        //I get userId with some other data from db and set to session
        //but for the sake of simplicity i set here to 10.
        Session["getSession"] = "10";
    }

    //I use this method only for getting the changed session value
    public ActionResult GetWaiting()
        {
            //now i just need to return the changed value
            return Json(Session["getSession"], JsonRequestBehavior.AllowGet);
        }
}
</code>```

Web.config

```<code><system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <sessionState mode="InProc" timeout="1" cookieless="true" />
</system.web>
</code>```

Index.cshtml

```<code><h1 id="session"></h1>
@section scripts{

<script>
    $(function () {
        function getWait() {
            $.ajax({
                url: 'http://localhost:50325/Home/GetWaiting',
                success: function (data) {
                    $('#session').text('@Session["getSession"]');
                }
            });
        }

        setInterval(function () {
            getWait();
        }, 1000);
})
</script>

}
</code>```

But the problem is that everytime i try to get data from that Session, it returns null (just like i never used it).
I also tried setting Session with System.Web.HttpContext.Current.Session["getSession"] but still the same, it does not make any changes.
I also tried changing timeout and removing cookieless from  in Web.config but still the same.

p.s. I need to store that value to Session, beucase the value is being changed by another method, and i just need to retrieve the new value that has been set by another method.

答:
In GetWaiting method return the value of session as below

```<code>public ActionResult GetWaiting()
{
    //I get userId with some other data from db and set to session
    //but for the sake of simplicity i set here to 10.
    Session["getSession"] = "10";
    var data = Session["getSession"];
    return Json(data, JsonRequestBehavior.AllowGet);
}
</code>```

and in script assign that returned value.

```<code>success: function (data) {
    $('#session').text(data);
}
</code>```

Body:
i am working on a project on ASP.NET MVC, and i need to use Session to store some data.

This is the code:

HomeController.cs

public class HomeController : Controller
{
    public HomeController()
    {
    }

    public void ChangeValue(){
        //I get userId with some other data from db and set to session
        //but for the sake of simplicity i set here to 10.
        Session["getSession"] = "10";
    }

    //I use this method only for getting the changed session value
    public ActionResult GetWaiting()
        {
            //now i just need to return the changed value
            return Json(Session["getSession"], JsonRequestBehavior.AllowGet);
        }
}

Web.config

<system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
    <sessionState mode="InProc" timeout="1" cookieless="true" />
</system.web>

Index.cshtml

@section scripts{

}

But the problem is that everytime i try to get data from that Session, it returns null (just like i never used it).
I also tried setting Session with System.Web.HttpContext.Current.Session["getSession"] but still the same, it does not make any changes.
I also tried changing timeout and removing cookieless from  in Web.config but still the same.

p.s. I need to store that value to Session, beucase the value is being changed by another method, and i just need to retrieve the new value that has been set by another method.

Body:
In GetWaiting method return the value of session as below

public ActionResult GetWaiting()
{
    //I get userId with some other data from db and set to session
    //but for the sake of simplicity i set here to 10.
    Session["getSession"] = "10";
    var data = Session["getSession"];
    return Json(data, JsonRequestBehavior.AllowGet);
}

and in script assign that returned value.

success: function (data) {
    $('#session').text(data);
}


来源: stackexchange

问:
UIViewController has no member 'method'
I have a method written in objective-c. It's like this.

```<code>-(void) onLongPress:(UILongPressGestureRecognizer *) longPressGestureRecognizer {
</code>```

I want to call this method from my swift file.So I did like this.

```<code>var longPressGuestureRecognizer = UILongPressGestureRecognizer(target: metrixUIViewController, action: #selector(metrixUIViewController.onLongPress(longPressGestureRecognizer:)))
</code>```

But it says MetrixUIViewController has no member onLongPress.
How can I solve this? Please help me.

答:
First check your bridging header is it correct?

Your onLongPress method will be public. should be declared in .h
 and .m file

Change at below

```<code>var longPressGuestureRecognizer = UILongPressGestureRecognizer(target: metrixUIViewController, action: #selector(metrixUIViewController.onLongPress(_:)))
</code>```

ContentLicense: CC BY-SA 3.0

Title: UIViewController has no member 'method'

Body:
I have a method written in objective-c. It's like this.

-(void) onLongPress:(UILongPressGestureRecognizer *) longPressGestureRecognizer {

I want to call this method from my swift file.So I did like this.

var longPressGuestureRecognizer = UILongPressGestureRecognizer(target: metrixUIViewController, action: #selector(metrixUIViewController.onLongPress(longPressGestureRecognizer:)))

But it says MetrixUIViewController has no member onLongPress.
How can I solve this? Please help me.

Body:
First check your bridging header is it correct?

Your onLongPress method will be public. should be declared in .h
 and .m file

Change at below

var longPressGuestureRecognizer = UILongPressGestureRecognizer(target: metrixUIViewController, action: #selector(metrixUIViewController.onLongPress(_:)))


问:
JSON URL specific item to DIV
```<code><html>
<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: todos1
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

```<code><div id="3rd_title_here">fugiat veniam minus</div>
</code>```

to any ones curiousity this is what the JSON structure looks like if u view the URL link

```<code>{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}
</code>```

答:
The data you're getting is an array of todos, to get the third element in the array you have to use it's index which is 2.  </p>

<p>You can achieve that by doing something like this.  </p>

```<code><html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
</script>

<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: function(data) {
          $('#3rd_title_here').html(data[2].title);
        }
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

Title: JSON URL specific item to DIV

Body:
how do i display the 3rd title on the json url to the div

the title on the 3rd row is "fugiat veniam minus"

i want it to have like this when i execute the html

fugiat veniam minus

to any ones curiousity this is what the JSON structure looks like if u view the URL link

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
{
"userId": 1,
"id": 4,
"title": "et porro tempora",
"completed": true
}

Body:
The data you're getting is an array of todos, to get the third element in the array you have to use it's index which is 2.

You can achieve that by doing something like this.

<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
</script>

<script>
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
    $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: function(data) {
          $('#3rd_title_here').html(data[2].title);
        }
    });
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>


问:
Not possible to break/split div into two divs?
Trying a way to split a div into two divs at a certain point by inserting end tag and start tag but javascript seems to adjust for this and switch the order of the tags...is there any other way?

https://jsfiddle.net/dn55u8rx/5/

```<code>$(".inner").before('ENDPAGE</div><div class="page">');
</code>```

答:
Would this be a good solution for you?

$(".inner").html('
1

2
');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="border:1px solid red">
<div class="page"  style="border:1px solid blue">
TEST
<div class="inner"  style="border:1px solid green">
TEST2
</div>
TEST3
</div>
</div></code>```

Body:
Trying a way to split a div into two divs at a certain point by inserting end tag and start tag but javascript seems to adjust for this and switch the order of the tags...is there any other way?

https://jsfiddle.net/dn55u8rx/5/

$(".inner").before('ENDPAGE

');

Body:
Would this be a good solution for you?

$(".inner").html('<div class="page" style="border:1px solid yellow">1</div><div class="page" style="border:1px solid yellow">2</div>');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer" style="border:1px solid red">
<div class="page"  style="border:1px solid blue">
TEST
<div class="inner"  style="border:1px solid green">
TEST2
</div>
TEST3
</div>
</div>


答:
```<code>function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
   var todos1 = $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: function(data){
        return data;

}});
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>
</code>```

then you do:

```<code> $("#3rd_title_here").html(todos1);
</code>```

Title: JSON URL specific item to DIV

Body:
function gettodo()
{
    var TODOS ='https://jsonplaceholder.typicode.com/todos';
   var todos1 = $.ajax({
        cache: false,
        dataType: "json",
        url: TODOS,
        success: function(data){
        return data;

}});
}
setInterval(gettodo(),1000);
</script>

<div id="3rd_title_here"></div>
</html>

then you do:

 $("#3rd_title_here").html(todos1);


答: onLongPress must be written in .m File not declared in .h please declare.

Title: UIViewController has no member 'method'


问:
Mule deployment issue
I'm getting the following error while deploying the interface

org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid
  content was found starting with element 'sfdc:query-single'.  One of
  '{"http://www.mulesoft.org/schema/mule/core":annotations,
  "http://www.mulesoft.org/schema/mule/core":abstract-message-processor,
  "http://www.mulesoft.org/schema/mule/core":abstract-outbound-endpoint,
  "http://www.mulesoft.org/schema/mule/core":abstract-mixed-content-message-processor}'
  is expected.

I have configured the salesforce connector globally.

```<code>PFB schema
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/wmq http://www.mulesoft.org/schema/mule/ee/wmq/current/mule-wmq-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">
</code>```

答:
Try to add dependency in Mule like below and rerun the application using maven with mule</p>

```<code><dependency>
    <groupId>org.mule.modules</groupId>
    <artifactId>mule-module-sfdc</artifactId>
    <version>RELEASE</version>
</dependency>
</code>```

Title: Mule deployment issue

Body:
I'm getting the following error while deploying the interface

org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid
  content was found starting with element 'sfdc:query-single'.  One of
  '{"http://www.mulesoft.org/schema/mule/core":annotations,
  "http://www.mulesoft.org/schema/mule/core":abstract-message-processor,
  "http://www.mulesoft.org/schema/mule/core":abstract-outbound-endpoint,
  "http://www.mulesoft.org/schema/mule/core":abstract-mixed-content-message-processor}'
  is expected.

I have configured the salesforce connector globally.

PFB schema
xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/wmq http://www.mulesoft.org/schema/mule/ee/wmq/current/mule-wmq-ee.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd">

Body:
Try to add dependency in Mule like below and rerun the application using maven with mule

<dependency>
    <groupId>org.mule.modules</groupId>
    <artifactId>mule-module-sfdc</artifactId>
    <version>RELEASE</version>
</dependency>


问:
Why do nullable numbers not preserve identity?
In kotlin nullable values are not preserving identity but equality:

```<code>val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'
</code>```

Why is this different ?

答:
This is explained in the documentation right next to this code sample:

Note that boxing of numbers does not necessarily preserve identity

Basically, using the nullable Int? type forces the compiler to use the boxed Integer type for those variables in the generated bytecode instead of the primitive int. So the code sample translates to this Java code:

```<code>int a = 10000;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
System.out.print(boxedA == anotherBoxedA);
</code>```

This, of course, prints false, since two different Integer instances have been created by the two Integer.valueOf calls. Thought the JVM has caching for the instances created by Integer.valueOf calls, it only works between -128 and 127 - if you run the code with a having a value in that range, both comparisons will indeed return true.

ContentLicense: CC BY-SA 4.0

Body:
In kotlin nullable values are not preserving identity but equality:

val a: Int = 10000
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
print(boxedA == anotherBoxedA) // Prints 'true'

Why is this different ?

Body:
This is explained in the documentation right next to this code sample:

Note that boxing of numbers does not necessarily preserve identity

Basically, using the nullable Int? type forces the compiler to use the boxed Integer type for those variables in the generated bytecode instead of the primitive int. So the code sample translates to this Java code:

int a = 10000;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
System.out.print(boxedA == anotherBoxedA);

This, of course, prints false, since two different Integer instances have been created by the two Integer.valueOf calls. Thought the JVM has caching for the instances created by Integer.valueOf calls, it only works between -128 and 127 - if you run the code with a having a value in that range, both comparisons will indeed return true.


问:
Java, Arrays, Methods
The below method calls are giving error while compilation. I'm unable to understand why is it so. I'm passing the same parameters as defined in the method. Kindly help.

ms_div( B[mid_i], mid_i );
ms_div( C[mid_j], mid_j );

Code Starts Below:

```<code>void ms_div(int[] A, int nbr)
        {
            if (nbr > 2)
            {
                int mid_i = A.length / 2;
                int mid_j = A.length - mid_i;
                int[] B = new int[13];
                int[] C = new int[13];

                //create left hand array
                for(int i;i<=mid_i - 1;i++)
                {
                    B[i] = A[i];
                }

                //creating right hand array
                for(int i = 0,j=mid_i;i>= mid_j - 1;i++,j++)
                {
                    C[i] = A[j];
                }

                //Sort Left Hand Array
                if (mid_i >= 2)
                {
                    ms_div( B[mid_i], mid_i );
                }

                //Sort Right Hand Array
                {
                    ms_div( C[mid_j],mid_j );
                }
            }
    }
</code>```

答:
In sort Left Hand Array and sort Right Hand Array, you have to change int value to array. you should use like

```<code>ms_div( B, mid_i );
</code>```

and

```<code>ms_div( C, mid_i );
</code>```

Title: Java, Arrays, Methods

Body:
The below method calls are giving error while compilation. I'm unable to understand why is it so. I'm passing the same parameters as defined in the method. Kindly help.

ms_div( B[mid_i], mid_i );
ms_div( C[mid_j], mid_j );

Code Starts Below:

void ms_div(int[] A, int nbr)
        {
            if (nbr > 2)
            {
                int mid_i = A.length / 2;
                int mid_j = A.length - mid_i;
                int[] B = new int[13];
                int[] C = new int[13];

                //create left hand array
                for(int i;i<=mid_i - 1;i++)
                {
                    B[i] = A[i];
                }

                //creating right hand array
                for(int i = 0,j=mid_i;i>= mid_j - 1;i++,j++)
                {
                    C[i] = A[j];
                }

                //Sort Left Hand Array
                if (mid_i >= 2)
                {
                    ms_div( B[mid_i], mid_i );
                }

                //Sort Right Hand Array
                {
                    ms_div( C[mid_j],mid_j );
                }
            }
    }

Body:
In sort Left Hand Array and sort Right Hand Array, you have to change int value to array. you should use like

ms_div( B, mid_i );

and

ms_div( C, mid_i );


问:
Removing array of arrays for certain inner values in PHP
Having this kind of array:

```<code>Array (
   [0] => Array (
        [0] => Array (
              [title] => "Test string"
              [lat] => "40.4211"
              [long] => "-3.70118"
              )
         )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
        [0] => Array (
              [title] => "Test string 6"
              [lat] => "11.1"
              [long] => "7.7"
              )
         )
)
</code>```

How can I get rid of that array of arrays for all the inner arrays that have length = 1?

My desired output would be:

```<code>Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
   )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
    )
    [2] => Array (
          [title] => "Test string 6"
          [lat] => "11.1"
          [long] => "7.7"
     )
)
</code>```

Thanks in advance.

PS: I'm using PHP 5.3

答:
Transform each value, if it has length 1 return its first child, else return the entire thing unchanged:</p>

```<code>$arr = array_map(function ($a) { return count($a) == 1 ? $a[0] : $a; }, $arr);
</code>```

Body:
Having this kind of array:

Array (
   [0] => Array (
        [0] => Array (
              [title] => "Test string"
              [lat] => "40.4211"
              [long] => "-3.70118"
              )
         )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
        [0] => Array (
              [title] => "Test string 6"
              [lat] => "11.1"
              [long] => "7.7"
              )
         )
)

How can I get rid of that array of arrays for all the inner arrays that have length = 1?

My desired output would be:

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
   )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
    )
    [2] => Array (
          [title] => "Test string 6"
          [lat] => "11.1"
          [long] => "7.7"
     )
)

Thanks in advance.

PS: I'm using PHP 5.3

Body:
Transform each value, if it has length 1 return its first child, else return the entire thing unchanged:

$arr = array_map(function ($a) { return count($a) == 1 ? $a[0] : $a; }, $arr);


问:
How do I get BitBucket.org commits to trigger TeamCity builds?
How does one configure webhooks in BitBucket.org to trigger TeamCity builds?</p>

答:
Use the TeamCity REST API:

Create a user on your TeamCity server with Run build permission

Create a new webhook on BitBucket to the prepared URL

```<code>http://username:password@teamcity.server.address/httpAuth/app/rest/vcs-root-instances/commitHookNotification?locator=vcsRoot:(type:jetbrains.git,count:99999),property:(name:url,value:bitbucket.org/bitbucketusername/repo.git,matchType:contains),count:99999
</code>```

Replace username,password with the user you just created

Replace teamcity.server.address, bitbucketusername and repo with your repo values,

See docs for more information:

https://confluence.jetbrains.com/display/TCD10/REST+API#RESTAPI-VCSrootinstancelocator

https://confluence.jetbrains.com/display/TCD10/Accessing+Server+by+HTTP

Body:
Use the TeamCity REST API:

Create a user on your TeamCity server with Run build permission

Create a new webhook on BitBucket to the prepared URL

http://username:password@teamcity.server.address/httpAuth/app/rest/vcs-root-instances/commitHookNotification?locator=vcsRoot:(type:jetbrains.git,count:99999),property:(name:url,value:bitbucket.org/bitbucketusername/repo.git,matchType:contains),count:99999

Replace username,password with the user you just created

Replace teamcity.server.address, bitbucketusername and repo with your repo values,

See docs for more information:

https://confluence.jetbrains.com/display/TCD10/REST+API#RESTAPI-VCSrootinstancelocator

https://confluence.jetbrains.com/display/TCD10/Accessing+Server+by+HTTP


问:
Convert Java project into Installation file
I'm working under a java desktop application project. I completed my java project using eclipse and it has many packages and class files in separate packages. My main class is Mainframe. My problem is I have to install this project into another computer, how can I convert my project to installation file? </p>

答: You can use Launch4j (http://launch4j.sourceforge.net/) to be able to create executable files (.exe) from Java projects.</p>


答:
You can do it like below:-

```<code>foreach($array as $key=>$value){
  if(is_array($value) && count($value) ==1){
    $array[$key] = $value[0];
  }
}
</code>```

Output:- https://eval.in/912263

Or you can use Passing by Reference mechanism also:-

```<code>foreach($array as &$value){
  if(is_array($value) && count($value) ==1){
    $value = $value[0];
  }
}
</code>```

Output:- https://eval.in/912264

Reference:- Passing by Reference

Title: Removing array of arrays for certain inner values in PHP

Body:
You can do it like below:-

foreach($array as $key=>$value){
  if(is_array($value) && count($value) ==1){
    $array[$key] = $value[0];
  }
}

Output:- https://eval.in/912263

Or you can use Passing by Reference mechanism also:-

foreach($array as &$value){
  if(is_array($value) && count($value) ==1){
    $value = $value[0];
  }
}

Output:- https://eval.in/912264

Reference:- Passing by Reference


问:
How to get the Glue code/Step definition file generated automatically in cucumber?
I am completely new to this automation. I know there's something like "Right Click on feature file and skeleton of the step definition file for the feature file would be generated automatically in the console". I am trying to achieve that.

My project is a maven project and its POM entries are :

```<code>cucumber-junit - 1.2.4
cucumber-core - 1.2.4
cucumber-java - 1.2.4
cucumber-jvm-deps - 1.0.3
cucumber-html-0.2.3
gherkin - 2.12.2
junit - 4.11
selenium-java - 2.53.1
selenium-server - 2.41.0
</code>```

And I have installed Cucumber 0.0.15N plugin in my eclipse - Neon.

Besides I installed all the above, I dont even get the Cucumber editor for feature file(Still opening in a notepad) and I dont see "Cucumber Feature" after I click "Run as".

答: Build your project from a command line, you will get snippet suggestions when Cucumber can't find any matching steps. Use these suggestions as a basis for implementing your steps in code.</p>

Body:
I am completely new to this automation. I know there's something like "Right Click on feature file and skeleton of the step definition file for the feature file would be generated automatically in the console". I am trying to achieve that.

My project is a maven project and its POM entries are :

cucumber-junit - 1.2.4
cucumber-core - 1.2.4
cucumber-java - 1.2.4
cucumber-jvm-deps - 1.0.3
cucumber-html-0.2.3
gherkin - 2.12.2
junit - 4.11
selenium-java - 2.53.1
selenium-server - 2.41.0

And I have installed Cucumber 0.0.15N plugin in my eclipse - Neon.

Besides I installed all the above, I dont even get the Cucumber editor for feature file(Still opening in a notepad) and I dont see "Cucumber Feature" after I click "Run as".


问:
Python convention: function constructor for a private class
I have noticed this in Python's threading module source:

```<code>def Event(*args, **kwargs):
  return _Event(*args, **kwargs)

class _Event(_Verbose):
  ...
</code>```

Am I correct in assuming this is an attempt in mimicking a "sealed" class (c#) or a "final" class (java) in other languages? Is this a common pattern in Python? Are there any other approaches to this problem in Python?

答:
I don't think I like this choice of identifiers. It is conventional to start class names with an uppercase letter, so you'd think that you could say isinstance(x, Event), but you can't. I think a name such as make_event that unambiguously identifies the function as a function would have been better.

This issue has already been discussed on the mailing list, where the BDFL states:

This started out as an experiment in API
  design, where I tried to make things look as much like the similar
  Java API as possible (I didn't want to invent yet anotherwobbly
  wheel). I specifically wanted these not to be classes so that people
  wouldn't start subclassing them. At the time PEP-8 wasn't well
  established (if at all) and I wanted the factory functions to look
  like classes. I think in 2.7 / 3.1 we can change the factory functions
  to conform to PEP-8 (leaving the old names in for a couple of
  release).

The change he mentioned hasn't been done yet, but I think it's pretty safe to say that nowadays the naming scheme is seen as misguided and should not be proliferated.

You're right when you say that these factory functions were introduced to mimic a sealed class. The BDFL says

Allowing them to be subclassed makes it harder to replace them on some
  platforms with equivalent but faster implementations.

I don't think this scheme is too common. Most of the time, there is no incentive to replace classes with equivalent implementations, and if a class is not designed for subclassing, you can mention that in the documentation.

ContentLicense: CC BY-SA 2.5

Body:
I have noticed this in Python's threading module source:

def Event(*args, **kwargs):
  return _Event(*args, **kwargs)

class _Event(_Verbose):
  ...

Am I correct in assuming this is an attempt in mimicking a "sealed" class (c#) or a "final" class (java) in other languages? Is this a common pattern in Python? Are there any other approaches to this problem in Python?


问:
Sort products by DESC order in Woocommerce
I wrote this code in functions.php file of my active theme:

```<code>    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}
</code>```

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?

答:
You can use a custom function hooked in woocommerce_product_query action hook this way:

```<code>add_action( 'woocommerce_product_query', 'default_catalog_ordering_desc', 10, 2 );
function default_catalog_ordering_desc( $q, $query ){
    if( $q->get( 'orderby' ) == 'menu_order title' )
        $q->set( 'order', 'DESC' );
}
</code>```

Code goes in functions.php file of your active child theme (or active theme) or in any plugin file.

Tested and works.

Body:
I wrote this code in functions.php file of my active theme:

    add_filter( 'woocommerce_get_catalog_ordering_args',
    'custom_woocommerce_get_catalog_ordering_args' );
    function custom_woocommerce_get_catalog_ordering_args( $args ) {
     $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'date';
        $args['order'] = 'desc';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'DESC SORT';
    return $sortby;
}

I am trying to sort products by Desc, but products still sorting by default (ASC).

How can I sort them by DESC?

Body:
You can use a custom function hooked in woocommerce_product_query action hook this way:

add_action( 'woocommerce_product_query', 'default_catalog_ordering_desc', 10, 2 );
function default_catalog_ordering_desc( $q, $query ){
    if( $q->get( 'orderby' ) == 'menu_order title' )
        $q->set( 'order', 'DESC' );
}

Code goes in functions.php file of your active child theme (or active theme) or in any plugin file.

Tested and works.


问:
Nodejs once every eight hours
I am trying to impliment into my nodejs script a function to allow once per 8 hours a select command.

example:

!hug <--- would let bot respond with a hug but only once every 8 hours

I've been scouring online but cannot find what I need... I am trying to get it as simplified as possible.. (i.e without mongo... etc)

答:
You can use node-cron</p>

```<code>var CronJob = require('cron').CronJob;
var job = new CronJob('00 30 11 * * 1-5', function() {
  /*
   * Runs every weekday (Monday through Friday)
   * at 11:30:00 AM. It does not run on Saturday
   * or Sunday.
   */
  }, function () {
    /* This function is executed when the job stops */
  },
  true, /* Start the job right now */
  timeZone /* Time zone of this job. */
);
</code>```

Title: Nodejs once every eight hours

Body:
You can use node-cron

var CronJob = require('cron').CronJob;
var job = new CronJob('00 30 11 * * 1-5', function() {
  /*
   * Runs every weekday (Monday through Friday)
   * at 11:30:00 AM. It does not run on Saturday
   * or Sunday.
   */
  }, function () {
    /* This function is executed when the job stops */
  },
  true, /* Start the job right now */
  timeZone /* Time zone of this job. */
);


问:
Element-wise multi-dimension array index in Tensorflow
I am learning tensorflow, I know in numpy I can do

a = np.random.randn(1,2,3)
a[a<0.5] = -1

How can I do the same in tensorflow? Thank you!

Body:
Make use of tf.less and tf.where.

t1 = tf.Variable(np.random.randn(1,2,3), dtype = tf.float32)
t2 = tf.less(t1, 0.5)
t3 = tf.where(t2, tf.fill((1,2,3), -1.0), t1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(t1))
    print(sess.run(t3))

Output:

[[[-2.36796331 -0.29641244  1.46340346]
  [-0.38756183 -0.39763084 -0.34627825]]]

[[[-1.         -1.          1.46340346]
  [-1.         -1.         -1.        ]]]


答:
Assuming 2D arrays remain as is</p>

```<code>foreach ($array as $key => $value) {      // Loop to result array
    if (count($value) <= 1) {           // Checks if array count is less than or equal to 1
        $array[$key] = reset($value);  // Reset to reduce from 2d array to 1d
    }
}

print_r($array);
</code>```

Body:
Assuming 2D arrays remain as is

foreach ($array as $key => $value) {      // Loop to result array
    if (count($value) <= 1) {           // Checks if array count is less than or equal to 1
        $array[$key] = reset($value);  // Reset to reduce from 2d array to 1d
    }
}

print_r($array);


问:
Using Javascript in CSS
Is it possible to use Javascript inside CSS?

If it is, can you give a simple example?

答:
IE supports CSS expressions:

```<code>width:expression(document.body.clientWidth > 955 ? "955px": "100%" );
</code>```

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

OwnerDisplayName: HelpMe

Title: Using Javascript in CSS

Body:
IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

OwnerDisplayName: jetxee


问:
Best practices in unit-test writing
I have a "best practices" question. I'm writing a test for a certain method, but there are multiple entry values. Should I write one test for each entry value or should I change the entryValues variable value, and call the .assert() method (doing it for all range of possible values)?

Thank you for your help.
Best regards,

Pedro Magueija

edited: I'm using .NET. Visual Studio 2010 with VB.

答:
Smaller tests are easier to read.

The name is part of the documentation of the test.

Separate methods give a more precise indication of what has failed.

So if you have a single method like:

```<code>void testAll() {
  // setup1
  assert()
  // setup2
  assert()
  // setup3
  assert()
}
</code>```

In my experience this gets very big very quickly, and so becomes hard to read and understand, so I would do:

```<code>void testDivideByZero() {
  // setup
  assert()
}

void testUnderflow() {
  // setup
  assert()
}

void testOverflow() {
  // setup
  assert()
}
</code>```

Title: Best practices in unit-test writing

Body:
Smaller tests are easier to read.

The name is part of the documentation of the test.

Separate methods give a more precise indication of what has failed.

So if you have a single method like:

void testAll() {
  // setup1
  assert()
  // setup2
  assert()
  // setup3
  assert()
}

In my experience this gets very big very quickly, and so becomes hard to read and understand, so I would do:

void testDivideByZero() {
  // setup
  assert()
}

void testUnderflow() {
  // setup
  assert()
}

void testOverflow() {
  // setup
  assert()
}


问:
python dictionary for incremental values
I would like to perform the following:
Given a total number of observations (in this case the variable 'total_models'), I would like to parse this for parallel processing by a given number of python sessions ('sessions' variable and 'by' variable).  I figure it best to perform this task using a dictionary.

The desired results should can be found in the 'obs_dict' object.  For any given input to 'total_models', 'sessions' and 'by'.  Can you assist in creating the desired output in a dictionary object?  If possible, I would like to see the answer using some sort of list or dictionary comprehension.

```<code>total_models=1000000
sessions=4
by=int(total_models/sessions)

### Desired Output.
obs_dict={1:'0:250000',2:'250001:500000',3:'500001:750000',4:'750001:1000000'}
</code>```

答:
```<code>obs = {i+1: str(i*by+1)+':'+str((i+1)*by) for i in range(sessions)}
</code>```

Edited, Kyle:

For the odd models it would seem wrapping a ceil the division will ensure we we do not go over the 'total_models'

```<code>total_models=1000326
sessions=5
by=math.ceil(total_models/sessions)
obs = {i+1: str(i*by+1)+':'+str(min((i+1)*by,total_models)) for i in range(sessions)}
</code>```

Body:
I would like to perform the following:
Given a total number of observations (in this case the variable 'total_models'), I would like to parse this for parallel processing by a given number of python sessions ('sessions' variable and 'by' variable).  I figure it best to perform this task using a dictionary.

The desired results should can be found in the 'obs_dict' object.  For any given input to 'total_models', 'sessions' and 'by'.  Can you assist in creating the desired output in a dictionary object?  If possible, I would like to see the answer using some sort of list or dictionary comprehension.

total_models=1000000
sessions=4
by=int(total_models/sessions)

### Desired Output.
obs_dict={1:'0:250000',2:'250001:500000',3:'500001:750000',4:'750001:1000000'}

Body:
obs = {i+1: str(i*by+1)+':'+str((i+1)*by) for i in range(sessions)}

Edited, Kyle:

For the odd models it would seem wrapping a ceil the division will ensure we we do not go over the 'total_models'

total_models=1000326
sessions=5
by=math.ceil(total_models/sessions)
obs = {i+1: str(i*by+1)+':'+str(min((i+1)*by,total_models)) for i in range(sessions)}


问:
net.iamyellow.gcmjs does not with SDK 6.3.0.GA for titanium appcelerator
We migrated to an old version(Ti 5.2.2).GA to a new version(Ti 6.3.0.GA) of titanium Appcelerator.

When we run our app with latest version(Ti 6.3.0.GA) the net.iamyellow.gcmjs (0.2 & 0.3) module not supported.

My app is depends on net.iamyellow.gcmjs module.

Questions

Is there any latest version of net.iamyellow.gcmjs module to support for titanium SDK Version 6.3.0.GA?

If it is not there when will you release the new version of net.iamyellow.gcmjs module?

Is there any push notification module to support for both android and iOS app which are developed through titanium appcelerator?

Please, can please help me out.

Environments:

```<code>Operating System          = Mac OS X

Node.js Version           = 6.10.3

npm Version               = 3.10.10

Titanium CLI Version      = 5.0.14

Titanium SDK Version      = 6.3.0.GA

Axway Appcelerator Studio = 4.10.0
</code>```

答:
For smaller modules like this one, you can update the module yourself to make it support a higher titanium SDK. In this case TheFuquan suggested an alternative module which hopefully fills your requirements, but for others where there might not be an alternative downloading the sourcecode from git and rebuilding the module for the newer sdk is usually pretty simple.

in this case i believe the only thing that needs to be changed is the "apiversion" to 3 in the manifest file of the module. Possibly the "architectures" property need to be updated in the manifest file aswell. Then you just build the module and you are good to go.

Body:
We migrated to an old version(Ti 5.2.2).GA to a new version(Ti 6.3.0.GA) of titanium Appcelerator.

When we run our app with latest version(Ti 6.3.0.GA) the net.iamyellow.gcmjs (0.2 & 0.3) module not supported.

My app is depends on net.iamyellow.gcmjs module.

Questions

Is there any latest version of net.iamyellow.gcmjs module to support for titanium SDK Version 6.3.0.GA?

If it is not there when will you release the new version of net.iamyellow.gcmjs module?

Is there any push notification module to support for both android and iOS app which are developed through titanium appcelerator?

Please, can please help me out.

Environments:

Operating System          = Mac OS X

Node.js Version           = 6.10.3

npm Version               = 3.10.10

Titanium CLI Version      = 5.0.14

Titanium SDK Version      = 6.3.0.GA

Axway Appcelerator Studio = 4.10.0


问:
combine blocks of code to one function
How can I make one function to do something like this</p>

```<code>$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});
</code>```

答:
I would bind one function to both selectors.

In the function, check which id is triggered.

The toggle the visibility by using toggle( expression ). Where expression checks if the the checkbox is checked (=show) or not (=hide).

$('#check_express,#check_standard').on('change', function(){
    if( this.id == 'check_express' ) {
        $('#form_express').toggle( $(this).is(':checked') );
    }
    else {
        $('#form_standard').toggle( $(this).is(':checked') );
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form { display: none; }</code>```

Check express: <input type="checkbox" id="check_express" />

Check standard: <input type="checkbox" id="check_standard" />

<form id="form_express">
  Form express
</form>
<form id="form_standard">
  Form standard
</form>```

Title: combine blocks of code to one function

Body:
How can I make one function to do something like this

$('#check_express').is(':checked') ? $('#form_express').show() : $('#form_express').hide();

$('#check_express').on('change', function(){
    $(this).is(':checked') ? $('#form_express').show() :
    $('#form_express').hide();
});

$('#check_standard').is(':checked') ? $('#form_standard').show() : $('#form_standard').hide();

$('#check_standard').on('change', function(){
    $(this).is(':checked') ? $('#form_standard').show() :
    $('#form_standard').hide();
});

Body:
I would bind one function to both selectors.

In the function, check which id is triggered.

The toggle the visibility by using toggle( expression ). Where expression checks if the the checkbox is checked (=show) or not (=hide).

$('#check_express,#check_standard').on('change', function(){
    if( this.id == 'check_express' ) {
        $('#form_express').toggle( $(this).is(':checked') );
    }
    else {
        $('#form_standard').toggle( $(this).is(':checked') );
    }
});

form { display: none; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check express: <input type="checkbox" id="check_express" /> <br />
Check standard: <input type="checkbox" id="check_standard" /> <br />

<form id="form_express">
  Form express
</form>
<form id="form_standard">
  Form standard
</form>


问:
Single sign-on in Java / VNC

Background

On the project I work on we have GUI applications running on several different servers. Due to their user interface similarities I am investigating combining their OMIs into a single unified interface. Currently these applications are all remotely viewable via VNC. I plan to take advantage of this by having the master display run several VNC viewers under the covers and wrap an interface around these VNC sessions to make them appear like native applications.

Problem

I am looking for pointers for architecting a single sign-on solution. I want to eliminate each application's individual login and instead have users login to the unified display only. When they do that they would then be automatically logged in to each of the individual apps.

Constraints

The applications are all Swing-based Java apps running on Linux.

Authentication is performed by a Windows 2003 Server machine with Active Directory.

I'd strongly prefer an off-the-shelf solution to a custom-built one.

Ideas

My investigation has pointed me towards Kerberos and GSSAPI. Kerberos's ticket-based mechanism seems well-suited to the task.

One tricky bit is that these applications are always running. I need the unified display to somehow "tell" them when the user has logged in. It's not like normal Kerberized programs where they will perform a Kerberos login at startup.

If I use Kerberos I'm not sure how to transfer tickets to the various application servers. Is there a standard way to transfer them? Do I just use "scp" or something? Or do I develop my own socket-based network protocol and have the Java programs connect to each other and transfer tickets that way?

I don't want to get too bogged down in the details, though. I'd appreciate even general ideas like "have you considered Technology X?" or "try XYZ instead of VNC, it does this for you."

Updates

I'll edit in answers and clarifications here...

Have you considered that some authentication must take place anyway and that VNC only exports the view to a running program, so a VNC session cannot transport tickets?

Yes, indeed. Java + VNC is what we have right now. I could change out VNC for something else if there's a better way to remotely view the apps. Without rewriting them, that is. The ideal solution would be to separate them into distinct client and server pieces and put all the GUI code into the client, but that's 5-star difficulty and I need 1- or 2-star.

Have you considered the case when two users log in the same time? Will they see the same app? Or will this be forbidden?

Yeah, I've considered that. They will either see the same app or it will be forbidden. Either solution is okay as far as this particular system goes, so this isn't a big deal.

Have you considered just using an X Server on your local host and export the clients applications windows?

Yeah, this would be great. Can this be done with already-running apps? I have to connect to these apps after they've already started. I can't start them on demand when somebody fires up the central viewer.

答:
Okey, I will try and start this list. Have you considered...

JAAS? Should include the GSS API, but was very cumbersome the last time I tried it.

that some authentication must take place anyway and that VNC only exports the view to a running program, so a VNC session cannot transport tickets?

a browser based solution with an embedded Java VNC client? At least the IE is able to carry out kerberos authentication, I don't know about the other browsers, or HOW the IE does that.

the case when two users log in the same time? Will they see the same app? Or will this be forbidden?

just using an X Server on your local host and export the clients applications windows?

EDIT: More considerations:

When using the X Server variant, use Xmove to move the programs to the X Server.

You can use SSH authentication with private/secret keys and let the user enter one passphrase to connect all your servers. SSH agent is the keyword.

With the existing SSH connections, start XMove on all the machines, collect all GUIs and send them to the client. You could even write a little MainWindow, with Buttons for each app, and when clicked, export only one of the apps, so it seems like they have been started from the main GUI.

Title: Single sign-on in Java / VNC


问:
Identity Server 4 with MVC Client That Requires Social Logins Only
We have a quite standard IdSrv4 configuration with a client that supports HybridAndClientCredentials grant flow (MVC web site):

```<code>public void ConfigureServices( IServiceCollection services ) {
    services.AddMvc();
    services.AddIdentityServer()
        .AddInMemoryClients(Clients.Get())
        .AddInMemoryIdentityResources(Resources.GetIdentityResources())
        .AddInMemoryApiResources(Resources.GetApiResources())
        .AddTestUsers(Users.Get())
        .AddDeveloperSigningCredential();

    services.AddAuthentication()
        .AddGoogle( "Google", options => {
            options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
            options.ClientId = "xxxxx.apps.googleusercontent.com";
            options.ClientSecret = "xxxxx";
        } );
        .AddFacebook(...)
}
</code>```

Multiple questions in regard to MVC client's configuration:

```<code>public void ConfigureServices( IServiceCollection services ) {

    services.AddMvc();
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication( options => {
        options.DefaultScheme = ??????;
        options.DefaultChallengeScheme = ??????;
        options.???
    } )
    .AddCookie()
    .??????
    ;
}
</code>```

What should be the sufficient configuration to utilize social authentication only?

答:
It looks like adding OpenIdConnect middleware will be sufficient for social vendor authentication scenarios.

I'm still trying to figure out what will be the best practice to manage addtitional claims given Cookie's limitations.

```<code> JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

 services.AddAuthentication( options => {
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
 } )
 .AddCookie()
 .AddOpenIdConnect( OpenIdConnectDefaults.AuthenticationScheme, options => {
      options.RequireHttpsMetadata = false; //-- change it for production

      options.GetClaimsFromUserInfoEndpoint = true;
      options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

      options.Authority = "http://localhost:5010";
      options.ClientId = "xxx";
      options.ClientSecret = "xxx.secret";

      options.ResponseType = "code id_token";
      options.SaveTokens = true;

      //options.Scope.Clear(); //-- requires more research
      options.Scope.Add( "xxx-api" );
      options.Scope.Add( "email" );
      options.Scope.Add( "offline_access" );

      options.TokenValidationParameters =
          new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" };

      //options.ClaimActions.MapUniqueJsonKey(); //-- requires more research
 } );
</code>```

Body:
We have a quite standard IdSrv4 configuration with a client that supports HybridAndClientCredentials grant flow (MVC web site):

public void ConfigureServices( IServiceCollection services ) {
    services.AddMvc();
    services.AddIdentityServer()
        .AddInMemoryClients(Clients.Get())
        .AddInMemoryIdentityResources(Resources.GetIdentityResources())
        .AddInMemoryApiResources(Resources.GetApiResources())
        .AddTestUsers(Users.Get())
        .AddDeveloperSigningCredential();

    services.AddAuthentication()
        .AddGoogle( "Google", options => {
            options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
            options.ClientId = "xxxxx.apps.googleusercontent.com";
            options.ClientSecret = "xxxxx";
        } );
        .AddFacebook(...)
}

Multiple questions in regard to MVC client's configuration:

public void ConfigureServices( IServiceCollection services ) {

    services.AddMvc();
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication( options => {
        options.DefaultScheme = ??????;
        options.DefaultChallengeScheme = ??????;
        options.???
    } )
    .AddCookie()
    .??????
    ;
}

What should be the sufficient configuration to utilize social authentication only?

Body:
It looks like adding OpenIdConnect middleware will be sufficient for social vendor authentication scenarios.

I'm still trying to figure out what will be the best practice to manage addtitional claims given Cookie's limitations.

 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

 services.AddAuthentication( options => {
     options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
 } )
 .AddCookie()
 .AddOpenIdConnect( OpenIdConnectDefaults.AuthenticationScheme, options => {
      options.RequireHttpsMetadata = false; //-- change it for production

      options.GetClaimsFromUserInfoEndpoint = true;
      options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

      options.Authority = "http://localhost:5010";
      options.ClientId = "xxx";
      options.ClientSecret = "xxx.secret";

      options.ResponseType = "code id_token";
      options.SaveTokens = true;

      //options.Scope.Clear(); //-- requires more research
      options.Scope.Add( "xxx-api" );
      options.Scope.Add( "email" );
      options.Scope.Add( "offline_access" );

      options.TokenValidationParameters =
          new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role" };

      //options.ClaimActions.MapUniqueJsonKey(); //-- requires more research
 } );


问:
How do I able to see the source code of this website www.samy.pl?
This website (www.samy.pl) uses some technique so that no one can inspect the code
(Ctrl+Shift+I) or view source (Ctrl+U). It can detect if you have opened the console or inspector the code automatically changes.

How this is possible?

答:
hahaha, this is a good one, you should not expect less from samy!

Now I see why people think it is the wrong answer (the source get replaced if you do otherwise)

1.Navigate to site with inspector open there you end up with "No source for you! You found easter egg #7."

2.and then check the source to find Easter egg #2:

```<code>view-source:https://samy.pl
</code>```

you will see:

```<code>/*
No source for you! Easter egg #2
*// AFTER SOME LONG WHITE SPACES HERE  /.source.replace(/.{7}/g,function(w){document.write(String.fromCharCode(parseInt(w.replace(/ /g,'0').replace(/   /g,'1'),2)))});
</code>```

This is the way he loads the site(by injecting js), by replacing two type of white spaces for 1 and 0 and parsing that to char code by some regex and then that to string of course :D

https://de.wikipedia.org/wiki/Whitespace_(Programmiersprache)

If you paste that part to a js console, you will get the tags that loads the page.

ps. to see the rendered source, just load the page normaly and hit F12 after disabling javascript.

Have fun!

Body:
hahaha, this is a good one, you should not expect less from samy!

Now I see why people think it is the wrong answer (the source get replaced if you do otherwise)

1.Navigate to site with inspector open there you end up with "No source for you! You found easter egg #7."

2.and then check the source to find Easter egg #2:

view-source:https://samy.pl

you will see:

/*
No source for you! Easter egg #2
*// AFTER SOME LONG WHITE SPACES HERE  /.source.replace(/.{7}/g,function(w){document.write(String.fromCharCode(parseInt(w.replace(/ /g,'0').replace(/   /g,'1'),2)))});

This is the way he loads the site(by injecting js), by replacing two type of white spaces for 1 and 0 and parsing that to char code by some regex and then that to string of course :D

https://de.wikipedia.org/wiki/Whitespace_(Programmiersprache)

If you paste that part to a js console, you will get the tags that loads the page.

ps. to see the rendered source, just load the page normaly and hit F12 after disabling javascript.

Have fun!


问:
Visible the table
My Output for this php is the table in database is retrieved in table of the page. Now , I would like to make the table in page become visible when click this php in browser, when i enter the name in text box, it will retrived the name with row. All I success, only the table visible havent done. Below is my code and the output i would like when open the php:

Now my output when open this php is the output i post below but got information in table. Now I would like make them become visible when I open this php and when i enter the name in text box and click search button, the row of table will display if it is match with name.

Php:

```<code><?php

if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `table` WHERE CONCAT(`id`,
`username`, `name`, `date`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);

}
else {
$query = "SELECT * FROM `table`";
$search_result = filterTable($query);
}

// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "wp");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>REWARD DATA SEARCH</title>
    <style>
        table,tr,th,td
        {
            border: 1px solid black;
        }
    </style>
</head>
<body>

    <form action="test.php" method="post">
        <input type="text" name="valueToSearch" placeholder="Enter Name"><br><br>
        <input type="submit" name="search" value="Search"><br><br>

        <table>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Item</th>
                <th>Date</th>
            </tr>

  <!-- populate table from mysql database -->
            <?php while($row = mysqli_fetch_array($search_result)):?>
            <tr>
                <td><?php echo $row['id'];?></td>
                <td><?php echo $row['username'];?></td>
                <td><?php echo $row['name'];?></td>
                <td><?php echo $row['date'];?></td>
            </tr>
            <?php endwhile;?>
        </table>
    </form>

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

Output I would like to do when open the php:

答:
```<code> <?php while($row = mysqli_fetch_array($search_result)):?>
        <tr>
            <td><?php echo $row['id'];?></td>
            <td><?php echo $row['username'];?></td>
            <td><?php echo $row['name'];?></td>
            <td><?php echo $row['date'];?></td>
        </tr>
 <?php endwhile;?>
</code>```

after this just place code

```<code> <?php if(empty($search_result)){ ?>
    <tr>
        <td colspan = '4' align='center'>Data not found.</td>
    </tr>
<?php } ?>
</code>```

This will load initial table with no data.

Title: Visible the table

Body:
My Output for this php is the table in database is retrieved in table of the page. Now , I would like to make the table in page become visible when click this php in browser, when i enter the name in text box, it will retrived the name with row. All I success, only the table visible havent done. Below is my code and the output i would like when open the php:

Now my output when open this php is the output i post below but got information in table. Now I would like make them become visible when I open this php and when i enter the name in text box and click search button, the row of table will display if it is match with name.

Php:

<?php

if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `table` WHERE CONCAT(`id`,
`username`, `name`, `date`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);

}
else {
$query = "SELECT * FROM `table`";
$search_result = filterTable($query);
}

// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "wp");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}

?>

<!DOCTYPE html>

    <title>REWARD DATA SEARCH</title>

    <form action="test.php" method="post">
        <input type="text" name="valueToSearch" placeholder="Enter Name">

        <input type="submit" name="search" value="Search">

                Id
                Name
                Item
                Date

            <?php while($row = mysqli_fetch_array($search_result)):?>

                <?php echo $row['id'];?>
                <?php echo $row['username'];?>
                <?php echo $row['name'];?>
                <?php echo $row['date'];?>

            <?php endwhile;?>

    </form>

Output I would like to do when open the php:

Body:
 <?php while($row = mysqli_fetch_array($search_result)):?>
        <tr>
            <td><?php echo $row['id'];?></td>
            <td><?php echo $row['username'];?></td>
            <td><?php echo $row['name'];?></td>
            <td><?php echo $row['date'];?></td>
        </tr>
 <?php endwhile;?>

after this just place code

 <?php if(empty($search_result)){ ?>
    <tr>
        <td colspan = '4' align='center'>Data not found.</td>
    </tr>
<?php } ?>

This will load initial table with no data.


问:
VBA to convert amount to words except for cents
I have the codes below, how can I edit this so the cents will remain numeric.

Instead of converting Cents to text, I want it to show Cent amount over 100 (10.21 > Ten Dollars & 21/100).

Example:
  $50.31 convert to Fifty Dollars & 31/100.
  $50.00  convert to Fifty Dollars Only
  $50.01  convert to Fifty Dollars & 1/100

(Sorry for bad english).

```<code>'Main function
Function SpellNumber(ByVal MyNumber)
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
    Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
              "00", 2))
    MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
    Temp = GetHundreds(Right(MyNumber, 3))
    If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
    If Len(MyNumber) > 3 Then
        MyNumber = Left(MyNumber, Len(MyNumber) - 3)
    Else
        MyNumber = ""
    End If
    Count = Count + 1
Loop

SpellNumber = Dollars & Cents
End Function

' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
    Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred and "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
    Result = Result & GetTens(Mid(MyNumber, 2))
Else
    Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = ""           ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then   ' If value between 10-19...
    Select Case Val(TensText)
        Case 10: Result = "Ten"
        Case 11: Result = "Eleven"
        Case 12: Result = "Twelve"
        Case 13: Result = "Thirteen"
        Case 14: Result = "Fourteen"
        Case 15: Result = "Fifteen"
        Case 16: Result = "Sixteen"
        Case 17: Result = "Seventeen"
        Case 18: Result = "Eighteen"
        Case 19: Result = "Nineteen"
        Case Else
    End Select
Else                                 ' If value between 20-99...
    Select Case Val(Left(TensText, 1))
        Case 2: Result = "Twenty "
        Case 3: Result = "Thirty "
        Case 4: Result = "Forty "
        Case 5: Result = "Fifty "
        Case 6: Result = "Sixty "
        Case 7: Result = "Seventy "
        Case 8: Result = "Eighty "
        Case 9: Result = "Ninety "
        Case Else
    End Select
    If GetDigit(Right(TensText, 1)) = "" Then
    Result = Result & GetDigit(Right(TensText, 1))   ' Retrieve ones place.
        Else
         Result = Result & "-" & GetDigit(Right(TensText, 1))
    End If
End If
GetTens = Result
End Function

' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
    Case 1: GetDigit = "One"
    Case 2: GetDigit = "Two"
    Case 3: GetDigit = "Three"
    Case 4: GetDigit = "Four"
    Case 5: GetDigit = "Five"
    Case 6: GetDigit = "Six"
    Case 7: GetDigit = "Seven"
    Case 8: GetDigit = "Eight"
    Case 9: GetDigit = "Nine"
    Case 0: GetDigit = ""
End Select
End Function
</code>```

答:
Change

```<code>Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
          "00", 2))
</code>```

to

```<code>Cents = " " & Mid(MyNumber, DecimalPlace + 1) & "/100"
</code>```

BTW, you should declare types of variables, like

```<code>Dim Dollars As String, Cents As String, Temp As String
</code>```

Body:
I have the codes below, how can I edit this so the cents will remain numeric.

Instead of converting Cents to text, I want it to show Cent amount over 100 (10.21 > Ten Dollars & 21/100).

Example:
  $50.31 convert to Fifty Dollars & 31/100.
  $50.00  convert to Fifty Dollars Only
  $50.01  convert to Fifty Dollars & 1/100

(Sorry for bad english).

'Main function
Function SpellNumber(ByVal MyNumber)
Dim Dollars, Cents, Temp
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert cents and set MyNumber to dollar amount.
If DecimalPlace > 0 Then
    Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
              "00", 2))
    MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
    Temp = GetHundreds(Right(MyNumber, 3))
    If Temp <> "" Then Dollars = Temp & Place(Count) & Dollars
    If Len(MyNumber) > 3 Then
        MyNumber = Left(MyNumber, Len(MyNumber) - 3)
    Else
        MyNumber = ""
    End If
    Count = Count + 1
Loop

SpellNumber = Dollars & Cents
End Function

' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
    Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred and "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
    Result = Result & GetTens(Mid(MyNumber, 2))
Else
    Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function

' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = ""           ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then   ' If value between 10-19...
    Select Case Val(TensText)
        Case 10: Result = "Ten"
        Case 11: Result = "Eleven"
        Case 12: Result = "Twelve"
        Case 13: Result = "Thirteen"
        Case 14: Result = "Fourteen"
        Case 15: Result = "Fifteen"
        Case 16: Result = "Sixteen"
        Case 17: Result = "Seventeen"
        Case 18: Result = "Eighteen"
        Case 19: Result = "Nineteen"
        Case Else
    End Select
Else                                 ' If value between 20-99...
    Select Case Val(Left(TensText, 1))
        Case 2: Result = "Twenty "
        Case 3: Result = "Thirty "
        Case 4: Result = "Forty "
        Case 5: Result = "Fifty "
        Case 6: Result = "Sixty "
        Case 7: Result = "Seventy "
        Case 8: Result = "Eighty "
        Case 9: Result = "Ninety "
        Case Else
    End Select
    If GetDigit(Right(TensText, 1)) = "" Then
    Result = Result & GetDigit(Right(TensText, 1))   ' Retrieve ones place.
        Else
         Result = Result & "-" & GetDigit(Right(TensText, 1))
    End If
End If
GetTens = Result
End Function

' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
    Case 1: GetDigit = "One"
    Case 2: GetDigit = "Two"
    Case 3: GetDigit = "Three"
    Case 4: GetDigit = "Four"
    Case 5: GetDigit = "Five"
    Case 6: GetDigit = "Six"
    Case 7: GetDigit = "Seven"
    Case 8: GetDigit = "Eight"
    Case 9: GetDigit = "Nine"
    Case 0: GetDigit = ""
End Select
End Function

Body:
Change

Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
          "00", 2))

to

Cents = " " & Mid(MyNumber, DecimalPlace + 1) & "/100"

BTW, you should declare types of variables, like

Dim Dollars As String, Cents As String, Temp As String


问:
How I need to configure PersistenceJPAConfig?
I have a class with config. And I have a method entityManagerFactory() that tagged like Bean.

```<code>@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
@EnableJpaRepositories
public class PersistenceJPAConfig {
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "java.entities" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/carpark?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCx`");
    dataSource.setUsername( "root" );
    dataSource.setPassword( "1111" );
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
    return new PersistenceExceptionTranslationPostProcessor();
}

public Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    return properties;
}
</code>```

}

And I have a service that use EntityManager. EntityManager tagged like @Autowired, and spring create EntityManager is null. Where I'm configured incorrectly. I need to entityManager with fields from method entityManagerFactory() (in  class PersistenceJPAConfig).

```<code>@Service
public class BusService {
@Autowired
private BusRepository busRepository;

@Autowired
private EntityManager entityManager;

public void getBus(){
    try{
       entityManager.getTransaction().begin();
       Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
       busRepository.save(query.getResultList());
       System.out.println(busRepository.toString());
   }finally {
       entityManager.getTransaction().commit();
   }
}
</code>```

}

my packages are located like this

thanks in advance

答:
You should use the `@PersistenceContext' annotation to inject the entity manager:

```<code>@Service
public class BusService {
@Autowired
private BusRepository busRepository;

@PersistenceContext
private EntityManager entityManager;

public void getBus(){
  try{
    entityManager.getTransaction().begin();
    Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
   busRepository.save(query.getResultList());
   System.out.println(busRepository.toString());
  } finally {
    entityManager.getTransaction().commit();
  }
}
</code>```

there are several reasons to do that, you can get an overview here

and update you configuration class with the @ComponentScan annotation

```<code>@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
@EnableJpaRepositories
@ComponentScan(basePackages = {
    "model.service"})
public class PersistenceJPAConfig {

   ....

   @Bean
   public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new
     LocalContainerEntityManagerFactoryBean();
     em.setDataSource(dataSource());
     em.setPackagesToScan(new String[] { "model.entities" });

     JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
     em.setJpaVendorAdapter(vendorAdapter);
     em.setJpaProperties(additionalProperties());
     return em;
   }

....
</code>```

Body:
I have a class with config. And I have a method entityManagerFactory() that tagged like Bean.

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
@EnableJpaRepositories
public class PersistenceJPAConfig {
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "java.entities" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/carpark?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCx`");
    dataSource.setUsername( "root" );
    dataSource.setPassword( "1111" );
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
    return new PersistenceExceptionTranslationPostProcessor();
}

public Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    return properties;
}

}

And I have a service that use EntityManager. EntityManager tagged like @Autowired, and spring create EntityManager is null. Where I'm configured incorrectly. I need to entityManager with fields from method entityManagerFactory() (in  class PersistenceJPAConfig).

@Service
public class BusService {
@Autowired
private BusRepository busRepository;

@Autowired
private EntityManager entityManager;

public void getBus(){
    try{
       entityManager.getTransaction().begin();
       Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
       busRepository.save(query.getResultList());
       System.out.println(busRepository.toString());
   }finally {
       entityManager.getTransaction().commit();
   }
}

}

my packages are located like this

thanks in advance

Body:
You should use the `@PersistenceContext' annotation to inject the entity manager:

@Service
public class BusService {
@Autowired
private BusRepository busRepository;

@PersistenceContext
private EntityManager entityManager;

public void getBus(){
  try{
    entityManager.getTransaction().begin();
    Query query = entityManager.createNativeQuery("SELECT ID, NUMBER , Rote_ID FROM bus", Bus.class);
   busRepository.save(query.getResultList());
   System.out.println(busRepository.toString());
  } finally {
    entityManager.getTransaction().commit();
  }
}

there are several reasons to do that, you can get an overview here

and update you configuration class with the @ComponentScan annotation

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:hibernate.properties" })
@EnableJpaRepositories
@ComponentScan(basePackages = {
    "model.service"})
public class PersistenceJPAConfig {

   ....

   @Bean
   public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new
     LocalContainerEntityManagerFactoryBean();
     em.setDataSource(dataSource());
     em.setPackagesToScan(new String[] { "model.entities" });

     JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
     em.setJpaVendorAdapter(vendorAdapter);
     em.setJpaProperties(additionalProperties());
     return em;
   }

....


问:
combining columns so words become column value v column value
I am wanting to get df1 to combine AA, AB and v which is added through df3["C"] = "v".

df1

```<code>    AA   AB        AC      AD     AE
0  fry  pan  calendar  cakery  chock
1    a  pan  calendar  cakery  chock
2  fry  pan  calendar  cakery  chock
3    a  pan  calendar  cakery  chock
</code>```

Wanting for df3:

```<code>    AA   AB        AC      AD     AE   AF
0  fry  pan  calendar  cakery  chock   fry v pan
1    a  pan  calendar  cakery  chock   a v pan
2  fry  pav  calendar  cakery  chock   fry v pav
3    a  pan  calendar  cakery  chock   a v pab
</code>```

KeyError:

```<code>('C', 'occurred at index 0')
</code>```

In:

```<code>df3["C"] = np.nan
df3["C"] = "v"
AAAAAH = df1['combined']=df1.apply(lambda x:'%s_%s_%s' % (x['AA'],x['C'],x['AB']),axis=1)
df3['AB']=AAAAAH
</code>```

答:
You can combine columns without apply:

```<code>df['new'] = df['AA'] + ' v ' + df['AB']
print (df)

    AA   AB        AC      AD     AE        new
0  fry  pan  calendar  cakery  chock  fry v pan
1    a  pan  calendar  cakery  chock    a v pan
2  fry  pan  calendar  cakery  chock  fry v pan
3    a  pan  calendar  cakery  chock    a v pan
</code>```

Or if need assign to AB column:

```<code>df['AB'] = df['AA'] + ' v ' + df['AB']
print (df)
    AA         AB        AC      AD     AE
0  fry  fry v pan  calendar  cakery  chock
1    a    a v pan  calendar  cakery  chock
2  fry  fry v pan  calendar  cakery  chock
3    a    a v pan  calendar  cakery  chock
</code>```

Body:
I am wanting to get df1 to combine AA, AB and v which is added through df3["C"] = "v".

df1

    AA   AB        AC      AD     AE
0  fry  pan  calendar  cakery  chock
1    a  pan  calendar  cakery  chock
2  fry  pan  calendar  cakery  chock
3    a  pan  calendar  cakery  chock

Wanting for df3:

    AA   AB        AC      AD     AE   AF
0  fry  pan  calendar  cakery  chock   fry v pan
1    a  pan  calendar  cakery  chock   a v pan
2  fry  pav  calendar  cakery  chock   fry v pav
3    a  pan  calendar  cakery  chock   a v pab

KeyError:

('C', 'occurred at index 0')

In:

df3["C"] = np.nan
df3["C"] = "v"
AAAAAH = df1['combined']=df1.apply(lambda x:'%s_%s_%s' % (x['AA'],x['C'],x['AB']),axis=1)
df3['AB']=AAAAAH

Body:
You can combine columns without apply:

df['new'] = df['AA'] + ' v ' + df['AB']
print (df)

    AA   AB        AC      AD     AE        new
0  fry  pan  calendar  cakery  chock  fry v pan
1    a  pan  calendar  cakery  chock    a v pan
2  fry  pan  calendar  cakery  chock  fry v pan
3    a  pan  calendar  cakery  chock    a v pan

Or if need assign to AB column:

df['AB'] = df['AA'] + ' v ' + df['AB']
print (df)
    AA         AB        AC      AD     AE
0  fry  fry v pan  calendar  cakery  chock
1    a    a v pan  calendar  cakery  chock
2  fry  fry v pan  calendar  cakery  chock
3    a    a v pan  calendar  cakery  chock


问:
How to use gwt bootstrap datetimepicker
I can't understand how to use the bootstrap widget datetimepicker in my gwt java web application. I've found a lot of examples but all about html usage. I just know that I have to declare a Datetimepicker variable, but how about the usage? Thanks.
Finally I found that I needed this jar file:
https://mvnrepository.com/artifact/org.gwtbootstrap3/gwtbootstrap3-extras/0.9.4
Now I can declare my

```<code>DateTimePicker datePicker = new DateTimePicker();
</code>```

but how about the positioning and the capture of the date and time fired by the user's click?
Thanks

答:
Are you using GWT Bootstrap 3 ?

https://gwtbootstrap3.github.io/gwtbootstrap3-demo/#datePicker

Or in java code :

```<code>private DatePicker datePicker = new DatePicker();
datePicker.setValue(new Date());
div.add(datePicker);
</code>```

To add a handler

```<code>datePicker.addValidationChangedHandler
</code>```

To position the datepicker you can just put probably want to use bootstrap Grid system.

When you are just starting with GWT/Bootstrap, I strongly advice you to buy a small book about bootstrap 3. So that you know the basics of bootstrap without GWT.
After this, go back to GWT and apply your new knowledge.

Title: How to use gwt bootstrap datetimepicker

Body:
I can't understand how to use the bootstrap widget datetimepicker in my gwt java web application. I've found a lot of examples but all about html usage. I just know that I have to declare a Datetimepicker variable, but how about the usage? Thanks.
Finally I found that I needed this jar file:
https://mvnrepository.com/artifact/org.gwtbootstrap3/gwtbootstrap3-extras/0.9.4
Now I can declare my

DateTimePicker datePicker = new DateTimePicker();

but how about the positioning and the capture of the date and time fired by the user's click?
Thanks

Body:
Are you using GWT Bootstrap 3 ?

https://gwtbootstrap3.github.io/gwtbootstrap3-demo/#datePicker

Or in java code :

private DatePicker datePicker = new DatePicker();
datePicker.setValue(new Date());
div.add(datePicker);

To add a handler

datePicker.addValidationChangedHandler

To position the datepicker you can just put probably want to use bootstrap Grid system.

When you are just starting with GWT/Bootstrap, I strongly advice you to buy a small book about bootstrap 3. So that you know the basics of bootstrap without GWT.
After this, go back to GWT and apply your new knowledge.


问:
Git Option doesn't show in Android Studio anymore
I'm missing the git option in Android Studio -> VCS. One moment it was there a few minutes later it was gone and I have no clue why this happened.

Here is what I see:

And:

答:
It’s mainly caused Git Integration plugin was disabled. You should enable the plugin:

File -> Settings -> Plugins -> serch git -> Enable Git Integration -> OK -> restart AS.


问:
Why the downloaded web pages have so long *.js files?
I am learning to develop a website.
I am the backend developer but have no experience in this web development.

I have several good references such as https://mvs.org/
In order to see how many lines of code or structure of the web pages, I downloaded the entire web page using Httrack.

I am surprised that a few *.js files include around 60,000 lines of code.
Does it mean that the web developer of the pages wrote that many codes?
or am I missing something here?

答:
It might be a library such as JQuery or React.js, which indeed can include many lines.

Sometimes (usually) all .js files are also bundled into one big file.


问:
Shuffle string c#
I want to know shuffle string

Example string

```<code>string word;

//I want to shuffle it
word = "hello"
</code>```

I would be able to get:

```<code>rand == "ohlel"
rand == "lleho"
etc.
</code>```

答:
inspired from tsql' order by newid()</p>

```<code>static string shuffle(string input)
{
    var q = from c in input.ToCharArray()
            orderby Guid.NewGuid()
            select c;
    string s = string.Empty;
    foreach (var r in q)
        s += r;
    return s;
}
</code>```

Title: Shuffle string c#

Body:
I want to know shuffle string

Example string

string word;

//I want to shuffle it
word = "hello"

I would be able to get:

rand == "ohlel"
rand == "lleho"
etc.

Body:
inspired from tsql' order by newid()

static string shuffle(string input)
{
    var q = from c in input.ToCharArray()
            orderby Guid.NewGuid()
            select c;
    string s = string.Empty;
    foreach (var r in q)
        s += r;
    return s;
}


问:
Type string cannot be converted to type SomeClass in Angular 4/2. Why?
I have a Company and a Contact class, I have service for both.
This is how the classes look like:

The Company class:

```<code>export class Company{
    id: number;
    logo: string;
    name: string;
    phone: string;
    email: string;
    website: string;
    facebook: string;
    country_code: string;
    hq_country: string;
    hq_zipcode: number;
    hq_settlement: string;
    hq_address: string;
    bi_name: string;
    bi_country: string;
    bi_zipcode: number;
    bi_settlement: string;
    bi_address: string;
    taxnumber: number;
    mail_name: string;
    mail_country: string;
    mail_zipcode: number;
    mail_settlement: string;
    mail_address: string;
    industry_id: number;
    employeesnum_id: number;
    yearlyincome_id: number;
    founded: number;
    selected: boolean;
    project: number[];
}
</code>```

The Contact class:

```<code>import { Company } from './company';

export class Contact{
    id: number;
    company: Company[];
    full_name: string;
    surname: string;
    middle_name: string;
    forename: string;
    nickname: string;
    phone: string;
    email: string;
    primary_communication_chanel: string;
    rank: string;
    greeting: string;
    selected: boolean;
}
</code>```

In their services, there are an add method, where you can add new company (or contact) to the in memory web api:

this is very similar in the 2 services:

in company.service:

```<code>addCompany(company: Company): Observable<Company>{
    return this.http.post<Company>(this.companiesUrl, company, httpOptions).pipe(
        catchError(this.handleError<Company>('addHero'))
    );
}
</code>```

in contact.service:

```<code>addContact(contact: Contact): Observable<Contact>{
    return this.http.post<Contact>(this.contactsUrl, contact, httpOptions).pipe(
        catchError(this.handleError<Contact>('addContact'))
    );
}
</code>```

And I have components to companies and contacts, where I display the companies/contacts I have. In this components you can add new company/contact instat. Instat means you only have to give the name of the company/contact.

This is the methods to add instant company/contact:

in companies.compontent:

```<code>addInstant(name: string): void{
    name = name.trim();
    if (!name) { return; }
    this.companiesService.addCompany({ name } as Company)
        .subscribe(company => {
    this.companies.push(company);
  });
}
</code>```

in contats.component:

```<code>addInstant(name: string): void{
    name = name.trim();
    if (!name) { return; }
    this.contactsService.addContact({ name } as Contact)
        .subscribe(contact => {
    this.contacts.push(contact);
  });
}
</code>```

This 2 is really similar. The problem is in the companies.component is work, no error, but in the contacts.component there is an error: Type '{ name: string; }' cannot be converted to type 'Contact'. Property 'id' is missing in type '{ name: string; }'.
If I add the id manually, still have an error ("Property 'company' is missing...").

What is the problem?

答:
If you take a look at your Contact class, there is no property with the name of name. Really I'd recommend you alter your services to pass in a string and change the web API to accept the string rather than a whole object.

If you are not trying to set the name property you can do this:

```<code>this.contactsService.addContact({ fullName: name } as Contact)
</code>```

Body:
I have a Company and a Contact class, I have service for both.
This is how the classes look like:

The Company class:

export class Company{
    id: number;
    logo: string;
    name: string;
    phone: string;
    email: string;
    website: string;
    facebook: string;
    country_code: string;
    hq_country: string;
    hq_zipcode: number;
    hq_settlement: string;
    hq_address: string;
    bi_name: string;
    bi_country: string;
    bi_zipcode: number;
    bi_settlement: string;
    bi_address: string;
    taxnumber: number;
    mail_name: string;
    mail_country: string;
    mail_zipcode: number;
    mail_settlement: string;
    mail_address: string;
    industry_id: number;
    employeesnum_id: number;
    yearlyincome_id: number;
    founded: number;
    selected: boolean;
    project: number[];
}

The Contact class:

import { Company } from './company';

export class Contact{
    id: number;
    company: Company[];
    full_name: string;
    surname: string;
    middle_name: string;
    forename: string;
    nickname: string;
    phone: string;
    email: string;
    primary_communication_chanel: string;
    rank: string;
    greeting: string;
    selected: boolean;
}

In their services, there are an add method, where you can add new company (or contact) to the in memory web api:

this is very similar in the 2 services:

in company.service:

addCompany(company: Company): Observable<Company>{
    return this.http.post<Company>(this.companiesUrl, company, httpOptions).pipe(
        catchError(this.handleError<Company>('addHero'))
    );
}

in contact.service:

addContact(contact: Contact): Observable<Contact>{
    return this.http.post<Contact>(this.contactsUrl, contact, httpOptions).pipe(
        catchError(this.handleError<Contact>('addContact'))
    );
}

And I have components to companies and contacts, where I display the companies/contacts I have. In this components you can add new company/contact instat. Instat means you only have to give the name of the company/contact.

This is the methods to add instant company/contact:

in companies.compontent:

addInstant(name: string): void{
    name = name.trim();
    if (!name) { return; }
    this.companiesService.addCompany({ name } as Company)
        .subscribe(company => {
    this.companies.push(company);
  });
}

in contats.component:

addInstant(name: string): void{
    name = name.trim();
    if (!name) { return; }
    this.contactsService.addContact({ name } as Contact)
        .subscribe(contact => {
    this.contacts.push(contact);
  });
}

This 2 is really similar. The problem is in the companies.component is work, no error, but in the contacts.component there is an error: Type '{ name: string; }' cannot be converted to type 'Contact'. Property 'id' is missing in type '{ name: string; }'.
If I add the id manually, still have an error ("Property 'company' is missing...").

What is the problem?

Body:
If you take a look at your Contact class, there is no property with the name of name. Really I'd recommend you alter your services to pass in a string and change the web API to accept the string rather than a whole object.

If you are not trying to set the name property you can do this:

this.contactsService.addContact({ fullName: name } as Contact)


问:
How to pass pass user credentials to chrome via Native Messaging API
This is a pretty specific problem to have ... but if you're using Selenium, etc, from a machine which is not part of an Active Directory and you're being foiled by browser popups, I have a solution for you.

I will explain the problem and link to some resources (and my other questions, with even more links in them) which informed the solution then I'll post the change I made to the example for the extension I "wrote."

Problem:

You're automating or testing via selenium or something similar ... and an auth popup comes out of the blue! But this popup isn't JavaScript and you're required not to save any credentials on the machine you're testing from.

How do you pass through the authentication credentials to the browser and prevent that popup from occurring ... but without using keystores, browser storage or, ghasp, a file?

Once you know how to pass that data in, how do you then get the values into the browser in such a way as to allow hands-free authentication?

答:
Solution:

You're going to need to use a browser extension.
My solution has been built for chromium but it should port almost-unchanged for Firefox and maybe edge.

First up, you need 2 APIs to be available for your browser:

webRequest.onAuthRequired - Chrome & Firefox

runtime.nativeMessaging - Chrome & Firefox

While both browser APIs are very similar, they do have some significant differences - such as Chrome's implementation lacking Promises.

If you setup your Native Messaging Host to send a properly-formed JSON string, you need only poll it once. This means you can use a single call to runtime.sendNativeMessage() and be assured that your credentials are paresable. Pun intended.

Next, we need to look at how we're supposed to handle the webRequest.onAuthRequired event.

Since I'm working in Chromium, I need to use the promise-less Chrome API.

```<code>chrome.webRequest.onAuthRequired.addListener(
  callbackFunctionHere,
  {urls:[targetUrls]},
  ['asyncBlocking'] // --> this line is important, too. Very.
</code>```

The Change:

I'll be calling my function provideCredentials because I'm a big stealy-stealer and used an example from this source. Look for the asynchronous version.

The example code fetches the credentials from storage.local ...

```<code>chrome.storage.local.get(null, gotCredentials);
</code>```

We don't want that. Nope.

We want to get the credentials from a single call to sendNativeMessage so we'll change that one line.

```<code>chrome.runtime.sendNativeMessage(hostName, { text: "Ready" }, gotCredentials);
</code>```

That's all it takes. Seriously. As long as your Host plays nice, this is the big secret. I won't even tell you how long it took me to find it!

Links:

My questions with helpful links:

Here - Workaround for Authenticating against Active Directory

Here - Also has some working code for a functional NM Host

Here - Some enlightening material on promises

Body:
Solution:

You're going to need to use a browser extension.
My solution has been built for chromium but it should port almost-unchanged for Firefox and maybe edge.

First up, you need 2 APIs to be available for your browser:

webRequest.onAuthRequired - Chrome & Firefox

runtime.nativeMessaging - Chrome & Firefox

While both browser APIs are very similar, they do have some significant differences - such as Chrome's implementation lacking Promises.

If you setup your Native Messaging Host to send a properly-formed JSON string, you need only poll it once. This means you can use a single call to runtime.sendNativeMessage() and be assured that your credentials are paresable. Pun intended.

Next, we need to look at how we're supposed to handle the webRequest.onAuthRequired event.

Since I'm working in Chromium, I need to use the promise-less Chrome API.

chrome.webRequest.onAuthRequired.addListener(
  callbackFunctionHere,
  {urls:[targetUrls]},
  ['asyncBlocking'] // --> this line is important, too. Very.

The Change:

I'll be calling my function provideCredentials because I'm a big stealy-stealer and used an example from this source. Look for the asynchronous version.

The example code fetches the credentials from storage.local ...

chrome.storage.local.get(null, gotCredentials);

We don't want that. Nope.

We want to get the credentials from a single call to sendNativeMessage so we'll change that one line.

chrome.runtime.sendNativeMessage(hostName, { text: "Ready" }, gotCredentials);

That's all it takes. Seriously. As long as your Host plays nice, this is the big secret. I won't even tell you how long it took me to find it!

Links:

My questions with helpful links:

Here - Workaround for Authenticating against Active Directory

Here - Also has some working code for a functional NM Host

Here - Some enlightening material on promises