问:
Why does this Javascript example copy the variable value instead of pass by reference?
In Javascript The Good Parts, it states:

So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?

```<code>var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';

$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"
</code>```

Added:

@Gareth @David, thanks, this is what I was trying to show in this example, works:

```<code>var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';

$('p#test').html(page_item.access_groups.developer); //is '1001'
</code>```

答:
Don't think of pass-by-reference in the C++ context, because it's not the same.

```<code>var member = page_item.access_groups.member // Sets member to this value
member = '1001'; // Now sets it to another value
</code>```

If there was a method on strings which changed them, then this:

```<code>member.removeLastLetter();
</code>```

would alter page_item.access_groups.member. However, with your = you are changing the variable's reference, not the object it previously referenced

Body:
In Javascript The Good Parts, it states:

So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';

$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"

Added:

@Gareth @David, thanks, this is what I was trying to show in this example, works:

var page_item = {
  id_code : 'welcome',
  title : 'Welcome',
  access_groups : {
      developer : '0010',
      administrator : '0100'
  }
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';

$('p#test').html(page_item.access_groups.developer); //is '1001'

Body:
Don't think of pass-by-reference in the C++ context, because it's not the same.

var member = page_item.access_groups.member // Sets member to this value
member = '1001'; // Now sets it to another value

If there was a method on strings which changed them, then this:

member.removeLastLetter();

would alter page_item.access_groups.member. However, with your = you are changing the variable's reference, not the object it previously referenced


来源: stackexchange

问:
scala get function name that was sent as param
I have a method that accepts a function as a param. is it possible to extract the function name ?
e.g:</p>

```<code>def plusOne(x:Int) = x+1
def minusOne(x:Int) = x+1

def printer(f: Int => Int) = println("Got this function ${f.getName}") //doesn't work of course

scala> printer(plusOne)
Got this function plusOne

scala> printer(minussOne)
Got this function minusOne
</code>```

答:
Not directly. Note that a lambda could be passed as well instead of a function or method name. But you may want to look at the sourcecode library, which may help you achieve some of this. For instance:

```<code>val plusOne = (x: Int) => x + 1
val minusOne = (x: Int) => x + 1

def printer(fWithSrc: sourcecode.Text[Int => Int]) = {
  val f = fWithSrc.value
  println(s"Got this function ${ fWithSrc.source }. f(42) = ${ f(42) }")
}
</code>```

Due to the way implicit conversions work, you cannot use the def version directly as in your example. If you have this:

```<code>def plusOne(x: Int) = x + 1
</code>```

Then you need this:

```<code>printer(plusOne _)
</code>```

and you'll also see the _ in the String representation of the parameter.

Note that it also breaks type inference for lambdas, i.e., you can't write this any more:

```<code>printer(_ * 2)
</code>```

which is a shame.

ContentLicense: CC BY-SA 3.0

Body:
I have a method that accepts a function as a param. is it possible to extract the function name ?
e.g:

def plusOne(x:Int) = x+1
def minusOne(x:Int) = x+1

def printer(f: Int => Int) = println("Got this function ${f.getName}") //doesn't work of course

scala> printer(plusOne)
Got this function plusOne

scala> printer(minussOne)
Got this function minusOne

Body:
Not directly. Note that a lambda could be passed as well instead of a function or method name. But you may want to look at the sourcecode library, which may help you achieve some of this. For instance:

val plusOne = (x: Int) => x + 1
val minusOne = (x: Int) => x + 1

def printer(fWithSrc: sourcecode.Text[Int => Int]) = {
  val f = fWithSrc.value
  println(s"Got this function ${ fWithSrc.source }. f(42) = ${ f(42) }")
}

Due to the way implicit conversions work, you cannot use the def version directly as in your example. If you have this:

def plusOne(x: Int) = x + 1

Then you need this:

printer(plusOne _)

and you'll also see the _ in the String representation of the parameter.

Note that it also breaks type inference for lambdas, i.e., you can't write this any more:

printer(_ * 2)

which is a shame.


问:
css style tag is not evaluated in safari
I want to load background images by css dependent on the display resolution with the @media keyword. It works fine in Firefox and chrome, but it does not work in Safari. Is there something I miss?</p>

```<code><!DOCTYPE html>
<html lang="en">
    <head>

        <meta charset="utf-8">
        <title>Snowboardschule: Skigebiet</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="/fileadmin/css/style.css?1496823820" media="all" title="main">

        <style type="text/css">@media(min-resolution: 1dppx){ .trailer { background-image: url(fileadmin/_processed_/e/d/csm_trailer1_ca6cb9b743.jpg); }}</style>
    </head>
    <body>
        <header>
            <div class="trailer">
                ...
            </div>
        </header>
    </body>
</html>
</code>```

答:
Try using</p>

```<code><style type="text/css">
@media and screen (min-resolution: 1dppx)
  { .trailer { background-image: url(fileadmin/_processed_/e/d/csm_trailer1_ca6cb9b743.jpg); }}
</style>
</code>```

Body:
I want to load background images by css dependent on the display resolution with the @media keyword. It works fine in Firefox and chrome, but it does not work in Safari. Is there something I miss?

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Snowboardschule: Skigebiet</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="/fileadmin/css/style.css?1496823820" media="all" title="main">

                ...

Body:
Try using

<style type="text/css">
@media and screen (min-resolution: 1dppx)
  { .trailer { background-image: url(fileadmin/_processed_/e/d/csm_trailer1_ca6cb9b743.jpg); }}
</style>


问:
MySQL using "-" as different
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

```<code>delete from <table> where id - 145;
</code>```

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

答: This is normal, sort of. id - 145 evaluates to nonzero when id is not 145 and nonzero evaluates to true in a boolean context like the where clause.

Title: MySQL using "-" as different

Body:
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

delete from
 where id - 145;

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?


问:
Setting dynamic velocity properties for archetype maven projects
I am creating an archetype and want to create a project wide available property containing things like the current date and an all lower case variant of the artifact id. I found the following post on Stackoverflow, that shows how it normally should be possible.

I tried adding this to the archetype-metadata.xml like so:

```<code>    ...
    <requiredProperty key="artifactIdLower">
        <defaultValue>${artifactId.toLowerCase()}</defaultValue>
    </requiredProperty>
    <requiredProperty key="ldt">
        <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null)}</defaultValue>
    </requiredProperty>
    <requiredProperty key="dtf">
        <defaultValue>${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")}</defaultValue>
    </requiredProperty>
    <requiredProperty key="date">
        <defaultValue>${ldt.format($dtf)}</defaultValue>
    </requiredProperty>
    ...
</code>```

The property artifactIdLower works like a charm, but the ldt, dtf and date don't seem to work, giving the error:

```<code>Null reference [template 'dtf', line 1, column 1] : ${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")} cannot be resolved.
</code>```

After that I tried to see where in the chain this null reference comes from. I was able to set pkgClass to $package.getClass() (or to $package.Class),

but after that I was unable to set $strClass to $package.getClass().forName("java.lang.String") or to $pkgClass.forName("java.lang.String") (funnily enough, both pkgClass and strClass should be a Class object).

This made me wonder if there is a restriction on using reflection inside the archetype-metadata.xml.

My question is: how can I set dynamically generated property values (like above) that can be used project wide?

I don't want to have to define these properties in every file that I create, because there might be more properties that I want to add later.

Edit:
I tried to instead create a generalproperties.vm file that contained the #set directives. This file would then be loaded by every file on the first line using #parse("generalproperties.vm"). While I did get the file to be parsed from within the pom.xml file, it didnt behave as I wanted.

The following input

```<code>test
$null
#set( $ldtClass = $package.getClass().forName("java.time.LocalDateTime") )
$ldtClass.Name
$ldtClass.getMethod("now")
#set( $ldtNowMethod = $ldtClass.getMethod("now") )
$ldtNowMethod.Name
#set( $clsLoader = $package.getClass().getClassLoader() )
$clsLoader
#set( $ldtClass2 = $clsLoader.loadClass("java.time.LocalDateTime") )
$ldtClass2.Name
$ldtClass2.getMethod("now")
#set( $ldtNowMethod2 = $ldtClass2.getMethod("now") )
$ldtNowMethod2.Name
#set( $ldt = $ldtNowMethod2.invoke($null) )
$ldt
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke($null, "yyyy/MM/dd HH:mm:ss") )
$dtf
</code>```

Generated the following output:

```<code>test
$null
java.time.LocalDateTime
$ldtClass.getMethod("now")
$ldtNowMethod.Name
$clsLoader
$ldtClass2.Name
$ldtClass2.getMethod("now")
$ldtNowMethod2.Name
$ldt
$dtf
</code>```

The first 3 outputs are as expected, but after that I don't get the results I want. If someone is able to solve either of the above issues (with the metadata file or the generalproperties file), it would be highly appreciated.

答:
This should work:</p>

```<code>...
<requiredProperty key="date">
    <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null).format($package.Class.forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.Class).invoke(null, "dd MMM yyyy"))}</defaultValue>
</requiredProperty>
...
</code>```

Body:
I am creating an archetype and want to create a project wide available property containing things like the current date and an all lower case variant of the artifact id. I found the following post on Stackoverflow, that shows how it normally should be possible.

I tried adding this to the archetype-metadata.xml like so:

    ...
    <requiredProperty key="artifactIdLower">
        <defaultValue>${artifactId.toLowerCase()}</defaultValue>
    </requiredProperty>
    <requiredProperty key="ldt">
        <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null)}</defaultValue>
    </requiredProperty>
    <requiredProperty key="dtf">
        <defaultValue>${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")}</defaultValue>
    </requiredProperty>
    <requiredProperty key="date">
        <defaultValue>${ldt.format($dtf)}</defaultValue>
    </requiredProperty>
    ...

The property artifactIdLower works like a charm, but the ldt, dtf and date don't seem to work, giving the error:

Null reference [template 'dtf', line 1, column 1] : ${package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke(null, "dd MMM yyyy")} cannot be resolved.

After that I tried to see where in the chain this null reference comes from. I was able to set pkgClass to $package.getClass() (or to $package.Class),

but after that I was unable to set $strClass to $package.getClass().forName("java.lang.String") or to $pkgClass.forName("java.lang.String") (funnily enough, both pkgClass and strClass should be a Class object).

This made me wonder if there is a restriction on using reflection inside the archetype-metadata.xml.

My question is: how can I set dynamically generated property values (like above) that can be used project wide?

I don't want to have to define these properties in every file that I create, because there might be more properties that I want to add later.

Edit:
I tried to instead create a generalproperties.vm file that contained the #set directives. This file would then be loaded by every file on the first line using #parse("generalproperties.vm"). While I did get the file to be parsed from within the pom.xml file, it didnt behave as I wanted.

The following input

test
$null
#set( $ldtClass = $package.getClass().forName("java.time.LocalDateTime") )
$ldtClass.Name
$ldtClass.getMethod("now")
#set( $ldtNowMethod = $ldtClass.getMethod("now") )
$ldtNowMethod.Name
#set( $clsLoader = $package.getClass().getClassLoader() )
$clsLoader
#set( $ldtClass2 = $clsLoader.loadClass("java.time.LocalDateTime") )
$ldtClass2.Name
$ldtClass2.getMethod("now")
#set( $ldtNowMethod2 = $ldtClass2.getMethod("now") )
$ldtNowMethod2.Name
#set( $ldt = $ldtNowMethod2.invoke($null) )
$ldt
#set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass().forName("java.lang.String")).invoke($null, "yyyy/MM/dd HH:mm:ss") )
$dtf

Generated the following output:

test
$null
java.time.LocalDateTime
$ldtClass.getMethod("now")
$ldtNowMethod.Name
$clsLoader
$ldtClass2.Name
$ldtClass2.getMethod("now")
$ldtNowMethod2.Name
$ldt
$dtf

The first 3 outputs are as expected, but after that I don't get the results I want. If someone is able to solve either of the above issues (with the metadata file or the generalproperties file), it would be highly appreciated.

Body:
This should work:

...
<requiredProperty key="date">
    <defaultValue>${package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null).format($package.Class.forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.Class).invoke(null, "dd MMM yyyy"))}</defaultValue>
</requiredProperty>
...


问:
location manager not able to get speed in ios
I am using CLLocationManager in my iOS app to get user's current location.

I also need to calculate the speed of the user and I got that, it can be calculated using the delegate method "didUpdateLocations".

```<code> func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location: CLLocation = locations.last!
    var speed1 = location.speed
    speedLabel.text = "\(speed1)"
}
</code>```

I can get the update of user's current location but the speed value is not correct. Initially the value of speed is -1 then no change in the value even the location is updating correctly.

The initialization of my location manager is below

```<code>    var locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
</code>```

What's wrong with it.

Advanced thanks..

答:
Usually, when dealing with external events and accessories (location, hardware communications etc.) Apple will give you a -1 when the information you want is not computable or is somehow invalid.  You cannot make any assumptions, you simply need to intercept that information (computation error of some kind) and deal with it as if the information was missing.

A negative value indicates an invalid speed

https://developer.apple.com/documentation/corelocation/cllocation/1423798-speed

ContentLicense: CC BY-SA 4.0

Body:
I am using CLLocationManager in my iOS app to get user's current location.

I also need to calculate the speed of the user and I got that, it can be calculated using the delegate method "didUpdateLocations".

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location: CLLocation = locations.last!
    var speed1 = location.speed
    speedLabel.text = "\(speed1)"
}

I can get the update of user's current location but the speed value is not correct. Initially the value of speed is -1 then no change in the value even the location is updating correctly.

The initialization of my location manager is below

    var locationManager = CLLocationManager()
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

What's wrong with it.

Advanced thanks..


问:
Garbage Collection in Delphi
Does Delphi have Garbage Collection?</p>

答:
Simple answer No.

Delphi is not a complete garbage collection language, user-defined types should be manually allocated and deallocated. It only provide automatic collection, for a few built-in types, such as strings, dynamic arrays and interfaces for ease of use.

But you can use interfaces which uses reference counting for garbage collection for some extent.

Title: Garbage Collection in Delphi

Body: Does Delphi have Garbage Collection?

ContentLicense: CC BY-SA 2.5


问:
How to add and substract 15 minutes from date sql
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

```<code>SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'
</code>```

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

```<code>SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'
</code>```

I want to get records where pt_date before 15 minutes and after 15 minutes.

答:
You can use difference in minutes. Query will be like this:</p>

```<code>SELECT
*
FROM post
WHERE st_lati LIKE '19.878454%'
  AND st_longi LIKE '73.836708%'
  AND ed_lati LIKE '20.012709%'
  AND ed_longi LIKE '73.791389%'
  AND ABS(TIMESTAMPDIFF(MINUTE, pt_date, '2017-05-30 06:30')) <= 15;
</code>```

Body:
I have a query to search records depending on latitude longitude and the date.

The query works fine for the same date, but I want to get records which are 15 minutes before the date and 15 minutes after the date.

Working query is this:

SELECT
   *
FROM post
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%'
AND pt_date LIKE '2017-05-30 06:30%'

I tried to minus 15 minutes using dateadd function but its giving errors.

my attempt

SELECT
 *
FROM post
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date)
AND st_lati LIKE '19.878454%'
AND st_longi LIKE '73.836708%'
AND ed_lati LIKE '20.012709%'
AND ed_longi LIKE '73.791389%'

I want to get records where pt_date before 15 minutes and after 15 minutes.

Body:
You can use difference in minutes. Query will be like this:

SELECT
*
FROM post
WHERE st_lati LIKE '19.878454%'
  AND st_longi LIKE '73.836708%'
  AND ed_lati LIKE '20.012709%'
  AND ed_longi LIKE '73.791389%'
  AND ABS(TIMESTAMPDIFF(MINUTE, pt_date, '2017-05-30 06:30')) <= 15;


问:
How to use one CSV file to pass data into multiple HTTP Samples in Jmeter?
I want to pass test data from one csv file to multiple http requests like first row should take by 1st http sample and second row should take by 2nd http sample.Please help how to use this in jmeter.</p>

答:
You can follow these:

Add your CSV Dataset config in test plan level

Define Thread group (enough thread, ramp-up, duration)

Under thread group, add your requests or samples.

Put your CSV file in the JMeter bin directory.

Use those variables (defined in CSV Dataset) in your requests.

Hint:

CSV Data set Config:

Http Request sampler:


问:
nvm is not compatible with the npm config "prefix" option:
I am trying to run another NodeJS version with nvm but getting this error:

```<code>$ nvm use v4.2.4

nvm is not compatible with the npm config "prefix" option:
   currently set to "/Users/z/.npm-global"
Run `npm config delete prefix` or `nvm use --delete-prefix v4.2.4` to unset it.
</code>```

I have my prefix set on purpose to avoid sudo npm (see https://docs.npmjs.com/getting-started/fixing-npm-permissions).

Is there any way I can use nvm without losing my prefix for globally installed packages?

答:
I ran into this while using node installed via nvm, with nvm installed via homebrew. I solved it by running brew uninstall nvm, rm -rf $NVM_DIR, then reinstalling nvm using the official install script and reinstalling the node version I needed.

Note: I also had $NVM_DIR mounted and symlinked. I moved it back into my homedir.

Body:
I am trying to run another NodeJS version with nvm but getting this error:

$ nvm use v4.2.4

nvm is not compatible with the npm config "prefix" option:
   currently set to "/Users/z/.npm-global"
Run `npm config delete prefix` or `nvm use --delete-prefix v4.2.4` to unset it.

I have my prefix set on purpose to avoid sudo npm (see https://docs.npmjs.com/getting-started/fixing-npm-permissions).

Is there any way I can use nvm without losing my prefix for globally installed packages?


问:
A suitable PC for Visual Studio 2010 programming
I'm planning on buying a new PC for programming under Visual Studio 2010. My main other usages are:

Programming under Microsoft Visual Studio.

Running VMWare Virtual Machines.

Probably multi-monitor (if my budget lets me buy an extra one)

Here are my questions:

Do I need to purchase a high performance display adapter considering my usage described above? or a medium-range one will suffice? In general, I'd like to know how much a display adapter could affect my usages?

Which CPU could perform better? Core i7, Core 2 Quad, AMD?  I have a limited budget but I really need a good performance and buying a good CPU/MB/RAM is my first priority.

答:
You can really get a great developer machine if you're willing to build it yourself.

Scott Hanselman says:

Jedis build their own lightsabers, so
you should build your own computer at
least once!

He describes how he built GOM (God's Own Machine) here for under $3K, and describes it in a podcast here.

If building your own is a bit beyond your aspirations, you can get some good ideas there about the most important features for a developer, from a Microsoft guru who really knows.


问:
What is setBounds and how do I use it?
I cannot find anything on setBounds, what it is for, or what its function actually is.  Could someone clear me up on this?  Thanks so much!</p>

答:
The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components.
Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

```<code>import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}
</code>```

Title: What is setBounds and how do I use it?

Body:
The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components.
Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.

For the NullLayoutManager (in case you used new JPanel(null)) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.

So with public void Component.setBounds(int x, int y, int width, int height) you specify where your component is placed and how many pixel it is wide and high.

Here's an example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JTableInNullLayout
{
  public static void main(String[] argv) throws Exception {

      JPanel panel = new JPanel(null);

      JLabel helloLabel = new JLabel("Hello world!");
      helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
      panel.add(helloLabel);

      JFrame frame = new JFrame();
      frame.add(panel);
      frame.setPreferredSize( new Dimension(200,200));
      frame.pack();
      frame.setVisible(true);
  }
}


问:
Ionic2 menuToggle hide dynamically
I am using Ionic2, and would like to show/hide the menuToggle on a user event. This is how it's done in Ionic1. Does anyone know how to do it in Ionic2 please?

Thanks

答:
suppose your code as following:

```<code><ion-menu [content]="mycontent" [class.hide]="hideMenu">
 <ion-content>
   <ion-list>
     <ion-item menuClose detail-none>Close Menu</ion-item>
   </ion-list>
 </ion-content>
</ion-menu>
</code>```

then add hide style in the Component's .scss file:

```<code>.hide{display: none !important}
</code>```

at last, in your .ts file, you can control the display state of menuToggle by change the value of "hideMenu", for Example,

```<code>hideMenu: boolean = false; // at first the menuToggle is show
....
btnClicked(){
  this.hideMenu = !this.hideMenu;
}
</code>```

Title: Ionic2 menuToggle hide dynamically

Body:
suppose your code as following:

<ion-menu [content]="mycontent" [class.hide]="hideMenu">
 <ion-content>
   <ion-list>
     <ion-item menuClose detail-none>Close Menu</ion-item>
   </ion-list>
 </ion-content>
</ion-menu>

then add hide style in the Component's .scss file:

.hide{display: none !important}

at last, in your .ts file, you can control the display state of menuToggle by change the value of "hideMenu", for Example,

hideMenu: boolean = false; // at first the menuToggle is show
....
btnClicked(){
  this.hideMenu = !this.hideMenu;
}


问:
Rebus: how to intercept when all correlated events are applied
I’m wondering if there is an easy way in ReBus to be notified when all “child” events (all events with a specific correlation id) have been executed.</p>

答:
I am not entirely sure what you are trying to achieve, but if I understand you correctly you are simply asking how to know when a couple of particular messages have been processed.

In many cases, this can be solved by implementing logic similar to this in each subscriber:

```<code>public class SomeSubscriberHandler : IHandleMessages<AnEvent>
{
    public async Task Handle(AnEvent anEvent)
    {
        // handle event by doing something
        // ...

        // let the world know I did something
        await _bus.Publish(new SomeSubscriberDidSomething(anEvent.CorrelationId));
    }
}
</code>```

thereby allowing a saga to subscribe to SomeSubscriberDidSomething, correlating by the enclosed CorrelationId.

If all subscribers do this, the saga can easily determine how far this process has come, and then figure out some final thing to do when all subscribers have done their things.

Body:
I am not entirely sure what you are trying to achieve, but if I understand you correctly you are simply asking how to know when a couple of particular messages have been processed.

In many cases, this can be solved by implementing logic similar to this in each subscriber:

public class SomeSubscriberHandler : IHandleMessages<AnEvent>
{
    public async Task Handle(AnEvent anEvent)
    {
        // handle event by doing something
        // ...

        // let the world know I did something
        await _bus.Publish(new SomeSubscriberDidSomething(anEvent.CorrelationId));
    }
}

thereby allowing a saga to subscribe to SomeSubscriberDidSomething, correlating by the enclosed CorrelationId.

If all subscribers do this, the saga can easily determine how far this process has come, and then figure out some final thing to do when all subscribers have done their things.


问:
rbenv install --list does not list version 2.1.2
I installed rbenv via Homebrew on an OS X 10.9.3 MacBook Pro:

```<code>brew update
brew upgrade rbenv ruby-build
</code>```

According to rbenv install --list on my laptop Ruby 2.1.0-dev is the latest.

答:
cd /home/[user]/.rbenv/plugins/ruby-build && git pull && cd -

Don't forget to replace [user] with your user

Body:
I installed rbenv via Homebrew on an OS X 10.9.3 MacBook Pro:

brew update
brew upgrade rbenv ruby-build

According to rbenv install --list on my laptop Ruby 2.1.0-dev is the latest.


问:
Python Tabs Fake or Real
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

```<code>au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf
</code>```

For other case:

```<code>set noexpandtab                " tabs are tabs, not spaces
</code>```

答: Many, if not most editors will do an inline conversion of tabs to a user defined number of spaces. Set that to 4 and you are home free. The real pain comes when you are on a team that hasn't standardized on this idea of 4 spaces.</p>

Title: Python Tabs Fake or Real

Body:
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf

For other case:

set noexpandtab                " tabs are tabs, not spaces


问:
Is there a command to undo git init?
I just Git init'ed a repos with a wrong user, and want to undo it.  Is there any command for this?  Do I actually have to go in and edit the .git directory?</p>

答:
Git keeps all of its files in the .git directory. Just remove that one and init again.

This post well show you how to find the hide .git file on Windows, Mac OSX, Ubuntu

Title: Is there a command to undo git init?


问:
Add two numbers and display result in textbox with Javascript
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in another text field. But unfortunately the below code is not working. Clicking the button does not show anything in the result text field. </p>

```<code><body>
    <div>
        <div>
            <h1>Add two number using text box as input using javascript</h1>
        </div>
            Enter First Number : <br>
            <input type="text" id="Text1" name="TextBox1">
            <br>
            Enter Second Number : <br>
            <input type="text" id="Text2" name="TextBox2">
            <br>
            Result : <br>
            <input type="text" id="txtresult" name="TextBox3">
            <br>
         <input type="button" name="clickbtn" value="Display Result" onclick="add_number()">

        <script type="text/javascript">
            function add_number(){
            var first_number = parseInt(document.getElementsById("Text1").value);
            var second_number = parseInt(document.getElementsById("Text2").value);
            var result = first_number + second_number;
            document.getElementById("txtresult").innerHTML = result;
            }
        </script>
</code>```

答:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

    $scope.minus = function() {

     var a = Number($scope.a || 0);
            var b = Number($scope.b || 0);
            $scope.sum1 = a-b;
    // $scope.sum = $scope.sum1+1;
    alert($scope.sum1);
    }

   $scope.add = function() {

     var c = Number($scope.c || 0);
            var d = Number($scope.d || 0);
            $scope.sum2 = c+d;
    alert($scope.sum2);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
   </head>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
     <h3>Using Double Negation</h3>

    <p>First Number:
        <input type="text" ng-model="a" />
    </p>
    <p>Second Number:
        <input type="text" ng-model="b" />
    </p>
    <button id="minus" ng-click="minus()">Minus</button>
    <!-- <p>Sum: {{ a - b }}</p>  -->
 <p>Sum: {{ sum1 }}</p>

    <p>First Number:
        <input type="number" ng-model="c" />
    </p>
    <p>Second Number:
        <input type="number" ng-model="d" />
    </p>
 <button id="minus" ng-click="add()">Add</button>
    <p>Sum: {{ sum2 }}</p>
</div></code>```

Body:
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in another text field. But unfortunately the below code is not working. Clicking the button does not show anything in the result text field.

Add two number using text box as input using javascript

            Enter First Number :

            <input type="text" id="Text1" name="TextBox1">

            Enter Second Number :

            <input type="text" id="Text2" name="TextBox2">

            Result :

            <input type="text" id="txtresult" name="TextBox3">

         <input type="button" name="clickbtn" value="Display Result" onclick="add_number()">

Body:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

    $scope.minus = function() {

     var a = Number($scope.a || 0);
            var b = Number($scope.b || 0);
            $scope.sum1 = a-b;
    // $scope.sum = $scope.sum1+1;
    alert($scope.sum1);
    }

   $scope.add = function() {

     var c = Number($scope.c || 0);
            var d = Number($scope.d || 0);
            $scope.sum2 = c+d;
    alert($scope.sum2);
    }
});

<head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
   </head>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
     <h3>Using Double Negation</h3>

    <p>First Number:
        <input type="text" ng-model="a" />
    </p>
    <p>Second Number:
        <input type="text" ng-model="b" />
    </p>
    <button id="minus" ng-click="minus()">Minus</button>
    <!-- <p>Sum: {{ a - b }}</p>  -->
 <p>Sum: {{ sum1 }}</p>

    <p>First Number:
        <input type="number" ng-model="c" />
    </p>
    <p>Second Number:
        <input type="number" ng-model="d" />
    </p>
 <button id="minus" ng-click="add()">Add</button>
    <p>Sum: {{ sum2 }}</p>
</div>


问:
How to efficiently find relations between html nodes with vanillaJS
I have several html nodes at various locations and depths in the DOM.
I need to efficiently sort them according to their location in the DOM regardless of each of their depths.

It should be implemented using VanillaJS, no jQuery and the likes.

For instance, given the following tree:

```<code><body>
   <div>
      <div id="a1b"></div>
   <div>
      <div>
         <div id="c1d"></div>
      </div>
      <div id="e1f"></div>
   </div>
   <div id="g1h"></div>
</body>
</code>```

Let's say we have a function that received the four html elements that have ids in a random order, the function should return those elements by the order of appearance within the DOM, namely an array similar to this: [a1b node, c1d node, e1f node, g1h node].

答:
I think this is nice approach:

var randomNodes = [document.getElementById('c1d'),document.getElementById('a1b'),document.getElementById('e1f')]
var sorted = document.querySelectorAll(randomNodes.map(el=>'#'+el.id).join(', '));
console.log(sorted);
//if you want standard array:
console.log([...sorted]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
      <div id="a1b"></div>
   <div>
      <div>
         <div id="c1d"></div>
      </div>
   </div>
   <div id="e1f"></div></code>```

Body:
I have several html nodes at various locations and depths in the DOM.
I need to efficiently sort them according to their location in the DOM regardless of each of their depths.

It should be implemented using VanillaJS, no jQuery and the likes.

For instance, given the following tree:

Let's say we have a function that received the four html elements that have ids in a random order, the function should return those elements by the order of appearance within the DOM, namely an array similar to this: [a1b node, c1d node, e1f node, g1h node].

Body:
I think this is nice approach:

var randomNodes = [document.getElementById('c1d'),document.getElementById('a1b'),document.getElementById('e1f')]
var sorted = document.querySelectorAll(randomNodes.map(el=>'#'+el.id).join(', '));
console.log(sorted);
//if you want standard array:
console.log([...sorted]);

<div>
      <div id="a1b"></div>
   <div>
      <div>
         <div id="c1d"></div>
      </div>
   </div>
   <div id="e1f"></div>


问:
Maintain order of requests when making several ajax callbacks
I'm looping through several items and making an ajax request for each of them (using jQuery).  I want them to execute independently, but populate into the DOM in the order they were called, not the order they are returned (for some reason some requests are taking longer than others).  Any tips on the best practice for this type of thing? </p>

答:
The answer to this ended up being a jQuery plugin called ajaxManager.  This did exactly what I needed:

https://github.com/aFarkas/Ajaxmanager


问:
Difference between SHL and SAL in 80x86
I have learned how to work with 80x86 assembler, so in bit-wise shift operation, I faced a problem with SAL and SHL usage. I means the difference between lines of code as follow :

```<code>MOV X, 0AAH
SAL X, 4

MOV X, 0AAH
SHL X, 4
</code>```

When we should use SHL and when use SAL? What is the difference of them?

答:
actually both are same ..!
but SAL Used when numeric multiplication is intended
EXAMPLE SAL:

```<code>Multiply AX by 8
MOV CL, 3
SAL AX, CL
</code>```

BOTH ARE MOSTLY WORK SAME AND HAVE SAME MACHINE CODE

Title: Difference between SHL and SAL in 80x86

Body:
I have learned how to work with 80x86 assembler, so in bit-wise shift operation, I faced a problem with SAL and SHL usage. I means the difference between lines of code as follow :

MOV X, 0AAH
SAL X, 4

MOV X, 0AAH
SHL X, 4

When we should use SHL and when use SAL? What is the difference of them?

Body:
actually both are same ..!
but SAL Used when numeric multiplication is intended
EXAMPLE SAL:

Multiply AX by 8
MOV CL, 3
SAL AX, CL

BOTH ARE MOSTLY WORK SAME AND HAVE SAME MACHINE CODE


问:
Error while using Github library in Java in Android Studio
I want to create a Speaker Recognition Android app using android studio.

I came accross https://github.com/amaurycrickx/recognito Library in java.
But I am having difficulty in implementing it in Android.

First, I saved the recognito folder by copying it in libs folder (creating it manually) in my main directory of my android app.

Then, in settings.gradle file -- include ':recognito'

```<code>build.gradle app file --     compile project(':recognito')
</code>```

After sync. getting the error -

```<code>Error:Project :app declares a dependency from configuration 'compile' to configuration 'default' which is not declared in the descriptor for project :recognito.
</code>```

I researched, Gradle error: configuration declares dependency which is not declared It says that since build.gradle file doesn`t exists for the Recognito project. But how will it? Cos it contains only java files.

Please help ..

Build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId "com.urvi.android.abc"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile project(':recognito')

}
</code>```

settings.gradle

```<code>include ':app'
include ':recognito'
</code>```

and the folder Recognito I copied has https://github.com/amaurycrickx/recognito/tree/master/recognito files. I did not copy from the initial path

答:
The way you try to add the library it needs to have gradle build-files. I see 2 ways to solve the problem:

create a jar from the library and include it this way

use a service like jitpack to include the library

For generating the jar:
 * clone the repo
 * cd recognito
 * mvn package

then you get:

```<code>Results :

Tests run: 53, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ recognito ---
[INFO] Building jar: /home/ligi/git/3rd/recognito/recognito/target/recognito-0.1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.318 s
[INFO] Finished at: 2017-06-07T11:58:23+02:00
[INFO] Final Memory: 21M/302M
[INFO] --
</code>```

there is your jar - now include it.

Body:
I want to create a Speaker Recognition Android app using android studio.

I came accross https://github.com/amaurycrickx/recognito Library in java.
But I am having difficulty in implementing it in Android.

First, I saved the recognito folder by copying it in libs folder (creating it manually) in my main directory of my android app.

Then, in settings.gradle file -- include ':recognito'

build.gradle app file --     compile project(':recognito')

After sync. getting the error -

Error:Project :app declares a dependency from configuration 'compile' to configuration 'default' which is not declared in the descriptor for project :recognito.

I researched, Gradle error: configuration declares dependency which is not declared It says that since build.gradle file doesn`t exists for the Recognito project. But how will it? Cos it contains only java files.

Please help ..

Build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId "com.urvi.android.abc"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile project(':recognito')

}

settings.gradle

include ':app'
include ':recognito'

and the folder Recognito I copied has https://github.com/amaurycrickx/recognito/tree/master/recognito files. I did not copy from the initial path

Body:
The way you try to add the library it needs to have gradle build-files. I see 2 ways to solve the problem:

create a jar from the library and include it this way

use a service like jitpack to include the library

For generating the jar:
 * clone the repo
 * cd recognito
 * mvn package

then you get:

Results :

Tests run: 53, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ recognito ---
[INFO] Building jar: /home/ligi/git/3rd/recognito/recognito/target/recognito-0.1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.318 s
[INFO] Finished at: 2017-06-07T11:58:23+02:00
[INFO] Final Memory: 21M/302M
[INFO] --

there is your jar - now include it.


问:
how to convert xml response to class object in c#?
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

```<code><Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>
</code>```

this is my class in c#:

```<code>        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }
</code>```

this is my method in c#:

```<code>    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }
</code>```

答:
User this class for serialization and destabilization</p>

```<code>[XmlRoot(ElementName="User")]
    public class User {
        [XmlElement(ElementName="UserId")]
        public string UserId { get; set; }
        [XmlElement(ElementName="Email")]
        public string Email { get; set; }
        [XmlElement(ElementName="UserName")]
        public string UserName { get; set; }
        [XmlElement(ElementName="ProfileImage")]
        public string ProfileImage { get; set; }
        [XmlElement(ElementName="Name")]
        public string Name { get; set; }
        [XmlElement(ElementName="InterestId")]
        public List<string> InterestId { get; set; }
        [XmlElement(ElementName="FeedId")]
        public List<string> FeedId { get; set; }
        [XmlElement(ElementName="Description")]
        public List<string> Description { get; set; }
        [XmlElement(ElementName="Interest")]
        public List<string> Interest { get; set; }
    }

    [XmlRoot(ElementName="Users")]
    public class Users {
        [XmlElement(ElementName="User")]
        public List<User> User { get; set; }
    }
</code>```

Body:
Hi i am going for the xml response to convert as a class object in c#.i have get the xml from the sql side and call the one utility and get the xml and go for the convert in class object but with my code not return null in the class. any one know where is my problem then please let me know.

Here is my xml data :

<Users>
      <User>
            <UserId>1</UserId>
            <Email>abc@gmail.com</Email>
            <UserName>abc</UserName>
            <ProfileImage>20160816105401206.jpeg</ProfileImage>
            <Name>abc</Name>

            <InterestId>8</InterestId>
            <FeedId>4608</FeedId>
            <Description>Test</Description>
            <Interest>Cricekt</Interest>

            <InterestId>12</InterestId>
            <FeedId>4609</FeedId>
            <Description>Test 2</Description>
            <Interest>Read</Interest>
      </User>
       <User>
            <UserId>2</UserId>
            <Email>xyz@gmail.com</Email>
            <UserName>xyz</UserName>
            <ProfileImage>20160816105401207.jpeg</ProfileImage>
            <Name>xyz</Name>

            <InterestId>8</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>swim</Interest>

            <InterestId>12</InterestId>
            <FeedId>4610</FeedId>
            <Description>Test 3</Description>
            <Interest>drive</Interest>
      </User>
 </Users>

this is my class in c#:

        [XmlRoot]
    public class Users
    {
        [XmlRoot]
        public class User
        {
            [XmlElement]
            public int UserId { get; set; }

            [XmlElement]
            public string Email { get; set; }

            [XmlElement]
            public string UserName { get; set; }

            [XmlElement]
            public string ProfileImage { get; set; }

            [XmlElement]
            public string Name { get; set; }

            [XmlElement]
            public int FeedId { get; set; }

            [XmlElement]
            public string Description { get; set; }

            [XmlElement]
            public string Interest { get; set; }

            [XmlElement]
            public int InterestId { get; set; }

        }

        [XmlArray("UserList")]
        [XmlArrayItem("User")]
        public User[] ListUsers { get; set; }
    }

this is my method in c#:

    public string xmldata()
    {
        Users obju = new Users();

            string xml = "";
            DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "Getxml",1,10);
            if (ds != null && ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    xml += ds.Tables[0].Rows[i]["XML_F52E2B61-18A1-11d1-B105-00805F49916B"].ToString();
                }
            }

            var serializer = new XmlSerializer(typeof(Users));
            Users result;

            using (TextReader reader = new StringReader(xml))
            {
                result = (Users)serializer.Deserialize(reader);// here i am not getting xml to in class
            }
        return null;
    }

Body:
User this class for serialization and destabilization

[XmlRoot(ElementName="User")]
    public class User {
        [XmlElement(ElementName="UserId")]
        public string UserId { get; set; }
        [XmlElement(ElementName="Email")]
        public string Email { get; set; }
        [XmlElement(ElementName="UserName")]
        public string UserName { get; set; }
        [XmlElement(ElementName="ProfileImage")]
        public string ProfileImage { get; set; }
        [XmlElement(ElementName="Name")]
        public string Name { get; set; }
        [XmlElement(ElementName="InterestId")]
        public List<string> InterestId { get; set; }
        [XmlElement(ElementName="FeedId")]
        public List<string> FeedId { get; set; }
        [XmlElement(ElementName="Description")]
        public List<string> Description { get; set; }
        [XmlElement(ElementName="Interest")]
        public List<string> Interest { get; set; }
    }

    [XmlRoot(ElementName="Users")]
    public class Users {
        [XmlElement(ElementName="User")]
        public List<User> User { get; set; }
    }


问:
How to run console command in yii2 from web
I have created a console command in console/controllers with SuggestionController .

If i run command like php yii suggestions, its working.

I want to know how to execute console command from web without any extensions of yii2.

答:
I think this is the simplest solution:</p>

```<code>$controller = new SuggestionController(Yii::$app->controller->id, Yii::$app);
$controller->actionSuggestions();
</code>```

Body:
I think this is the simplest solution:

$controller = new SuggestionController(Yii::$app->controller->id, Yii::$app);
$controller->actionSuggestions();


问:
Android : Permission doesn't seems to work and icon doesn't want to display
I have an app that supposed to work on android TV, so befor posting it on App Store I wanted to test it on my own Android TV.

But when I install it I have 3 problemes :

1) I don't know why but my permissions doesn't seems to work

2) My app isn't dipslayed on the menu, you can only find it on settings-->app

3) The icon is the android default icon and not my own icon

Here's my manifest :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.package">

<!-- read sd card -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- write sd card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- internet state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- to disable recent app button -->
<uses-permission android:name="android.permission.REORDER_TASKS" />
<!-- AccountManager -->
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<!-- same -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- don't rember -->
<uses-permission android:name="android.permission.GET_TASKS"/>

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".MainActivity"
        android:banner="@drawable/my_logo_temp"
        android:icon="@drawable/my_logo_temp"
        android:label="@string/app_name"
        android:logo="@drawable/my_logo_temp"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".account.AuthenticatorService"
        android:exported="true"
        android:process=":auth" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/auth" />
    </service>
</application>

</manifest>
</code>```

答:
Put your "logo" icon in the mipmap folder and change the following:

```<code>android:banner="@mipmap/my_logo_temp"
android:icon="@mipmap/my_logo_temp"
android:logo="@mipmap/my_logo_temp"
</code>```

Body:
I have an app that supposed to work on android TV, so befor posting it on App Store I wanted to test it on my own Android TV.

But when I install it I have 3 problemes :

1) I don't know why but my permissions doesn't seems to work

2) My app isn't dipslayed on the menu, you can only find it on settings-->app

3) The icon is the android default icon and not my own icon

Here's my manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.package">

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

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

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

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

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

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

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

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

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

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />
<uses-feature
    android:name="android.software.leanback"
    android:required="true" />
<uses-feature
    android:name="android.hardware.location.gps"
    android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity android:name=".MainActivity"
        android:banner="@drawable/my_logo_temp"
        android:icon="@drawable/my_logo_temp"
        android:label="@string/app_name"
        android:logo="@drawable/my_logo_temp"
        android:screenOrientation="landscape">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".account.AuthenticatorService"
        android:exported="true"
        android:process=":auth" >
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator" />
        </intent-filter>

        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/auth" />
    </service>
</application>

</manifest>

Body:
Put your "logo" icon in the mipmap folder and change the following:

android:banner="@mipmap/my_logo_temp"
android:icon="@mipmap/my_logo_temp"
android:logo="@mipmap/my_logo_temp"


问:
Set HEX string as MQ Correlation ID
I am trying to set the correlation ID of my MQ message as this Hex number:
correlationID = "414d51205350434954495f5550493032115bf458a7180410"
It is initially passed as a string to the function

```<code>        MQMessage msg = new MQMessage();
        byte[] corrID = null;
        corrID = Base64.getDecoder().decode(correlationID);
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
            corrID = msg.correlationId;
            System.out.println(corrID);
            System.out.println(Base64.getEncoder().encodeToString(corrID));

        }
</code>```

This is 48digits long. I've read that the CorrelationID field can hold 24bytes/48hexadecimal digits. But when I try to set the msg.correlationId field, the number gets truncated to only 32 digits. Can you please help me with this?

答:
This is what I did and it worked:</p>

```<code>MQMessage msg = new MQMessage();
        int len = correlationID.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(correlationID.charAt(i),
16) << 4)
                                 +
Character.digit(correlationID.charAt(i+1), 16));
        }
        byte[] corrID = data;
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
        }
</code>```

Title: Set HEX string as MQ Correlation ID

Body:
I am trying to set the correlation ID of my MQ message as this Hex number:
correlationID = "414d51205350434954495f5550493032115bf458a7180410"
It is initially passed as a string to the function

        MQMessage msg = new MQMessage();
        byte[] corrID = null;
        corrID = Base64.getDecoder().decode(correlationID);
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
            corrID = msg.correlationId;
            System.out.println(corrID);
            System.out.println(Base64.getEncoder().encodeToString(corrID));

        }

This is 48digits long. I've read that the CorrelationID field can hold 24bytes/48hexadecimal digits. But when I try to set the msg.correlationId field, the number gets truncated to only 32 digits. Can you please help me with this?

Body:
This is what I did and it worked:

MQMessage msg = new MQMessage();
        int len = correlationID.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(correlationID.charAt(i),
16) << 4)
                                 +
Character.digit(correlationID.charAt(i+1), 16));
        }
        byte[] corrID = data;
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
        }


问:
how to get specific value from array of data coming from modal
I am getting value from modal which contains array as well like this:

```<code>      <?php var_dump( $myaccount);?>
</code>```

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

```<code> if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}
</code>```

答:
//Try this code, it is cleaner and simpler: </p>

```<code>if(!empty($myaccount)){
    foreach($myaccount as $it){
        eval('$ar = '.$it->daysselected.';');
        echo $ar[0];
    }
}
</code>```

Body:
I am getting value from modal which contains array as well like this:

      <?php var_dump( $myaccount);?>

Result:

array (size=1)   0 =>
      object(stdClass)[28]

public 'daysselected' => string '["Monday","Tuesday"]'

public 'due' => string '["2017-06-12","2017-06-13"]'

I am trying to access Monday as single and similarly the date. How can i do so?

I am trying this:

 if(!empty($myaccount)){
     foreach($myaccount as $it){
           echo $it->daysselected[0];//i get '[' only
      }
}

Body:
//Try this code, it is cleaner and simpler:

if(!empty($myaccount)){
    foreach($myaccount as $it){
        eval('$ar = '.$it->daysselected.';');
        echo $ar[0];
    }
}


问:
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'templates/email/test.vm'
My code as follow.

```<code>VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");
</code>```

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ

答:
Try to set below variables and check it should work

```<code>ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,file");
        ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
        ve.setProperty("runtime.log.logsystem.log4j.logger", "VELLOGGER");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
</code>```

And your velocity file should be under resources folder

The above way i have it my project if that not working try this

I believe your folder structure like /src/main/java/com/xyz/email/velocity/.

```<code>ve.velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
  ve.velocityEngine.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName())
</code>```

Body:
My code as follow.

VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ

Body:
Try to set below variables and check it should work

ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,file");
        ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
        ve.setProperty("runtime.log.logsystem.log4j.logger", "VELLOGGER");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");

And your velocity file should be under resources folder

The above way i have it my project if that not working try this

I believe your folder structure like /src/main/java/com/xyz/email/velocity/.

ve.velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
  ve.velocityEngine.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName())


问:
jQuery dropdown menu hover state
My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both. I use this code:

```<code>$("ul li").hover(function () {

    $(this).stop().animate({ backgroundColor: "white"}, 500);

},
function () {

    $(this).stop().animate({ backgroundColor: "black"}, 400);

});

}
</code>```

to animate the background-color on hover in menu and submenu.

I want to change the color of the text on hover to (diferent for menu and submenu, not the same color animation). For this I use this code:(Submenu example, for menu example, change the selector to $('ul.menu li a')

```<code>$('ul.submenu li a').hover(function () {

$(this).css({color:'#FFFFFF'});

},
function () {

$(this).css({color:'#00FF00'});

});
</code>```

All This works fine, but when I hover the submenu the menu returns to the original color state (because the mouseleave is activated on menu hover out).

All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colors dinamically too.

CSS That Works:

```<code>ul li:hover a {
    color: #FFF;
}
</code>```

(with this css code I control the menu color with the css and when I hovered the submenu the menu stays in active state, but the submenu works with jquery .hover).

Can anyone Help? Thanks!

HTML Menu:

```<code><ul class="menu">

      <li><a href="#">text</a></li>

      <li><a href="#">text</a>

        <ul class="submenu">
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
        </ul>

      </li>

      <li><a href="#">text</a>

</ul>
</code>```

答:
If you want hover to set the current color until you hover some other li, use classes.

css:

```<code>ul.submenu li a { color: #0f0; }
ul.submenu li a.hovered { color: #fff; }
</code>```

js:

```<code>$('ul.submenu li a').mouseover( function() {
   if (!$(this).hasClass('hovered')) {
      $('ul.submenu li a.hovered').removeClass('hovered');
      $(this).setClass('hovered');
   }
});
</code>```

I hope I understood you correctly.  Good luck with your project.

[edit]

Oh hm, maybe you want it so when you go off to the submenu, your parent li shouldn't lose its color, despite you mousing out.  If so, the same idea is applicable, you'd just want that mouseover code to select on the menu item mouseover (so mousing over the menu unsets all other menus and sets this one), then you just also need to have it remove your menu's class color if you mouse out of its submenu's ul.  I don't know what your menus look like structure-wise, so I can't comment on a working CSS for this selector.

Oh and finally you'd want to have a css rule vs. submenu hover to handle your submenu's highlighting.

Sorry for the rambling answer...

Title: jQuery dropdown menu hover state

Body:
My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both. I use this code:

$("ul li").hover(function () {

    $(this).stop().animate({ backgroundColor: "white"}, 500);

},
function () {

    $(this).stop().animate({ backgroundColor: "black"}, 400);

});

}

to animate the background-color on hover in menu and submenu.

I want to change the color of the text on hover to (diferent for menu and submenu, not the same color animation). For this I use this code:(Submenu example, for menu example, change the selector to $('ul.menu li a')

$('ul.submenu li a').hover(function () {

$(this).css({color:'#FFFFFF'});

},
function () {

$(this).css({color:'#00FF00'});

});

All This works fine, but when I hover the submenu the menu returns to the original color state (because the mouseleave is activated on menu hover out).

All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colors dinamically too.

CSS That Works:

ul li:hover a {
    color: #FFF;
}

(with this css code I control the menu color with the css and when I hovered the submenu the menu stays in active state, but the submenu works with jquery .hover).

Can anyone Help? Thanks!

HTML Menu:

text

text

text

text

text

text

Body:
If you want hover to set the current color until you hover some other li, use classes.

css:

ul.submenu li a { color: #0f0; }
ul.submenu li a.hovered { color: #fff; }

js:

$('ul.submenu li a').mouseover( function() {
   if (!$(this).hasClass('hovered')) {
      $('ul.submenu li a.hovered').removeClass('hovered');
      $(this).setClass('hovered');
   }
});

I hope I understood you correctly.  Good luck with your project.

[edit]

Oh hm, maybe you want it so when you go off to the submenu, your parent li shouldn't lose its color, despite you mousing out.  If so, the same idea is applicable, you'd just want that mouseover code to select on the menu item mouseover (so mousing over the menu unsets all other menus and sets this one), then you just also need to have it remove your menu's class color if you mouse out of its submenu's ul.  I don't know what your menus look like structure-wise, so I can't comment on a working CSS for this selector.

Oh and finally you'd want to have a css rule vs. submenu hover to handle your submenu's highlighting.

Sorry for the rambling answer...


问:
laravel like query is not working?
This is my code :

```<code> $lists = DB::table('connection_request as cr')
                    ->leftJoin('users as u', function($join)
                         {
                             $join->on('u.id', '=', 'cr.sender_id')->orOn('u.id','=', 'cr.receiver_id');
                         })
                    ->select('cr.id as connection_id','cr.sender_id as sen_id','cr.receiver_id as rec_id','cr.approve_status','u.id','u.user_type','u.user_type_id',DB::raw("IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar"),'u.name','u.email')
                    ->where(function($query) use ($user_id)
                        {
                        if(!empty($user_id)):
                            $query->Where('cr.receiver_id','=', $user_id);
                        endif;
                        if(!empty($user_id)):
                            $query->orWhere('cr.sender_id','=', $user_id);
                        endif;
                     })
                    ->where(function($query) use ($searchValue)
                        {
                        if(!empty($searchValue)):
                           $query->Where('u.name','like', '%' . $searchValue . '%');
                           $query->orWhere('u.email','like', '%' . $searchValue . '%');
                        endif;
                     })
                    ->where('cr.approve_status','=',1)
                    ->where('u.id','!=',$user_id)
                    ->get();
</code>```

and it provide mysql query like this

```<code>select `cr`.`id` as `connection_id`, `cr`.`sender_id` as `sen_id`, `cr`.`receiver_id` as `rec_id`, `cr`.`approve_status`, `u`.`id`, `u`.`user_type`, `u`.`user_type_id`, IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar, `u`.`name`, `u`.`email` from `connection_request` as `cr` left join `users` as `u` on `u`.`id` = `cr`.`sender_id` or `u`.`id` = `cr`.`receiver_id` where (`cr`.`receiver_id` = 10 or `cr`.`sender_id` = 10) and (`u`.`name` LIKE 'pri' or `u`.`email` LIKE 'pri') and `cr`.`approve_status` = 1 and `u`.`id` != 10
</code>```

So, I can't able to get result because after like it should have % symbol but, generate laravel query not having percentage symbol

my below raw query is working perfect

```<code>select `cr`.`id` as `connection_id`, `cr`.`sender_id` as `sen_id`, `cr`.`receiver_id` as `rec_id`, `cr`.`approve_status`, `u`.`id`, `u`.`user_type`, `u`.`user_type_id`, IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar, `u`.`name`, `u`.`email` from `connection_request` as `cr` left join `users` as `u` on `u`.`id` = `cr`.`sender_id` or `u`.`id` = `cr`.`receiver_id` where (`cr`.`receiver_id` = 10 or `cr`.`sender_id` = 10) and (`u`.`name` LIKE '%pri%' or `u`.`email` LIKE '%pri%') and `cr`.`approve_status` = 1 and `u`.`id` != 10
</code>```

Please check and help me guys,

Thanks

答:
Personally, I use that and it works rather well ...</p>

```<code>$query->where('u.name','LIKE', "%{$searchValue}%")->get();
</code>```

Title: laravel like query is not working?

Body:
This is my code :

 $lists = DB::table('connection_request as cr')
                    ->leftJoin('users as u', function($join)
                         {
                             $join->on('u.id', '=', 'cr.sender_id')->orOn('u.id','=', 'cr.receiver_id');
                         })
                    ->select('cr.id as connection_id','cr.sender_id as sen_id','cr.receiver_id as rec_id','cr.approve_status','u.id','u.user_type','u.user_type_id',DB::raw("IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar"),'u.name','u.email')
                    ->where(function($query) use ($user_id)
                        {
                        if(!empty($user_id)):
                            $query->Where('cr.receiver_id','=', $user_id);
                        endif;
                        if(!empty($user_id)):
                            $query->orWhere('cr.sender_id','=', $user_id);
                        endif;
                     })
                    ->where(function($query) use ($searchValue)
                        {
                        if(!empty($searchValue)):
                           $query->Where('u.name','like', '%' . $searchValue . '%');
                           $query->orWhere('u.email','like', '%' . $searchValue . '%');
                        endif;
                     })
                    ->where('cr.approve_status','=',1)
                    ->where('u.id','!=',$user_id)
                    ->get();

and it provide mysql query like this

select `cr`.`id` as `connection_id`, `cr`.`sender_id` as `sen_id`, `cr`.`receiver_id` as `rec_id`, `cr`.`approve_status`, `u`.`id`, `u`.`user_type`, `u`.`user_type_id`, IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar, `u`.`name`, `u`.`email` from `connection_request` as `cr` left join `users` as `u` on `u`.`id` = `cr`.`sender_id` or `u`.`id` = `cr`.`receiver_id` where (`cr`.`receiver_id` = 10 or `cr`.`sender_id` = 10) and (`u`.`name` LIKE 'pri' or `u`.`email` LIKE 'pri') and `cr`.`approve_status` = 1 and `u`.`id` != 10

So, I can't able to get result because after like it should have % symbol but, generate laravel query not having percentage symbol

my below raw query is working perfect

select `cr`.`id` as `connection_id`, `cr`.`sender_id` as `sen_id`, `cr`.`receiver_id` as `rec_id`, `cr`.`approve_status`, `u`.`id`, `u`.`user_type`, `u`.`user_type_id`, IF(u.avatar = '', 'uploads/avatar/default.jpg', u.avatar) as avatar, `u`.`name`, `u`.`email` from `connection_request` as `cr` left join `users` as `u` on `u`.`id` = `cr`.`sender_id` or `u`.`id` = `cr`.`receiver_id` where (`cr`.`receiver_id` = 10 or `cr`.`sender_id` = 10) and (`u`.`name` LIKE '%pri%' or `u`.`email` LIKE '%pri%') and `cr`.`approve_status` = 1 and `u`.`id` != 10

Please check and help me guys,

Thanks

Body:
Personally, I use that and it works rather well ...

$query->where('u.name','LIKE', "%{$searchValue}%")->get();


问:
Camel file unit test
I am new to Apache Camel, I have written a simple route to scan a directory (/test), file will be processed when it was copied into the directory. Anyone has an idea on how to write a camel unit test to test the following route? Is there a way to mock the process of copying the file into the /test directory so that the route will be triggered.</p>

```<code>public void configure() {
    from( "file:/test?preMove=IN_PROGRESS" +
          "&move=completed/${date:now:yyyyMMdd}/${file:name}" +
          "&moveFailed=FAILED/${file:name.noext}-${date:now:yyyyMMddHHmmssSSS}.${file:ext}" )
    .process(new Processor() {
          public void process(Exchange exchange) throws IOException {
              File file = (File) exchange.getIn().getBody();
              // read file content ......
          }
    });
}
</code>```

答:
I think the basic idea is that you mock the end endpoint so you can check what is coming out your route. There are a few different ways, but you could test your route as follows:

```<code>public class MyRouteTest extends CamelSpringTestSupport {

    private static final String INPUT_FILE = "myInputFile.xml";

    private static final String URI_START = "direct:start";

    private static final String URI_END = "mock:end";

    @Override
    public boolean isUseAdviceWith() {
        return true;
    }

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return new AnnotationConfigApplicationContext(CamelTestConfig.class); // this is my Spring test config, where you wire beans
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        MyRoute route = new MyRoute();
        route.setFrom(URI_START); // I have added getter and setters to MyRoute so I can mock 'start' and 'end'
        route.setTo(URI_END);
        return route;
    }

    @Test
    public void testMyRoute() throws Exception {

        MockEndpoint result = getMockEndpoint(URI_END);
        context.start();

        // I am just checking I receive 5 messages, but you should actually check the content with expectedBodiesReceived() depending on what your processor does to the those files.

        result.expectedMessageCount(5);

        // I am just sending the same file 5 times
        for (int i = 0; i < 5; i++) {
            template.sendBody(URI_START, getInputFile(INPUT_FILE));
        }

        result.assertIsSatisfied();
        context.stop();
    }

    private File getInputFile(String name) throws URISyntaxException, IOException {
        return FileUtils.getFile("src", "test", "resources", name);
    }
</code>```

I am sure you already solved your issue is 2013, but this is how I would solve it in 2017. Regards

Title: Camel file unit test

Body:
I am new to Apache Camel, I have written a simple route to scan a directory (/test), file will be processed when it was copied into the directory. Anyone has an idea on how to write a camel unit test to test the following route? Is there a way to mock the process of copying the file into the /test directory so that the route will be triggered.

public void configure() {
    from( "file:/test?preMove=IN_PROGRESS" +
          "&move=completed/${date:now:yyyyMMdd}/${file:name}" +
          "&moveFailed=FAILED/${file:name.noext}-${date:now:yyyyMMddHHmmssSSS}.${file:ext}" )
    .process(new Processor() {
          public void process(Exchange exchange) throws IOException {
              File file = (File) exchange.getIn().getBody();
              // read file content ......
          }
    });
}

Body:
I think the basic idea is that you mock the end endpoint so you can check what is coming out your route. There are a few different ways, but you could test your route as follows:

public class MyRouteTest extends CamelSpringTestSupport {

    private static final String INPUT_FILE = "myInputFile.xml";

    private static final String URI_START = "direct:start";

    private static final String URI_END = "mock:end";

    @Override
    public boolean isUseAdviceWith() {
        return true;
    }

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        return new AnnotationConfigApplicationContext(CamelTestConfig.class); // this is my Spring test config, where you wire beans
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        MyRoute route = new MyRoute();
        route.setFrom(URI_START); // I have added getter and setters to MyRoute so I can mock 'start' and 'end'
        route.setTo(URI_END);
        return route;
    }

    @Test
    public void testMyRoute() throws Exception {

        MockEndpoint result = getMockEndpoint(URI_END);
        context.start();

        // I am just checking I receive 5 messages, but you should actually check the content with expectedBodiesReceived() depending on what your processor does to the those files.

        result.expectedMessageCount(5);

        // I am just sending the same file 5 times
        for (int i = 0; i < 5; i++) {
            template.sendBody(URI_START, getInputFile(INPUT_FILE));
        }

        result.assertIsSatisfied();
        context.stop();
    }

    private File getInputFile(String name) throws URISyntaxException, IOException {
        return FileUtils.getFile("src", "test", "resources", name);
    }

I am sure you already solved your issue is 2013, but this is how I would solve it in 2017. Regards


问:
MySQL using "-" as different
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

```<code>delete from <table> where id - 145;
</code>```

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

答:
try select * from mytable where 3;

Basically any non-zero value will be equivalent to true.   This is also the case in many languages:  I first came across this behaviour in the C language many years ago, while puzzling at the marvel of

while (*p++ = *q++);  which is used to copy character strings.

Title: MySQL using "-" as different

Body:
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

delete from
 where id - 145;

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?


问:
How to Click the label element in selenium
```<code>WebDriver driver=new FirefoxDriver();
driver.get("http://192.168.0.133/tiyorelease3");
driver.findElement(By.id("login_button")).click();
driver.findElement(By.id("login_button")).click();
driver.findElement(By.xpath("id(//label[text() = 'signup']/@for)")).click();
driver.close();
</code>```

答:
You can try following code:-</p>

```<code>WebDriver driver=new FirefoxDriver();
driver.get("http://192.168.0.133/tiyorelease3");
driver.findElement(By.id("login_button")).click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='login-form']/div[1]/ul/li[2]/label").click();
</code>```

Body:
You can try following code:-

WebDriver driver=new FirefoxDriver();
driver.get("http://192.168.0.133/tiyorelease3");
driver.findElement(By.id("login_button")).click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id='login-form']/div[1]/ul/li[2]/label").click();


问:
Perl Regex match incorrect
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.</p>

```<code>my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }
</code>```

答:
Try This. This will give you perfect result.

my $content = "The 39 Steps - a GREAT book - colours_15";

```<code>if($content =~m /\b([A-Z]+)\b/){
    print "Matched $1\n";
}
else{
    print "No match\n";
}
</code>```

Title: Perl Regex match incorrect

Body:
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.

my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }

Body:
Try This. This will give you perfect result.

my $content = "The 39 Steps - a GREAT book - colours_15";

if($content =~m /\b([A-Z]+)\b/){
    print "Matched $1\n";
}
else{
    print "No match\n";
}


问:
simple authorisation / login capability in php
I'm looking to implement user login onto my site for the first time.  I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far.  Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss something obvious if I roll my own solution, and leave the doors well and truly open.

Any suggestions?  We're not talking super sensitive or payment data here, but equally, I'm keen not to have people mess up my site!

requirements are
- php based
- simple as possible, not need for fancy bells and whistles
- not Zend framework, since i've now rolled my own very basic frameworkthanks to this post

Thanks for your input.

答:
A few good security gotcha's are

never store the an un-encrypted users password in the database

never store the users password or even a hash of the password in session or cookie data.

If you need to have ensure that the login is secure you have to use https.

I found these article very helpful in building login systems with cookies:

blog post on the fishbowl.

Improved Persistent Login Cookie Best Practice

OwnerDisplayName: Rob Y

OwnerDisplayName: Brian Fisher


问:
Codeigniter - Adding Code to Constructor without affected to Specific Controller Function
Short Version of this question

How to write something like this (if(Controller Function is Not "Login()" Function)) in Codeigniter Constructor?

```<code>if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}
</code>```

Long Version of this question if is not clear the short version

This is Admin controller of my codeigniter project

```<code>class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        /**
        *
        *
        *  Here - I am going to check session is set or not.....
        *
        *
        */

    }

    public function login(){

    }

    public function update(){

    }

    public function edit(){

    }

    public function insert(){

    }

        /**
        *
        *
        *  And Many More Functions
        *
        *
        */

}
</code>```

I am going to add following code part to constructor.

```<code>if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}
</code>```

When I write this even I can't go to the login() function without session. How to write above code in constructor which not affect to the login function.

I am looking something like this,

```<code>if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}
</code>```

答:
1.Set default controller is login

```<code>function __construct()
{
    if(!($this->session->has_userdata('user_id')) && $this->router->fetch_method() != "login"){
        redirect(base_url());
    }
}
</code>```

2.If not set default controller as login

```<code>function __construct()
{
    if(!($this->session->has_userdata('user_id'))&& $this->router->fetch_method() != "login"){
        redirect(base_url()."login");
    }
}
</code>```

Body:
Short Version of this question

How to write something like this (if(Controller Function is Not "Login()" Function)) in Codeigniter Constructor?

if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}

Long Version of this question if is not clear the short version

This is Admin controller of my codeigniter project

class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        /**
        *
        *
        *  Here - I am going to check session is set or not.....
        *
        *
        */

    }

    public function login(){

    }

    public function update(){

    }

    public function edit(){

    }

    public function insert(){

    }

        /**
        *
        *
        *  And Many More Functions
        *
        *
        */

}

I am going to add following code part to constructor.

if(empty($this->session->userdata('user_id'))){
    redirect(base_url());
}

When I write this even I can't go to the login() function without session. How to write above code in constructor which not affect to the login function.

I am looking something like this,

if(Controller Function is Not "Login()" Function)
{
    if(empty($this->session->userdata('user_id'))){
        redirect(base_url());
    }
}

Body:
1.Set default controller is login

function __construct()
{
    if(!($this->session->has_userdata('user_id')) && $this->router->fetch_method() != "login"){
        redirect(base_url());
    }
}

2.If not set default controller as login

function __construct()
{
    if(!($this->session->has_userdata('user_id'))&& $this->router->fetch_method() != "login"){
        redirect(base_url()."login");
    }
}