问:
jboss-cli : How do I read one specific system property using jboss-cli?
I'm new to jboss-cli and working through the 'jboss-cli recipes'.

Question

How do I read one specific property using jboss-cli? E.g.

jboss.home.dir (e.g. "-Djboss.home.dir=/path/to/my/jboss")

Xmx ("-Xmx=4G")

Context

The "CLI Recipes" documentation has this helpful example to get all system properties. However its 'too much infomration'. I want to script reading one specific property.

https://docs.jboss.org/author/display/WFLY10/CLI+Recipes#CLIRecipes-

Overview of all system properties in JBoss AS7+ including OS system
  properties and properties specified on command line using -D, -P or
  --properties arguments.

```<code>Standalone
[standalone@IP_ADDRESS:9999 /] /core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)
</code>```

Thanks in advance

答:
This link pointed me to the answer: I can use a groovy script to get the values. From what I see the "jboss-cli command line" does not offer this flexibility.

https://developer.jboss.org/wiki/AdvancedCLIScriptingWithGroovyRhinoJythonEtc

Solution

Here's a solution for jboss home.

[For memory you can get results from "/core-service=platform-mbean/type=memory/:read-attribute(name=heap-memory-usage)"

bash

```<code>#!/bin/sh
# Note: must set jbbin to 'jboss home /bin'
groovy -cp $jbbin/client/jboss-cli-client.jar readJbossHome.groovy
</code>```

Groovy
Note: this is 'quick and dirty'.

```<code>import org.jboss.as.cli.scriptsupport.*

cli = CLI.newInstance()
cli.connect()

// Define properties
myParentProp="system-properties"
myProp="jboss.home.dir"

// Retrieve and pluck values
result = cli.cmd("/core-service=platform-mbean/type=runtime:read-resource(recursive=true,include-runtime=false)")

myResult = result.getResponse().get("result")
myParentVal = myResult.get(myParentProp)
myVal = myParentVal.get(myProp)

// Print out results
println "Property detail ${myProp}  is ${myVal}"

cli.disconnect()
</code>```

Body:
I'm new to jboss-cli and working through the 'jboss-cli recipes'.

Question

How do I read one specific property using jboss-cli? E.g.

jboss.home.dir (e.g. "-Djboss.home.dir=/path/to/my/jboss")

Xmx ("-Xmx=4G")

Context

The "CLI Recipes" documentation has this helpful example to get all system properties. However its 'too much infomration'. I want to script reading one specific property.

https://docs.jboss.org/author/display/WFLY10/CLI+Recipes#CLIRecipes-

Overview of all system properties in JBoss AS7+ including OS system
  properties and properties specified on command line using -D, -P or
  --properties arguments.

Standalone
[standalone@IP_ADDRESS:9999 /] /core-service=platform-mbean/type=runtime:read-attribute(name=system-properties)

Thanks in advance

Body:
This link pointed me to the answer: I can use a groovy script to get the values. From what I see the "jboss-cli command line" does not offer this flexibility.

https://developer.jboss.org/wiki/AdvancedCLIScriptingWithGroovyRhinoJythonEtc

Solution

Here's a solution for jboss home.

[For memory you can get results from "/core-service=platform-mbean/type=memory/:read-attribute(name=heap-memory-usage)"

bash

#!/bin/sh
# Note: must set jbbin to 'jboss home /bin'
groovy -cp $jbbin/client/jboss-cli-client.jar readJbossHome.groovy

Groovy
Note: this is 'quick and dirty'.

import org.jboss.as.cli.scriptsupport.*

cli = CLI.newInstance()
cli.connect()

// Define properties
myParentProp="system-properties"
myProp="jboss.home.dir"

// Retrieve and pluck values
result = cli.cmd("/core-service=platform-mbean/type=runtime:read-resource(recursive=true,include-runtime=false)")

myResult = result.getResponse().get("result")
myParentVal = myResult.get(myParentProp)
myVal = myParentVal.get(myProp)

// Print out results
println "Property detail ${myProp}  is ${myVal}"

cli.disconnect()


来源: stackexchange

问:
Flash upload image resize client side
Does anyone got an ideia on how to get client side image resize using flash.

Example:
Client chooses an image with 1200x800 and before it uploads it flash will turn it into half of it or something.

Any thoughts?

答:
Silverlight, ActiveX and Java can do this completely client-side. If you have to use Flash you are going to need to use Flash 10 which isn't prevalent quite yet. Here is an example on uploading an image to Flash then resizing it on the client from Flash Cafe.

Other options in Flash 8 or 9 would involve a server-side resizing script, defeating the purpose in most scenarios.

OwnerDisplayName: Hugo Gameiro

ContentLicense: CC BY-SA 2.5

Title: Flash upload image resize client side

OwnerDisplayName: David Thomas Garcia


问:
How do I set the namespace URI in c#?
Im using a namespace in my xml (I need to use this for xsd validation purposes). Because of this my xpath is no longer working.

I have the code:

```<code>XmlDocument doc = new XmlDocument();
doc.Load(newXmlFilePath);
</code>```

And the XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

But my xpath doesnt select the node. I tried to set the namespace using:

```<code>doc.NamespaceUR = "x";
</code>```

However its a get only accessor. Any ideas?

答: Check out this Microsoft How To: http://support.microsoft.com/kb/318545</p>

Title: How do I set the namespace URI in c#?

Body:
Im using a namespace in my xml (I need to use this for xsd validation purposes). Because of this my xpath is no longer working.

I have the code:

XmlDocument doc = new XmlDocument();
doc.Load(newXmlFilePath);

And the XML:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

But my xpath doesnt select the node. I tried to set the namespace using:

doc.NamespaceUR = "x";

However its a get only accessor. Any ideas?


问:
Apache-Spark: Nested for-comprehensions for RDDs
I am trying to do the Spark-RDD equivalent of this local Scala code:

```<code>val intList1=List(1,2,3,4,5,6)
val intList2=List(10,20,30,40,50,60)

val divisiblePairs=for(
    int1<-intList1;
    int2<-intList2
    if int2 % int1 == 0
) yield(int1,int2)

divisiblePairs.groupBy(_._1) //Map(6 -> List((6,30), (6,60)),...)
</code>```

I tried:

```<code>val intRDD1=sc.parallelize(List(1,2,3,4,5,6))
val intRDD2=sc.parallelize(List(10,20,30,40,50,60))

val divisiblePairs=
for(
    int1<-intRDD1;
    int2<-intRDD2
    if int2 % int1 == 0
) yield(int1,int2)
</code>```

which would need some extra work, but I am getting errors, even in the body of the for-comprehension:

error: type mismatch;  found   :
  org.apache.spark.rdd.RDD[(Int, Int)]  required: TraversableOnce[?]
             int2<-intList2

答:
The error is to be expected because Spark doesn't support nesting. You can use cartesian method to do the same thing:

```<code>for {
  (int1, int2) <- intRDD1.cartesian(intRDD2)
  if int2 % int1 == 0
} yield(int1, int2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to do the Spark-RDD equivalent of this local Scala code:

val intList1=List(1,2,3,4,5,6)
val intList2=List(10,20,30,40,50,60)

val divisiblePairs=for(
    int1<-intList1;
    int2<-intList2
    if int2 % int1 == 0
) yield(int1,int2)

divisiblePairs.groupBy(_._1) //Map(6 -> List((6,30), (6,60)),...)

I tried:

val intRDD1=sc.parallelize(List(1,2,3,4,5,6))
val intRDD2=sc.parallelize(List(10,20,30,40,50,60))

val divisiblePairs=
for(
    int1<-intRDD1;
    int2<-intRDD2
    if int2 % int1 == 0
) yield(int1,int2)

which would need some extra work, but I am getting errors, even in the body of the for-comprehension:

error: type mismatch;  found   :
  org.apache.spark.rdd.RDD[(Int, Int)]  required: TraversableOnce[?]
             int2<-intList2

Body:
The error is to be expected because Spark doesn't support nesting. You can use cartesian method to do the same thing:

for {
  (int1, int2) <- intRDD1.cartesian(intRDD2)
  if int2 % int1 == 0
} yield(int1, int2)


问:
How to Store Previous Value Of Loop in variable
JSONObject jsonRoot = new JSONObject(response);

```<code>    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}
</code>```

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

答:
Try this, I guess you have an User entity</p>

```<code>List<User> userList = new ArrayList<String>();
for (int j = 0; j <parentArray.length(); j++) {
        JSONObject finalObject = parentArray.getJSONObject(j);
        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");
        userList.add(user);
}
for(String k: userList)
        {
            System.out.println(k);
        }
return userList
</code>```

Body:
JSONObject jsonRoot = new JSONObject(response);

    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

Body:
Try this, I guess you have an User entity

List<User> userList = new ArrayList<String>();
for (int j = 0; j <parentArray.length(); j++) {
        JSONObject finalObject = parentArray.getJSONObject(j);
        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");
        userList.add(user);
}
for(String k: userList)
        {
            System.out.println(k);
        }
return userList


问:
BroadcastReceiver "action.USER_PRESENT" is not called
I'm trying to register the device unlock event. I use the receiver with action = "android.intent.action.USER_PRESENT".

When the application is active - everything works. When I delete an application from the curtain of recently launched - does not work. And this problem is noticeable with API21 (on 4.4. - everything works). This is expected, because Google from API21 seriously engaged in optimizing the work of background applications, but how does this receiver work? Code of manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appdroid.develop.receiverscreenlock">
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".ScreenReceiver">
        <intent-filter android:priority="2147483647">
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
</application>
</code>```

Class code:

```<code>public class ScreenReceiver extends BroadcastReceiver {

private static final String TAG = "myLog";

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG,"onReceive "+ intent.getAction());
    Toast.makeText(context,"screen unlock",Toast.LENGTH_SHORT).show();
}}
</code>```

答:
Someone report that setting in manifest does not help, so try to sse this in your onCreate method:

```<code>receiver = new ScreenReceiver()
IntentFilter i=new IntentFilter(Intent.ACTION_SCREEN_OFF);
        i.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(receiver ,i);
</code>```

You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver() source, so I think you cannot receive if your app is killed.

However you can use service:

```<code>public static class UpdateService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            // register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
        }

        @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                // your code
            } else {
                // your code
            }
        }
}
</code>```

Body:
I'm trying to register the device unlock event. I use the receiver with action = "android.intent.action.USER_PRESENT".

When the application is active - everything works. When I delete an application from the curtain of recently launched - does not work. And this problem is noticeable with API21 (on 4.4. - everything works). This is expected, because Google from API21 seriously engaged in optimizing the work of background applications, but how does this receiver work? Code of manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.appdroid.develop.receiverscreenlock">
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".ScreenReceiver">
        <intent-filter android:priority="2147483647">
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
    </receiver>
</application>

Class code:

public class ScreenReceiver extends BroadcastReceiver {

private static final String TAG = "myLog";

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG,"onReceive "+ intent.getAction());
    Toast.makeText(context,"screen unlock",Toast.LENGTH_SHORT).show();
}}

Body:
Someone report that setting in manifest does not help, so try to sse this in your onCreate method:

receiver = new ScreenReceiver()
IntentFilter i=new IntentFilter(Intent.ACTION_SCREEN_OFF);
        i.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(receiver ,i);

You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver() source, so I think you cannot receive if your app is killed.

However you can use service:

public static class UpdateService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            // register receiver that handles screen on and screen off logic
            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
        }

        @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                // your code
            } else {
                // your code
            }
        }
}


问:
Specifying column name in a "references" migration
I want to make a migration in Rails, referencing another table. Usually, I would do something like:

```<code>add_column :post, :user, :references
</code>```

This creates a column named user_id in posts table. But what if, instead of user_id, I want something like author_id? How can I do that?

答:
alias_attribute(new_name, old_name) is very handy.
Just create your model and the relationship:

```<code>rails g model Post title user:references
</code>```

then edit the model and add an attribute alias with

```<code>alias_attribute :author, :user
</code>```

After that you'll be able to run things like

```<code>Post.new(title: 'My beautiful story', author: User.first)
</code>```

Body:
I want to make a migration in Rails, referencing another table. Usually, I would do something like:

add_column :post, :user, :references

This creates a column named user_id in posts table. But what if, instead of user_id, I want something like author_id? How can I do that?

Body:
alias_attribute(new_name, old_name) is very handy.
Just create your model and the relationship:

rails g model Post title user:references

then edit the model and add an attribute alias with

alias_attribute :author, :user

After that you'll be able to run things like

Post.new(title: 'My beautiful story', author: User.first)


问:
Main class instance for all subclasses
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

```<code>// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}
</code>```

答:
In your account class you must call bank constructor because account extends bank and there is no default (no argument) constructor.
Do something like this:</p>

```<code>super(coin)
</code>```

Title: Main class instance for all subclasses

Body:
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}

Body:
In your account class you must call bank constructor because account extends bank and there is no default (no argument) constructor.
Do something like this:

super(coin)


问:
Property 'push' does not exist on type 'Promise<any[]>' with | async

"Property 'push' does not exist on thype 'IHero[] | Promise'. Property does not exist on type 'Promise'

Why the heck not? isn't it an array?

Going through the Tour of Heroes with Angular 4 in an angular-cli project. I'm using the async pipe for the repeater instead of the official tutorial's method.
https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

heroes.component.ts

```<code>export class HeroesComponent implements OnInit {
    heroes: IHero[]|Promise<IHero[]> = [];
    selectedHero: IHero;

    constructor(private _heroService: HeroService, private _router: Router)

    ngOnInit() {
        this.heroes = this._heroService.getHeroes();
    }

    add(name: string): void {
        name = name.trim();
        if (!name) { return; }
        this._heroService.create(name)
            .then(hero => {
                this.heroes.push(hero); // RED SQUIGGLY ERROR HERE "Property 'push' does not exist on thype 'IHero[] | Promise<IHero[]>'. Property does not exist on type 'Promise<IHero[]>'"
            });
    }
}
</code>```

hero.service.ts

```<code>...
getHeroes(): Promise<IHero[]> {
    return this._http.get(this.heroesUrl)
        .toPromise()
        .then( res => res.json().data as IHero[] )
        .catch( this._handleError)
}
...
</code>```

If I console.log out the this.heroes on init, I can see it is a ZoneAwarePromise....

How can I get the .push to work on this?

If I use a traditional .then method, then the | async pipe errors. out.

Wall of Errors ensues...

答:
```<code>ngOnInit() {
    this.heroes = this._heroService.getHeroes();
}
</code>```

should be

```<code>ngOnInit() {
    this._heroService.getHeroes().then(val => this.heroes = val);
}
</code>```

With your code you assign a Promise which doesn't have a push method.

Body:
"Property 'push' does not exist on thype 'IHero[] | Promise'. Property does not exist on type 'Promise'

Why the heck not? isn't it an array?

Going through the Tour of Heroes with Angular 4 in an angular-cli project. I'm using the async pipe for the repeater instead of the official tutorial's method.
https://angular.io/docs/ts/latest/tutorial/toh-pt6.html

heroes.component.ts

export class HeroesComponent implements OnInit {
    heroes: IHero[]|Promise<IHero[]> = [];
    selectedHero: IHero;

    constructor(private _heroService: HeroService, private _router: Router)

    ngOnInit() {
        this.heroes = this._heroService.getHeroes();
    }

    add(name: string): void {
        name = name.trim();
        if (!name) { return; }
        this._heroService.create(name)
            .then(hero => {
                this.heroes.push(hero); // RED SQUIGGLY ERROR HERE "Property 'push' does not exist on thype 'IHero[] | Promise<IHero[]>'. Property does not exist on type 'Promise<IHero[]>'"
            });
    }
}

hero.service.ts

...
getHeroes(): Promise<IHero[]> {
    return this._http.get(this.heroesUrl)
        .toPromise()
        .then( res => res.json().data as IHero[] )
        .catch( this._handleError)
}
...

If I console.log out the this.heroes on init, I can see it is a ZoneAwarePromise....

How can I get the .push to work on this?

If I use a traditional .then method, then the | async pipe errors. out.

Wall of Errors ensues...

Body:
ngOnInit() {
    this.heroes = this._heroService.getHeroes();
}

should be

ngOnInit() {
    this._heroService.getHeroes().then(val => this.heroes = val);
}

With your code you assign a Promise which doesn't have a push method.


问:
How can I insert code into :

here

 ..that will spawn a sized window.
cant get this to work (can I not have JS call from inside list tags?)
Thanks!!!

Helping Kids Who Struggle

```
</div>
</div>

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>..etc

,,but works fine when not in <li>
Thanks!!!</code>```

答:
I would advise you to use the jquery library for this solution. In order to use jquery you have to include the jquery files using a CDN or locally. I use a CDN.

```<code><script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</code>```

You can set up a jquery event listener so that once a list item is clicked, an event is executed. For example;

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>List Click</title>

<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include the jQuery library -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
<ul id="group">
    <li id="one">One</li>
    <li id="two">Two</li>
    <li id="three">Three</li>
    <li id="four">Four</li>
    <li id="five">Five</li>
</ul>
<script>
    $( "#group li" ).bind( "click", function() {
          var selected_item = $(this).attr('id');
            if(selected_item == "one"){
             window.open('helpingkidswhostruggle.html','name','width=600,height=450');
            }
});
</script>
</body>
</html>
</code>```

So to explain the code;

You must assign id attributes to the ul and li tags.

The $( "#group li" ).bind( "click", function() { code looks for the list items with tags of li enclosed in an element with an id of group and assigns a click listener to them so that when they are clicked, a function is called and executed.

The var selected_item = $(this).attr('id'); code uses the attr('id') method to obtain the id of the clicked list item and assign it to variable selected_item. So now this is the use of assigning an id to the list items so that you can identify them.

This if(selected_item == "one"){ code of course checks to see which item has been clicked and the action to take if it has. You can play around with this and see what works for you.

Do not forget to include the jquery files otherwise the code will not work.

Try it and let me know if it helps or if you found a problem

Body:
cant get this to work (can I not have JS call from inside list tags?)
Thanks!!!

Helping Kids Who Struggle

..etc

,,but works fine when not in

Thanks!!!

Body:
I would advise you to use the jquery library for this solution. In order to use jquery you have to include the jquery files using a CDN or locally. I use a CDN.

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

You can set up a jquery event listener so that once a list item is clicked, an event is executed. For example;

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>List Click</title>

<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include the jQuery library -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
<ul id="group">
    <li id="one">One</li>
    <li id="two">Two</li>
    <li id="three">Three</li>
    <li id="four">Four</li>
    <li id="five">Five</li>
</ul>
<script>
    $( "#group li" ).bind( "click", function() {
          var selected_item = $(this).attr('id');
            if(selected_item == "one"){
             window.open('helpingkidswhostruggle.html','name','width=600,height=450');
            }
});
</script>
</body>
</html>

So to explain the code;

You must assign id attributes to the ul and li tags.

The $( "#group li" ).bind( "click", function() { code looks for the list items with tags of li enclosed in an element with an id of group and assigns a click listener to them so that when they are clicked, a function is called and executed.

The var selected_item = $(this).attr('id'); code uses the attr('id') method to obtain the id of the clicked list item and assign it to variable selected_item. So now this is the use of assigning an id to the list items so that you can identify them.

This if(selected_item == "one"){ code of course checks to see which item has been clicked and the action to take if it has. You can play around with this and see what works for you.

Do not forget to include the jquery files otherwise the code will not work.

Try it and let me know if it helps or if you found a problem


问:
Logstash - sleep until there is a specific message
In Logstash, let's say I have the following lines in my logs:

```<code>Message: msisdn: 111111111
Message: msisdn: 222222222
Answer: msisdn: 111111111
Answer: msisdn: 222222222
</code>```

Now, whenever I get the Message, I'd like to wait for X seconds.
If within this time period I get the matching Answer (i.e. with the same msisdn), mark it as OK, else mark it as ERROR.

How can I do that?

Thanks

```<code>**EDIT**
</code>```

Fairy, I tried to work with the aggregate filter but with no success, can you please help me with that?

```<code>input {
  stdin {}
}

filter {
  grok {
    match => {"message" => "%{GREEDYDATA:type}: msisdn: %{INT:msisdn}"}
  }

  if [type] == "Message" {
    aggregate {
      task_id => "%{msisdn}"
      code => "event.set('result', 'OK')"
      timeout => 5
      timeout_code => "event.set('result', 'error')"
    }
  }

  if [logger] == "Answer" {
    aggregate {
      task_id => "%{msisdn}"
      code => "event.set('result', 'OK')"
      end_of_task => true
    }
  }

  if "_grokparsefailure" in [tags] {
    drop {}
  }

}

output {
  stdout { codec => rubydebug }
}
</code>```

After writing this line to the stdin:

```<code>Message: msisdn: 111111111
</code>```

There was a response immediately (it didn't wait 5 seconds) with status OK

```<code>{
    "result" => "OK",
    "@timestamp" => 2017-03-30T17:58:39.940Z,
    "@version" => "1",
    "host" => "31634cf481d5",
    "message" => "Message: msisdn: 111111111",
    "type" => "Message",
    "msisdn" => "111111111"
}
</code>```

Should I write it differently?

Many thanks ;)

答:
The aggregate filter pretty much does what you are describing. First you need to identify the task_id to which you correlate your messages. Then you set up your logstash filter so it get the type of the message and your task_id. Then we have to seperate aggregate filters, one for the first theother for the second event.

The first has the timeout and the code to set the event to error should it timeout. The second filter checks for the Answer message and ends the aggregation.

```<code>grok {
  match => {%{DATA:type}: %{DATA:name}: %{DATA:id}}
}

if [type] == "Message" {
  aggregate {
    task_id => "%{id}"
    code => "event.set('result', 'OK')"
    timeout => 5
    timeout_code => "event.set('result', 'error')"
  }
}

if [type] == "Answer" {
  aggregate {
    task_id => "%{id}"
    code => "event.set('result', 'OK')"
    end_of_task => true
  }
}
</code>```

Check out the documentation for the aggregate filter here.

Body:
In Logstash, let's say I have the following lines in my logs:

Message: msisdn: 111111111
Message: msisdn: 222222222
Answer: msisdn: 111111111
Answer: msisdn: 222222222

Now, whenever I get the Message, I'd like to wait for X seconds.
If within this time period I get the matching Answer (i.e. with the same msisdn), mark it as OK, else mark it as ERROR.

How can I do that?

Thanks

**EDIT**

Fairy, I tried to work with the aggregate filter but with no success, can you please help me with that?

input {
  stdin {}
}

filter {
  grok {
    match => {"message" => "%{GREEDYDATA:type}: msisdn: %{INT:msisdn}"}
  }

  if [type] == "Message" {
    aggregate {
      task_id => "%{msisdn}"
      code => "event.set('result', 'OK')"
      timeout => 5
      timeout_code => "event.set('result', 'error')"
    }
  }

  if [logger] == "Answer" {
    aggregate {
      task_id => "%{msisdn}"
      code => "event.set('result', 'OK')"
      end_of_task => true
    }
  }

  if "_grokparsefailure" in [tags] {
    drop {}
  }

}

output {
  stdout { codec => rubydebug }
}

After writing this line to the stdin:

Message: msisdn: 111111111

There was a response immediately (it didn't wait 5 seconds) with status OK

{
    "result" => "OK",
    "@timestamp" => 2017-03-30T17:58:39.940Z,
    "@version" => "1",
    "host" => "31634cf481d5",
    "message" => "Message: msisdn: 111111111",
    "type" => "Message",
    "msisdn" => "111111111"
}

Should I write it differently?

Many thanks ;)

Body:
The aggregate filter pretty much does what you are describing. First you need to identify the task_id to which you correlate your messages. Then you set up your logstash filter so it get the type of the message and your task_id. Then we have to seperate aggregate filters, one for the first theother for the second event.

The first has the timeout and the code to set the event to error should it timeout. The second filter checks for the Answer message and ends the aggregation.

grok {
  match => {%{DATA:type}: %{DATA:name}: %{DATA:id}}
}

if [type] == "Message" {
  aggregate {
    task_id => "%{id}"
    code => "event.set('result', 'OK')"
    timeout => 5
    timeout_code => "event.set('result', 'error')"
  }
}

if [type] == "Answer" {
  aggregate {
    task_id => "%{id}"
    code => "event.set('result', 'OK')"
    end_of_task => true
  }
}

Check out the documentation for the aggregate filter here.


问:
Open and Read Exchange EDB file in Visual Studio
This is a research project, what I would like to do is be able to open a MS Exchange EDB (2003 to 2016) files and read the tables and data.

First part of the project is to open the edb file and determine the mailboxes inside.

Second part of the project is to then read individual messages in a selected mailbox.

I'm using Visual Studio for the project.

I understand the EDB file is a b-tree database (aka Jet Blue) but I have found very little documentation on the matter.

Some searching talks about a library for Linux called LIBESEDB but the project is missing on sourceforge, but has a new location HERE on GitHub.

Can anyone point me at URLs for this.  Any example code or libraries even better.

答:
It will be a challenge. The Exchange Store schema has changed a few times from 2003 to 2016. The massive I/O reduction from release to release has been accomplished by changing the schema.

You can use ManagedEsent from codeplex. http://managedesent.codeplex.com. The ese.dll (for Exchange) and esent.dll (for Windows) are similar enough that they can read each others database files. Do not use it for writing! There are enough differences in their implementations that you could get subtle corruptions.

If C/C++ is more your style: https://msdn.microsoft.com/en-us/library/gg269259(v=exchg.10).aspx. Again, there are some subtle differences between ese.dll and esent.dll, and ese.dll does not have any documentation, but for read-only purposes you should be fine.

-martin


问:
Is there a way to create an ecommerce site using zend?
The title might be a bit misleading. As you can see, we created a site for a client. Afterwards, he decided to add ecommerce-like module wherein the user's may avail items from the site. This was not the main intention of the site but the client doesn't want a new one but rather, update the site and add an ecommerce feature.

We are planning to do it manually... I was just thinking if there's a better way of doing it? are there any tools or plugin code or way that we can do it?

答:
See:

best E-Commerce Shopping Carts for Zend Framework developer

Always good to give SO a search.

You may also like to look at
http://ecartcommerce.com/


问:
How to swipe Left and Right with vertical scrolling using ScrollView in Android
I have some layouts inside a scrollView. Those layouts have to be swipable in left and right directions but it creates some conflicts with the scroll View. How can use both swipe and scroll using ScrollView in Android. I don,t want to use ViewPager.

Please help me as i am fresher in android.

Thanks in Advance.

答:
You can use HorizontalScrollView to scroll your child views horizontally and place this HorizontalScrollView inside ScrollView. Also add LinearLayout with Vertical orientation as a direct child of ScrollView.

Here is an working example. Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- First row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

        <!-- Second row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

        <!-- Third row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

    </LinearLayout>
</ScrollView>
</code>```

OUTPUT:

Hope this will help~

Body:
You can use HorizontalScrollView to scroll your child views horizontally and place this HorizontalScrollView inside ScrollView. Also add LinearLayout with Vertical orientation as a direct child of ScrollView.

Here is an working example. Try this:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- First row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

        <!-- Second row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

        <!-- Third row -->
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="One"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Two"/>

                <Button
                    android:layout_width="200dp"
                    android:layout_height="200dp"
                    android:text="Three"/>

            </LinearLayout>
        </HorizontalScrollView>

    </LinearLayout>
</ScrollView>

OUTPUT:

Hope this will help~


问:
"SystemError: tile cannot extend outside image" in PIL during save image
I have this Image =>

here is, all coordinates of above yellow boxes that is written in 3.txt file.

```<code>#Y   X Height     Width

46 135 158 118
46 281 163 104
67 494 188 83
70 372 194 101
94 591 207 98
252 132 238 123
267 278 189 105
320 741 69 141
322 494 300 135
323 389 390 124
380 726 299 157
392 621 299 108
449 312 227 93
481 161 425 150
678 627 285 91
884 13 650 437
978 731 567 158
983 692 60 43
1402 13 157 114
</code>```

My intension is to crop those boxes and save all boxes as Image. I have written a code for that but getting error.

Here is my code =>

```<code>from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from os import listdir
#from scipy.misc import imsave

ARR = np.empty([1,4])
# print(ARR)

i = 0
k = 0
img = Image.open('3.png')

fo = open("3.txt", "r")
for line in fo:
    if not line.startswith('#'):
        for word in line.split():

            ARR[0][i] = int(word)
            print(int(word))
            # ARR[0][i] = int(word)
            i = i +1

    img2 = img.crop((int(ARR[0][1]), int(ARR[0][0]), int(ARR[0][0] + ARR[0][2]), int(ARR[0][1] + ARR[0][3])))
    name = "new-img" + str(k) + ".png"
    img2.save(name)
    k = k + 1
    i = 0
</code>```

I am getting these error =>

Traceback (most recent call last):   File "reshape.py", line 26, in

      img2.save(name)   File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1468, in save
      save_handler(self, fp, filename)   File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 624, in
  _save
      ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])   File "/usr/lib/python2.7/dist-packages/PIL/ImageFile.py",
  line 462, in _save
      e.setimage(im.im, b) SystemError: tile cannot extend outside image

How do I fix these?

答:
With reference to the comments, the error occurred due to improper passing of the coordinates to PIL's crop() function.

As mentioned in the documentation, the function returns an image having taken in a tuple of four (x, y, width and height).

In the given text file the y coordinate is mentioned in the first column and x coordinate in the second column. The crop() function however accepts the value of x coordinate as the first parameter and the y coordinate as the second parameter.

The same applies for OpenCV as well.

Body:
I have this Image =>

here is, all coordinates of above yellow boxes that is written in 3.txt file.

#Y   X Height     Width

46 135 158 118
46 281 163 104
67 494 188 83
70 372 194 101
94 591 207 98
252 132 238 123
267 278 189 105
320 741 69 141
322 494 300 135
323 389 390 124
380 726 299 157
392 621 299 108
449 312 227 93
481 161 425 150
678 627 285 91
884 13 650 437
978 731 567 158
983 692 60 43
1402 13 157 114

My intension is to crop those boxes and save all boxes as Image. I have written a code for that but getting error.

Here is my code =>

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from os import listdir
#from scipy.misc import imsave

ARR = np.empty([1,4])
# print(ARR)

i = 0
k = 0
img = Image.open('3.png')

fo = open("3.txt", "r")
for line in fo:
    if not line.startswith('#'):
        for word in line.split():

            ARR[0][i] = int(word)
            print(int(word))
            # ARR[0][i] = int(word)
            i = i +1

    img2 = img.crop((int(ARR[0][1]), int(ARR[0][0]), int(ARR[0][0] + ARR[0][2]), int(ARR[0][1] + ARR[0][3])))
    name = "new-img" + str(k) + ".png"
    img2.save(name)
    k = k + 1
    i = 0

I am getting these error =>

Traceback (most recent call last):   File "reshape.py", line 26, in

      img2.save(name)   File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1468, in save
      save_handler(self, fp, filename)   File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 624, in
  _save
      ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])   File "/usr/lib/python2.7/dist-packages/PIL/ImageFile.py",
  line 462, in _save
      e.setimage(im.im, b) SystemError: tile cannot extend outside image

How do I fix these?

ContentLicense: CC BY-SA 4.0


问:
Div overlay two sibling div who will fill parent
I have 4 div, which look something like this

Desired output:

Current code:

```<code><div class="center aligned" style="width: 100%;height: 7em; padding: 2em; position:absolute;">
    <div class="ui small grey label fluid progress_padding_top_bottom" style="z-index:1;height: 7em; border-radius: 0; padding-right: 0; padding-left: 0; background-color: #E8E8E8 !important;">
    <div style="background-color: #21BA45; width: 5%; height: 7em; float:left;"></div>
    <div style="background-color: #ffdd00; width: 20%; height: 7em; float:left;"></div>
    <div style="width: 100%;" class="center aligned">ABC</div>
</div>
</code>```

Update: This is a part of a progress bar, so both red and yellow width will change

答:
This produces what you're trying to putput

https://jsfiddle.net/wcsfnbuL/

```<code><div class="center aligned" style="width: 100%;height: 7em; padding: 2em; position:absolute;">
        <div style="background-color: red; width: 15%; height: 7em; float:left; margin: auto;"></div>
        <div style="background-color: #ffdd00; width: 15%; height: 7em; text-align: center; vertical-align: middle; line-height: 7em; float:left; margin: auto;">ABC</div>
        <div class="ui small grey label fluid progress_padding_top_bottom" style="z-index:1;height: 7em; border-radius: 0; padding-right: 0; padding-left: 0; background-color: #E8E8E8; float: left; width: 15%"></div>

    </div>
</code>```

Body:
I have 4 div, which look something like this

Desired output:

Current code:

ABC

Update: This is a part of a progress bar, so both red and yellow width will change

Body:
This produces what you're trying to putput

https://jsfiddle.net/wcsfnbuL/

<div class="center aligned" style="width: 100%;height: 7em; padding: 2em; position:absolute;">
        <div style="background-color: red; width: 15%; height: 7em; float:left; margin: auto;"></div>
        <div style="background-color: #ffdd00; width: 15%; height: 7em; text-align: center; vertical-align: middle; line-height: 7em; float:left; margin: auto;">ABC</div>
        <div class="ui small grey label fluid progress_padding_top_bottom" style="z-index:1;height: 7em; border-radius: 0; padding-right: 0; padding-left: 0; background-color: #E8E8E8; float: left; width: 15%"></div>

    </div>


问:
alert doesn't appear in localhost
The below code works fine in jsfiddle but when i run in the locahost, alert box doesn't appear while there is no error in the console too. What could be the reason. Can anyone help?

index.html

```<code><title>App</title>

<script type="text/javascript" src="movieList.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</code>```

movieList.js

```<code>$(document).ready(function(){
    alert('something');
});
</code>```

答:
JQuery First</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="movieList.js"></script>
</code>```

Title: alert doesn't appear in localhost

Body:
The below code works fine in jsfiddle but when i run in the locahost, alert box doesn't appear while there is no error in the console too. What could be the reason. Can anyone help?

index.html

<title>App</title>

movieList.js

$(document).ready(function(){
    alert('something');
});

Body:
JQuery First

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="movieList.js"></script>


问:
How to ensure that MySQL column only accepts X number of characters?
I've been doing some searching on the Internet, but I can't for the life figure this out:

Can I force a MySQL table column to ONLY accept a set number of characters (e.g. 5 numbers ONLY, not 4 numbers nor 6 numbers)? I've read the MySQL documentation for some various data types but haven't really discovered anything yet.

In a rather unfortunate move, I can't perform reg-ex checking in PHP that easily right now, and would like to take the easy way out by forcing this check in the database itself. Thanks in advance!

答: you can probably do this with a check constraint on the table</p>


问:
Dynamic PIVOT two columns prefix
Database: Microsoft SQL Server 2012

I have one table that contains the computers and the software installed.
Now, one computer can have 30+ software installed but there are probably 100+ different software on the infrastructure.

This is a representation of the table

```<code>Computer  | Software
--------------------
PC123     | Office
PC123     | Firefox
PC456     | Office
PC456     | Firefox
PC456     | CAD
PC789     | Firefox
PC789     | Outlook
...
</code>```

I'm looking for a result that would look like this

```<code>Computer  | Software 1 | Software 2 | Software 3
------------------------------------------------
PC123     | Firefox    | Office     | NULL
PC456     | CAD        | Firefox    | Office
PC789     | Firefox    | Outlook    | NULL
...
</code>```

I've been looking into dynamic PIVOT but I'm still new with SQL.

Thank you for the help

答:
Another alternative is to use the stuff function and put all of the software into one line.
My code might be slightly off. I suck without being able to test.

```<code>Results should look like this:
Computer    Software
PC123       Firefox, CAD, Office
PC456       Firefox

SELECT t.Computer, Software_String.Software
FROM (SELECT DISTINCT Computer FROM TABLE) t
OUTER APPLY (
SELECT REPLACE(STUFF((
            SELECT ', ' + w.Start_Date, 100)
            FROM Computer w
            WHERE c.Computer_ID = w.Computer_ID
            FOR XML PATH('')
            ), 1, 2, ''), '  ', ' ') [Software]
        ) Software_String
</code>```

Or you can use a case statement instead of pivots. I find pivot programming slow and a pain to write.

Title: Dynamic PIVOT two columns prefix

Body:
Database: Microsoft SQL Server 2012

I have one table that contains the computers and the software installed.
Now, one computer can have 30+ software installed but there are probably 100+ different software on the infrastructure.

This is a representation of the table

Computer  | Software
--------------------
PC123     | Office
PC123     | Firefox
PC456     | Office
PC456     | Firefox
PC456     | CAD
PC789     | Firefox
PC789     | Outlook
...

I'm looking for a result that would look like this

Computer  | Software 1 | Software 2 | Software 3
------------------------------------------------
PC123     | Firefox    | Office     | NULL
PC456     | CAD        | Firefox    | Office
PC789     | Firefox    | Outlook    | NULL
...

I've been looking into dynamic PIVOT but I'm still new with SQL.

Thank you for the help

Body:
Another alternative is to use the stuff function and put all of the software into one line.
My code might be slightly off. I suck without being able to test.

Results should look like this:
Computer    Software
PC123       Firefox, CAD, Office
PC456       Firefox

SELECT t.Computer, Software_String.Software
FROM (SELECT DISTINCT Computer FROM TABLE) t
OUTER APPLY (
SELECT REPLACE(STUFF((
            SELECT ', ' + w.Start_Date, 100)
            FROM Computer w
            WHERE c.Computer_ID = w.Computer_ID
            FOR XML PATH('')
            ), 1, 2, ''), '  ', ' ') [Software]
        ) Software_String

Or you can use a case statement instead of pivots. I find pivot programming slow and a pain to write.


问:
Show/Hide div element with rails view html.erb file
I am trying to show/hide certain divs depending on the click of a button/link. I have done some reading on how to do this with JQuery, but it doesn't seem to be working.

edit.html.erb

```<code><script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<div class="pad-bottom">
  <a id="edit-profile-button" class="button default ok" href="#">
    Edit Profile
  </a>
  <div id="profile-information" class="hidden">
    <div class="row pad-top">
      <div class="col-xs-6 col-sm-6 field-row">
        <div class="roboto bold black field-label">
          First
        </div>
        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>
      </div>
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function(event){
    $('#edit-profile-button').click(function(){
      event.preventDefault();
      $('#profile-information').toggle();
    });
  });
</script>
</code>```

application.css

```<code>.hidden {
  display: none;
}
</code>```

I can click on the link and fall into a debugger and access the two elements that I try to select in the jQuery code, but it doesn't seem do be doing anything at all, the div is never made visible.

答:
Ended using bootstrap to solve my problem (http://getbootstrap.com/javascript/#collapse)

edit.html.erb

```<code><div class="pad-bottom">
  <a id="edit-profile-button" class="button default ok" href="#profile-information" data-toggle="collapse" aria-expanded="false">
    Edit Profile
  </a>
  <div id="profile-information" class="collapse">
    <div class="row pad-top">
      <div class="col-xs-6 col-sm-6 field-row">
        <div class="roboto bold black field-label">
          First
        </div>
        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>
      </div>
  </div>
</div>
</code>```

Body:
I am trying to show/hide certain divs depending on the click of a button/link. I have done some reading on how to do this with JQuery, but it doesn't seem to be working.

edit.html.erb

    Edit Profile

          First

        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>

application.css

.hidden {
  display: none;
}

I can click on the link and fall into a debugger and access the two elements that I try to select in the jQuery code, but it doesn't seem do be doing anything at all, the div is never made visible.

Body:
Ended using bootstrap to solve my problem (http://getbootstrap.com/javascript/#collapse)

edit.html.erb

<div class="pad-bottom">
  <a id="edit-profile-button" class="button default ok" href="#profile-information" data-toggle="collapse" aria-expanded="false">
    Edit Profile
  </a>
  <div id="profile-information" class="collapse">
    <div class="row pad-top">
      <div class="col-xs-6 col-sm-6 field-row">
        <div class="roboto bold black field-label">
          First
        </div>
        <%= f.text_field :first_name, class: 'field', placeholder: 'First Name'%>
      </div>
  </div>
</div>


问:
Power BI Pro Content error
I installed Power BI Gateway in order to use SQL directly in my Dashboard. I published the report and found that none of my colleagues could view it without a Pro License. I tried everything but can't get rid of the so called "power BI pro content" in my dashboard.

So I uninstalled the gateway software and reinstalled Power BI.

I tested by creating a very basic report with one line chart linking to excel. Even this report can't be viewed by my colleagues because "it contains pro content".

As it turns out, ALL dashboards (even created by my colleagues) give this warning when I try to share it.

This is driving me nuts. Please can someone help.

thanks
g

答:
The documentation for what counts as Power BI Pro content is here: https://powerbi.microsoft.com/en-us/documentation/powerbi-power-bi-pro-content-what-is-it/

Some key tripping points: anything with a scheduled refresh that uses a gateway, or that refreshes more than daily counts as Pro. Anything posted to a group workspace or shared via an organizational content pack count as Pro too.

Bear in mind that a dashboard only needs one tile from a "Pro" report to be considered Pro.

In an enterprise setting, where your data is coming from SQL on-premises, it'd be hard to avoid pro content. Your data would have to be imported into Power BI Desktop, and refreshed & republished manually. You couldn't use direct query mode, a gateway, automatic refresh, group workspaces, or organizational content packs.

It's hard to comment specifically on why your very basic Excel report contains pro content. If you're sure it doesn't meet any of the documented reasons, click the Smile at the top-right of PowerBI.com and Submit an Issue. Microsoft should be able to tell you.

Note: What makes content pro could easily change in the future, so although I highlighted some common tripping points, I do recommend referring to the linked documentation for the definitive answer.

Title: Power BI Pro Content error


答:
Script order matters. You need to load jQuery before you load your script because your script relies on jQuery.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="movieList.js"></script>
</code>```

If you were to open your javascript console in your browser (Ctrl Shift J), you'd probably see an error saying something like $ is not a function.

If there are no errors, perhaps you've suppressed alerts for the page. Try replacing

```<code>alert('something');
</code>```

With

```<code>console.log('something');
</code>```

And keep an eye on your javascript console to see if the message gets printed. If it shows up, you've probably disabled alerts. To fix this, close and re-open the tab. It's recommended you use console.log() over alert() for debugging since alerts and other prompts can cause weird timing issues because of how they interrupt the javascript execution.

Title: alert doesn't appear in localhost

Body:
Script order matters. You need to load jQuery before you load your script because your script relies on jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript" src="movieList.js"></script>

If you were to open your javascript console in your browser (Ctrl Shift J), you'd probably see an error saying something like $ is not a function.

If there are no errors, perhaps you've suppressed alerts for the page. Try replacing

alert('something');

With

console.log('something');

And keep an eye on your javascript console to see if the message gets printed. If it shows up, you've probably disabled alerts. To fix this, close and re-open the tab. It's recommended you use console.log() over alert() for debugging since alerts and other prompts can cause weird timing issues because of how they interrupt the javascript execution.


问:
Swift Firebase query taking up to a minute
Ok so I have a Swift app that's loading in this Firebase db into a tableview. The problem is that it can take up to an entire minute to get the Firebase response and load in the data. This happens regardless of the internet connection. Am I doing something wrong here, there's only 7 of those items in the database so I can't see it being an issue with the database being too large. I should also note that it strangly takes at least a minute just to load the Realtime Database through the Firebase console on the browser.

Any idea what's going wrong here? Below is the code where I'm querying the db, and a snapshot of the content I'm loading in the Firebase console.

Oh and I'm using a free Firebase account, but I didn't see any restrictions on speed in the pricing options so I don't think that's the problem.

```<code>  private func loadItems(){

    var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()

    ref.child("DonationItem").observeSingleEvent(of: .value, with: { (snapshot) in

        if let values = snapshot.value as? NSDictionary {

            for (key,_) in values{

                let donationItem: NSObject = values[key] as! NSObject

                let myTitle: String! = donationItem.value(forKey: "title") as? String
                let myItemID: String! = donationItem.value(forKey: "itemID") as? String

                let myPhotoString = donationItem.value(forKey: "image") as? String
                let decodedData = NSData(base64Encoded: myPhotoString!)
                let myImage = UIImage(data: decodedData as! Data)

                let myDescription = donationItem.value(forKey: "description") as? String
                let myDate = donationItem.value(forKey: "expiration") as? String
                let myLatitude = donationItem.value(forKey: "latitude") as? Double
                let myLongitude = donationItem.value(forKey: "longitude") as? Double
                let myCoordinates = CLLocationCoordinate2D(latitude: myLatitude!, longitude: myLongitude!)
                let myUserID = donationItem.value(forKey: "userID") as? String
                let myAddress = donationItem.value(forKey: "address") as? String

                var  donated: Bool
                if let donatedInt = donationItem.value(forKey: "donated") as? Int {
                    donated = Bool(donatedInt as NSNumber)
                } else {
                    donated = true
                }

                let donation1 = DonatedItem(myTitle, myImage!, donated, myDescription!, myDate!, myCoordinates, myUserID!, myItemID!, myAddress!)
                self.addItem(item: donation1!)

                }
        }

    }) { (error) in
        print(error.localizedDescription)
    }

}
</code>```

Here's the Firebase console.

Thanks for the help!

答:
How is the long and lat determined, and is this done before the query is executed? It may not be the query that is problem.

Edit:

The encoded image size was the problem to this question in the end. Images can become quite large and slow down response times in a query if they are hard-coded image urls. Watch out for the ways in which you retrieve images.

The better way would be to store images in Firebase Storage and put a reference to it in the DB, as @riper wrote in a comment to this answer.

Body:
Ok so I have a Swift app that's loading in this Firebase db into a tableview. The problem is that it can take up to an entire minute to get the Firebase response and load in the data. This happens regardless of the internet connection. Am I doing something wrong here, there's only 7 of those items in the database so I can't see it being an issue with the database being too large. I should also note that it strangly takes at least a minute just to load the Realtime Database through the Firebase console on the browser.

Any idea what's going wrong here? Below is the code where I'm querying the db, and a snapshot of the content I'm loading in the Firebase console.

Oh and I'm using a free Firebase account, but I didn't see any restrictions on speed in the pricing options so I don't think that's the problem.

  private func loadItems(){

    var ref: FIRDatabaseReference!
    ref = FIRDatabase.database().reference()

    ref.child("DonationItem").observeSingleEvent(of: .value, with: { (snapshot) in

        if let values = snapshot.value as? NSDictionary {

            for (key,_) in values{

                let donationItem: NSObject = values[key] as! NSObject

                let myTitle: String! = donationItem.value(forKey: "title") as? String
                let myItemID: String! = donationItem.value(forKey: "itemID") as? String

                let myPhotoString = donationItem.value(forKey: "image") as? String
                let decodedData = NSData(base64Encoded: myPhotoString!)
                let myImage = UIImage(data: decodedData as! Data)

                let myDescription = donationItem.value(forKey: "description") as? String
                let myDate = donationItem.value(forKey: "expiration") as? String
                let myLatitude = donationItem.value(forKey: "latitude") as? Double
                let myLongitude = donationItem.value(forKey: "longitude") as? Double
                let myCoordinates = CLLocationCoordinate2D(latitude: myLatitude!, longitude: myLongitude!)
                let myUserID = donationItem.value(forKey: "userID") as? String
                let myAddress = donationItem.value(forKey: "address") as? String

                var  donated: Bool
                if let donatedInt = donationItem.value(forKey: "donated") as? Int {
                    donated = Bool(donatedInt as NSNumber)
                } else {
                    donated = true
                }

                let donation1 = DonatedItem(myTitle, myImage!, donated, myDescription!, myDate!, myCoordinates, myUserID!, myItemID!, myAddress!)
                self.addItem(item: donation1!)

                }
        }

    }) { (error) in
        print(error.localizedDescription)
    }

}

Here's the Firebase console.

Thanks for the help!


问:
Why does loss increase when go to deeper network with multiple loss?
I am using ResNet scheme to train my network architecture. After every 16 layers, I used a deconvolution and loss layer (SoftmaxWithLoss). When going to deeper layer, I saw that my loss (loss3 and loss4) increase compares with loss2. Why does it happen? How can I choose loss weight for each loss layer? Now, I used loss_weight=0.1 for all loss layer, except loss_main

```<code>Iteration 9960, loss = 0.287316
    Train net output #0: loss_main = 0.0921776 (* 1 = 0.0921776 loss)
    Train net output #1: loss1 = 0.259363 (* 0.1 = 0.0259363 loss)
    Train net output #2: loss2 = 0.14823 (* 0.1 = 0.014823 loss)
    Train net output #3: loss3 = 0.169563 (* 0.1 = 0.0169563 loss)
     Train net output #4: loss4 = 0.21544 (* 0.1 = 0.021544 loss)
Iteration 9980, lr = 0.002
Iteration 9980, loss = 0.286957
     Train net output #0: loss_main = 0.151433 (* 1 = 0.151433 loss)
     Train net output #1: loss1 = 0.362414 (* 0.1 = 0.0362414 loss)
     Train net output #2: loss2 = 0.267339 (* 0.1 = 0.0267339 loss)
     Train net output #3: loss3 = 0.304756 (* 0.1 = 0.0304756 loss)
     Train net output #4: loss4 = 0.393892 (* 0.1 = 0.0393892 loss)
Iteration 10000, lr = 0.002
Iteration 10000, loss = 0.287502
     Train net output #0: loss_main = 0.149631 (* 1 = 0.149631 loss)
     Train net output #1: loss1 = 0.377756 (* 0.1 = 0.0377756 loss)
     Train net output #2: loss2 = 0.252874 (* 0.1 = 0.0252874 loss)
     Train net output #3: loss3 = 0.26978 (* 0.1 = 0.026978 loss)
     Train net output #4: loss4 = 0.355817 (* 0.1 = 0.0355817 loss)
</code>```

答:
loss is not a monotonically decreasing function; it varies up and down.  As long as the overall trend is downward, training is progressing as expected.  Since you haven't given a sufficiently long base-line for the behaviour, I can't give you a full judgement on whether your model has problems.

You can adjust the loss weights in the source code, of course -- but I don't recommend it.  I think you can also override it in train_val.prototxt, but I can't find the reference at the moment.

Body:
I am using ResNet scheme to train my network architecture. After every 16 layers, I used a deconvolution and loss layer (SoftmaxWithLoss). When going to deeper layer, I saw that my loss (loss3 and loss4) increase compares with loss2. Why does it happen? How can I choose loss weight for each loss layer? Now, I used loss_weight=0.1 for all loss layer, except loss_main

Iteration 9960, loss = 0.287316
    Train net output #0: loss_main = 0.0921776 (* 1 = 0.0921776 loss)
    Train net output #1: loss1 = 0.259363 (* 0.1 = 0.0259363 loss)
    Train net output #2: loss2 = 0.14823 (* 0.1 = 0.014823 loss)
    Train net output #3: loss3 = 0.169563 (* 0.1 = 0.0169563 loss)
     Train net output #4: loss4 = 0.21544 (* 0.1 = 0.021544 loss)
Iteration 9980, lr = 0.002
Iteration 9980, loss = 0.286957
     Train net output #0: loss_main = 0.151433 (* 1 = 0.151433 loss)
     Train net output #1: loss1 = 0.362414 (* 0.1 = 0.0362414 loss)
     Train net output #2: loss2 = 0.267339 (* 0.1 = 0.0267339 loss)
     Train net output #3: loss3 = 0.304756 (* 0.1 = 0.0304756 loss)
     Train net output #4: loss4 = 0.393892 (* 0.1 = 0.0393892 loss)
Iteration 10000, lr = 0.002
Iteration 10000, loss = 0.287502
     Train net output #0: loss_main = 0.149631 (* 1 = 0.149631 loss)
     Train net output #1: loss1 = 0.377756 (* 0.1 = 0.0377756 loss)
     Train net output #2: loss2 = 0.252874 (* 0.1 = 0.0252874 loss)
     Train net output #3: loss3 = 0.26978 (* 0.1 = 0.026978 loss)
     Train net output #4: loss4 = 0.355817 (* 0.1 = 0.0355817 loss)


问:
Localhost and 127.0.0.1 show different content in web browser
When I enter 127.0.0.1 to web browser, it shows page /var/www/index.php as I expected, but when I enter localhost it shows "a simple hello world" html page which I cannot find in the computer.

I used find, grep and other similar tools, but no luck.

Can you please tell me why localhost shows another content then 127.0.0.1 in the web browser?

I have installed apache, mysql and php on my ubuntu 14.04 and Document Root is set to /var/www/. There were previously installed apache, postgresql and php (which I removed), maybe should I check some old exist config files?

/etc/hosts is set to

```<code>127.0.0.1    localhost
</code>```

答:
As requested in comment I post it as answer.

Web browsers use cache and in some cases your changes are not reloaded.
So refreshing using Ctrl+R, Ctrl+f5 or disabling cache in your settings may be useful.

Body:
When I enter 127.0.0.1 to web browser, it shows page /var/www/index.php as I expected, but when I enter localhost it shows "a simple hello world" html page which I cannot find in the computer.

I used find, grep and other similar tools, but no luck.

Can you please tell me why localhost shows another content then 127.0.0.1 in the web browser?

I have installed apache, mysql and php on my ubuntu 14.04 and Document Root is set to /var/www/. There were previously installed apache, postgresql and php (which I removed), maybe should I check some old exist config files?

/etc/hosts is set to

127.0.0.1    localhost


问:
Cakephp uploading an image, the tmp_name file is getting deleted before the script is done?
I have an html form that allows the user to browse for a file to upload.

In the cakephp script, I use move_uploaded_file() to upload the file from the temp location to a location on the server.

```<code>move_uploaded_file($file['tmp_name'], $url);
</code>```

However, the file seems to be disappearing before the upload is complete:

move_uploaded_file(/img/recipes/5.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory [APP\app_controller.php, line 97]

move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpF25A.tmp' to '/img/recipes/5.jpg' [APP\app_controller.php, line 97]

答: It's complaining about the non-existence of /img/recipes/5.jpg, not the source file (that's uploaded by the user).</p>

Body:
I have an html form that allows the user to browse for a file to upload.

In the cakephp script, I use move_uploaded_file() to upload the file from the temp location to a location on the server.

move_uploaded_file($file['tmp_name'], $url);

However, the file seems to be disappearing before the upload is complete:

move_uploaded_file(/img/recipes/5.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory [APP\app_controller.php, line 97]

move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpF25A.tmp' to '/img/recipes/5.jpg' [APP\app_controller.php, line 97]


问:
How do I create a generic reducer plugin, that fires on all forms?
Currently my code works, but only for the forms specified specifically in the combine reducer function. But, I would like to have my code work generally for all forms loaded in my single page app.

Here is the relevant code:

```<code>import { reducer as formReducer } from 'redux-form';
export default combineReducers({
  someReducer,
  anotherReducer,
  form: formReducer.plugin({
    specificFormId: (state, action) => { // <-- I don't want this only for specificFormId, I want this to happen for all my forms,
                                        // or at least have a dynamic way of adding more forms
      const {type, payload} = action;
      switch(type) {
        case 'RESET_LINK_TYPE_FIELDS': {
          return {
            ...state,
            registeredFields: {
              ...state.registeredFields,
              // Do some custom restting here based on payload
            }
          };
        }
        default:
          return state;
      }
    }
  })
});
</code>```

So, anytime my <Field ..of a certain type/> fires off this the RESET_LINK_TYPE_FIELDS action, I want the correct form to respond to it.

In the action payload, I can specifically the form identifier or anything else I would need to make this work.

In fact, if the .plugin let me do my own form state slicing, I could easily do this, but because it forces me to pass an object, with a hardcoded form identifier it doesn't work.

Is there a way to have the plugin give me the WHOLE form state, and then I will slice as needed, and return state as needed based on payload?

答:
There is currently no way to do this with the existing API.

You could jury rig a solution by wrapping the redux-form reducer in your own thing.

```<code>export default combineReducers({
  someReducer,
  anotherReducer,
  form: resetHack(formReducer)
})

function resetHack(formReducer) {
  return (state, action) => {
    if(action.RESET_LINK_TYPE_FIELDS) {
      // manipulate slice somehow
    } else {
      return formReducer(state, action)
    }
  }
}
</code>```

Body:
Currently my code works, but only for the forms specified specifically in the combine reducer function. But, I would like to have my code work generally for all forms loaded in my single page app.

Here is the relevant code:

import { reducer as formReducer } from 'redux-form';
export default combineReducers({
  someReducer,
  anotherReducer,
  form: formReducer.plugin({
    specificFormId: (state, action) => { // <-- I don't want this only for specificFormId, I want this to happen for all my forms,
                                        // or at least have a dynamic way of adding more forms
      const {type, payload} = action;
      switch(type) {
        case 'RESET_LINK_TYPE_FIELDS': {
          return {
            ...state,
            registeredFields: {
              ...state.registeredFields,
              // Do some custom restting here based on payload
            }
          };
        }
        default:
          return state;
      }
    }
  })
});

So, anytime my <Field ..of a certain type/> fires off this the RESET_LINK_TYPE_FIELDS action, I want the correct form to respond to it.

In the action payload, I can specifically the form identifier or anything else I would need to make this work.

In fact, if the .plugin let me do my own form state slicing, I could easily do this, but because it forces me to pass an object, with a hardcoded form identifier it doesn't work.

Is there a way to have the plugin give me the WHOLE form state, and then I will slice as needed, and return state as needed based on payload?

Body:
There is currently no way to do this with the existing API.

You could jury rig a solution by wrapping the redux-form reducer in your own thing.

export default combineReducers({
  someReducer,
  anotherReducer,
  form: resetHack(formReducer)
})

function resetHack(formReducer) {
  return (state, action) => {
    if(action.RESET_LINK_TYPE_FIELDS) {
      // manipulate slice somehow
    } else {
      return formReducer(state, action)
    }
  }
}


问:
Grow flexbox container height without row content overflowing
I have a flexbox page element with a min-height with a container that contains rows, and the rows contain events. The row heights are evenly distributed against the height of the container as in this example:

http://codepen.io/tysonnero/pen/LWXaMG

HTML

```<code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}
</code>```

However, if I add several additional events to the row, the events overflow into the next row as so:

http://codepen.io/tysonnero/pen/bqQyeG

HTML

```<code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>
</code>```

I can fix that by removing display:flex from the .page, but that causes the row to not evenly distribute the min-height when the row content is minimal.

Can anything recommend the best working approach to this?

答:
Update .row's flex property to flex: 1 0 auto;.

The flex property is shorthand for flex-grow, flex-shrink and flex-basis. By setting the second value to 0 we're telling those flex items not to shrink and maintain their original size.

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1 0 auto;
  flex-direction: column;
  border: solid 1px #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 1</div>
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div></code>```

Body:
I have a flexbox page element with a min-height with a container that contains rows, and the rows contain events. The row heights are evenly distributed against the height of the container as in this example:

http://codepen.io/tysonnero/pen/LWXaMG

HTML

Event 1

Event 2

Event 1

Event 1

Event 1

CSS

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

However, if I add several additional events to the row, the events overflow into the next row as so:

http://codepen.io/tysonnero/pen/bqQyeG

HTML

Event 1

Event 2

Event 3

Event 4

Event 5

Event 6

Event 1

Event 1

Event 1

I can fix that by removing display:flex from the .page, but that causes the row to not evenly distribute the min-height when the row content is minimal.

Can anything recommend the best working approach to this?

Body:
Update .row's flex property to flex: 1 0 auto;.

The flex property is shorthand for flex-grow, flex-shrink and flex-basis. By setting the second value to 0 we're telling those flex items not to shrink and maintain their original size.

.page {
  min-height: 300px;
  display: flex;
}

.container {
  display: flex;
  flex: 1;
  flex-direction: column;
  border: solid 1px #eee;
}

.row {
  display: flex;
  flex: 1 0 auto;
  flex-direction: column;
  border: solid 1px #eee;
}

<div class="page">
  <div class="container">
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 2</div>
      <div class="event">Event 3</div>
      <div class="event">Event 4</div>
      <div class="event">Event 5</div>
      <div class="event">Event 6</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
      <div class="event">Event 1</div>
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
    <div class="row">
      <div class="event">Event 1</div>
    </div>
  </div>
</div>


问:
convert numbers to 26base with only letters
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

```<code>function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}
</code>```

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

答:
You can try  something  like this

```<code>function convert($n)
{
    if ($n <= 0) return "";

    $r = "";
    $c  = "abcdefghijklmnopqrstuvwxyz";
    do {
        $n -= 1;
        $r = $c[$n % 26] . $r;
        $n = intval($n / 26);
    } while($n > 0);

    return strtoupper($r);
}

var_dump(convert(703));  // AAA
var_dump(convert(52));   // AZ
</code>```

The key is $n -= 1 in every loop because the number system you are using have  no concept of zero (0).

Body:
I need to convert number in "Alphabetic" Counting System, similar to excel spreadsheets:

convert(1) == "A";

  convert(2) == "B";

  ...

  convert(26) == "Z";

  convert(27) == "AA";

  ...

  convert(52) == "AZ";

  convert(53) == "BA";

  ...

  convert(702 ) == "ZZ";

  convert(703 ) == "AAA";

this is my code:

function convert($n){
    if ($n> 26) {
        $tmp = floor($n / 26);
        $n= $n % 26;
        $result = chr(($tmp - 1) + 65) . chr(($n - 1) + 65);
    } else {
        $result = chr(($n- 1) + 65);
    }
    return $result;
}

but the output is a bit off:

@, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,

  AA, AB, AC, AD, AE, AF, AG, AH, AI, AJ, AK, AL, AM, AN, AO, AP, AQ, AR, AS, AT, AU, AV, AW, AX, AY,

  B@, BA

I tried to tweak the numbers but I can not make it right, any suggestion for a better algorithm ?

Body:
You can try  something  like this

function convert($n)
{
    if ($n <= 0) return "";

    $r = "";
    $c  = "abcdefghijklmnopqrstuvwxyz";
    do {
        $n -= 1;
        $r = $c[$n % 26] . $r;
        $n = intval($n / 26);
    } while($n > 0);

    return strtoupper($r);
}

var_dump(convert(703));  // AAA
var_dump(convert(52));   // AZ

The key is $n -= 1 in every loop because the number system you are using have  no concept of zero (0).


问:
Browser cache not expiring
I am developing my application in asp.net and wanted force refreshing of .js files after certain period of time. In order to test that in local environment, I made following change to my web.config file:

```<code><httpProtocol>
  <customHeaders>
    <add name="Cache-Control" value="must-revalidate max-age=120" />
  </customHeaders>
</httpProtocol>
</code>```

As I understand cache-control, based on above settings, browser cache should expire after 2:00 minutes and any new postback should send a request to webserver to check if newer version of .js is avialable or not. I used fiddler to monitor network traffic and I don't see any request for js file. The browser I am using is Chrome. So I used dev tools to monitor network traffic. I see that the browser is using cached version of that file.

Are there any other settings that would force the browser to expire the cached files?

答:
Your Cache-Control is invalid, try separate values by comma: must-revalidate, max-age=120.

Relevant excerpt from RFC 7234 Hypertext Transfer Protocol (HTTP/1.1): Caching:

Cache-Control   = 1#cache-directive

cache-directive = token [ "=" ( token / quoted-string ) ]

And ABNF List Extension from RFC 7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing:

A construct "#" is defined, similar to "*", for defining
comma-delimited lists of elements.  The full form is "<n>#<m>element"
indicating at least <n> and at most <m> elements, each separated by a
single comma (",") and optional whitespace (OWS).

Also make sure to put new configuration in right place. For more information check Is it possible to add response http headers in web.config?.

Title: Browser cache not expiring

Body:
I am developing my application in asp.net and wanted force refreshing of .js files after certain period of time. In order to test that in local environment, I made following change to my web.config file:

<httpProtocol>
  <customHeaders>
    <add name="Cache-Control" value="must-revalidate max-age=120" />
  </customHeaders>
</httpProtocol>

As I understand cache-control, based on above settings, browser cache should expire after 2:00 minutes and any new postback should send a request to webserver to check if newer version of .js is avialable or not. I used fiddler to monitor network traffic and I don't see any request for js file. The browser I am using is Chrome. So I used dev tools to monitor network traffic. I see that the browser is using cached version of that file.

Are there any other settings that would force the browser to expire the cached files?


问:
MATLAB: Adding a bar graph to plotyy messes up line plot
I am using plotyy() to plot both precipitation data (bar plot) and flow data (line plot). When I add both datasets as line plots, everything looks fine (top image, see link). When I add the precipitation data as a bar plot, it messes up the smoothness of the line plot (bottom image, see link). I do not have this issue with all of my datasets, but two are giving me this problem. I have tried loading the data from a different source and plotting the data individually. The bar plot always messes up my line plot. I cannot figure out what might be causing this. Any ideas? Thanks in advance!

Files for Minimum Example

Data

Matlab File

答:
I copied the figure and pasted it into a Word document. As ridiculous as this sounds, it looks perfectly normal in the Word document but is still messed up in the MATLAB figure window and in the .png I saved. The error is definitely caused by a bug. At least I know to try pasting the figure into Word first next time.

Thanks to everyone who read through my question and provided feedback.


问:
Replacing certain characters while allowing unicode (PHP)
So I got a search box in a site we're developing that will search in a database with both English and Greek product strings. I'm trying to clear the text input from all kinds of special characters like: / . , ' ] [ % & _ etc. and replace them with a space or totally delete them. Even double instances of them should be deleted, like ^^, &&, [[ etc.

I have been messing around with preg_replace but can't find a solution...

Thanks in advance.

答:
I finally came up with this:

```<code>$term = preg_replace("/[^\p{Greek}a-zA-Z0-9\s]+/u", '', $term);
</code>```

It seems to work for what I need. It allows Greek characters (even with accents), alphanumerical and spaces. Replaces everything else with a space. Thanks for the fast response guys.

Body:
I finally came up with this:

$term = preg_replace("/[^\p{Greek}a-zA-Z0-9\s]+/u", '', $term);

It seems to work for what I need. It allows Greek characters (even with accents), alphanumerical and spaces. Replaces everything else with a space. Thanks for the fast response guys.


问:
How do you set a JLabel to take all the available width space?
I'm trying to center the JLabel text and to change the background and foreground color. I tried to use HTML:

```<code>JLabel listHeader = new JLabel("<html><span style='background-color:#555;color:White;text-align:center;'>Tables</span></html>");
</code>```

But it doesn't seem to work as you can see in the image below.

Image of the components

The label is inside a panel that has the layout manager set to grid bag layout with the following constraints:

```<code>c.gridy=0;
c.gridx=0;
c.weighty=0;
c.weightx=1;
c.fill=GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;
</code>```

I tried with fill BOTH as well, same result.

How can I make the label take all the width space?

答: You could try to anchor at the center, not on the start of the line.</p>

Body:
I'm trying to center the JLabel text and to change the background and foreground color. I tried to use HTML:

JLabel listHeader = new JLabel("Tables");

But it doesn't seem to work as you can see in the image below.

Image of the components

The label is inside a panel that has the layout manager set to grid bag layout with the following constraints:

c.gridy=0;
c.gridx=0;
c.weighty=0;
c.weightx=1;
c.fill=GridBagConstraints.NONE;
c.anchor = GridBagConstraints.LINE_START;

I tried with fill BOTH as well, same result.

How can I make the label take all the width space?


问:
How do you add the sum of lists when the sublist is int?
How do you add the sum of List of List when the sub list is int. I know you can't do mainList.Sum(); because you can't add a list data type so I have to use loops and another list to get around it. If I don't want to use loops is there a simpler way of doing it ?

```<code>var mainList = new List<List<int>>( );
mainList.Add(new List<int>{ 6});
mainList [0].Add (5);
mainList [0].Add (3);
mainList.Add(new List<int>{ 7});
mainList [1].Add (5);
mainList [1].Add (2);
mainList.Add(new List<int>{ 8});
mainList [2].Add (5);
mainList [2].Add (19);
</code>```

without having to do this..

```<code>List<int> list = new List<int>();
for (int i =0; i <3; i++)
{
    for (int j = 0; j <mainList[i].Count; j++)
    {
        list.Add (mainList [i] [j]);
    }
}
Console.Write (list.Sum ());
</code>```

答:
LINQ's SelectMany will flatten the object to one collection, then you can just call Sum() on it:

```<code>var result = mainList.SelectMany(i => i).Sum();
//result = 60
</code>```

Body:
How do you add the sum of List of List when the sub list is int. I know you can't do mainList.Sum(); because you can't add a list data type so I have to use loops and another list to get around it. If I don't want to use loops is there a simpler way of doing it ?

var mainList = new List<List<int>>( );
mainList.Add(new List<int>{ 6});
mainList [0].Add (5);
mainList [0].Add (3);
mainList.Add(new List<int>{ 7});
mainList [1].Add (5);
mainList [1].Add (2);
mainList.Add(new List<int>{ 8});
mainList [2].Add (5);
mainList [2].Add (19);

without having to do this..

List<int> list = new List<int>();
for (int i =0; i <3; i++)
{
    for (int j = 0; j <mainList[i].Count; j++)
    {
        list.Add (mainList [i] [j]);
    }
}
Console.Write (list.Sum ());

Body:
LINQ's SelectMany will flatten the object to one collection, then you can just call Sum() on it:

var result = mainList.SelectMany(i => i).Sum();
//result = 60


问:
How to write const ref without allowing temporary creation
I want to be able to supply functions which take an existing object of a given type by const reference.

i.e. I want by-const-ref-but-no-temporaries-created. [edited this phrase to clarify it!]

I can't think of any way to express that in C++ directly:

1 void fn(const T & t)

will create a temporary T from an S if a (non-explicit) T(S) exists.

2 void fn(T & t)

will only allow a non-const t as an argument (I need this to work for const t's as well).

3 void fn(T && t)

requires a non-const rvalue.

4 void fn(const T && t)

requires a const rvalue

Is there any way to do this - accept any argument by reference, const, without allowing a temp to be created?

Failed thoughts:

Supplying #2 and #4 without supply the other two, and now we have an unambiguous fn that takes a reference to any existing T (but won't silently generate a temporary)?

Nope, that isn't adequate either, because I need to also be able to bind to a const T & - Where the target object is itself been passed in by const reference to our caller...

I guess I see no way to achieve this except in the case where I can control T to ensure it doesn't supply an implicit T(S).

Am I right, or am I overlooking some solution?

答:
Judging from the comments, it seems like your actual question has nothing to do with rvalues and lvalues, but simply preventing implicit conversions. You can do this by changing the function to a function template, and then constraining the template with sfinae:

```<code>template <class T, std::enable_if_t<std::is_same<std::decay_t<T>, CString>::value, int> = 0>
void fn(const T&) {

}
</code>```

This will only work if called with some kind of CString, a type that implicit converts to a CString will not work.

Live example: http://coliru.stacked-crooked.com/a/80602c39cdc4d35e

That said, a better solution would simply be to change those functions to accept a string_view, which can be cheaply implicitly constructed from various kinds of strings. I don't know if it handles CString or not, but you can always right your own. It's a fairly simple class to write. http://en.cppreference.com/w/cpp/string/basic_string_view

Body:
Judging from the comments, it seems like your actual question has nothing to do with rvalues and lvalues, but simply preventing implicit conversions. You can do this by changing the function to a function template, and then constraining the template with sfinae:

template <class T, std::enable_if_t<std::is_same<std::decay_t<T>, CString>::value, int> = 0>
void fn(const T&) {

}

This will only work if called with some kind of CString, a type that implicit converts to a CString will not work.

Live example: http://coliru.stacked-crooked.com/a/80602c39cdc4d35e

That said, a better solution would simply be to change those functions to accept a string_view, which can be cheaply implicitly constructed from various kinds of strings. I don't know if it handles CString or not, but you can always right your own. It's a fairly simple class to write. http://en.cppreference.com/w/cpp/string/basic_string_view