问:
using android animation-list
I'm having a little trouble getting an animated loading spinner to work for a splash page. Nothing shows up when I try to run the following code.  Any suggestions?  It seems that quite a few people have issues with this on google but I do not understand why mine is failing to work.  Thanks!

animationloader.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/loadingspinner1" android:duration="200" />
<item android:drawable="@drawable/loadingspinner2" android:duration="200" />
<item android:drawable="@drawable/loadingspinner3" android:duration="200" />
<item android:drawable="@drawable/loadingspinner4" android:duration="200" />
<item android:drawable="@drawable/loadingspinner5" android:duration="200" />
<item android:drawable="@drawable/loadingspinner6" android:duration="200" />
<item android:drawable="@drawable/loadingspinner7" android:duration="200" />
<item android:drawable="@drawable/loadingspinner8" android:duration="200" />
<item android:drawable="@drawable/loadingspinner9" android:duration="200" />
<item android:drawable="@drawable/loadingspinner01" android:duration="200" />
<item android:drawable="@drawable/loadingspinner11" android:duration="200" />
<item android:drawable="@drawable/loadingspinner12" android:duration="200" />
</animation-list>
</code>```

SplashScreen.java

```<code>package com.secure.inmatecanteen;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class SplashScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    //Beginning the loading animation as we attempt to verify registration with SIP
    ImageView ivLoader = (ImageView) findViewById(R.id.IVloadinganimation);
    ivLoader.setBackgroundResource(R.anim.animationloader);

    AnimationDrawable frameAnimation = (AnimationDrawable) ivLoader.getBackground();
    frameAnimation.start();
}
}
</code>```

splashscreen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="@android:color/white" >

 <ImageView
android:id="@+id/iclogo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/iclogo"
android:adjustViewBounds="true"
/>

 <ImageView
android:id="@+id/IVloadinganimation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
/>

    </LinearLayout>
</code>```

答:
Don't set image resource in xml code.

My XML is:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:id="@+id/splashLayout"
android:background="@color/colorPrimary"
android:layout_height="match_parent">

<ImageView
    android:layout_width="230dp"
    android:layout_height="230dp"
    android:id="@+id/iv_splash"
    android:layout_marginTop="-80dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>
</code>```

In Activity i do

```<code>public class SplashActivity extends Activity {

ImageView iv_splash;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    iv_splash=(ImageView)findViewById(R.id.iv_splash);
    iv_splash.setBackgroundResource(R.drawable.splash);
    final AnimationDrawable progressAnimation =(AnimationDrawable)iv_splash.getBackground();
    progressAnimation.start();
    }
}
</code>```

Drawable file

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >

<item android:drawable="@drawable/logo" android:duration="400"/>
<item android:drawable="@drawable/logo1" android:duration="400"/>

</animation-list>
</code>```

It's Working Good  :)

Title: using android animation-list

Body:
I'm having a little trouble getting an animated loading spinner to work for a splash page. Nothing shows up when I try to run the following code.  Any suggestions?  It seems that quite a few people have issues with this on google but I do not understand why mine is failing to work.  Thanks!

animationloader.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/loadingspinner1" android:duration="200" />
<item android:drawable="@drawable/loadingspinner2" android:duration="200" />
<item android:drawable="@drawable/loadingspinner3" android:duration="200" />
<item android:drawable="@drawable/loadingspinner4" android:duration="200" />
<item android:drawable="@drawable/loadingspinner5" android:duration="200" />
<item android:drawable="@drawable/loadingspinner6" android:duration="200" />
<item android:drawable="@drawable/loadingspinner7" android:duration="200" />
<item android:drawable="@drawable/loadingspinner8" android:duration="200" />
<item android:drawable="@drawable/loadingspinner9" android:duration="200" />
<item android:drawable="@drawable/loadingspinner01" android:duration="200" />
<item android:drawable="@drawable/loadingspinner11" android:duration="200" />
<item android:drawable="@drawable/loadingspinner12" android:duration="200" />
</animation-list>

SplashScreen.java

package com.secure.inmatecanteen;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class SplashScreen extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    //Beginning the loading animation as we attempt to verify registration with SIP
    ImageView ivLoader = (ImageView) findViewById(R.id.IVloadinganimation);
    ivLoader.setBackgroundResource(R.anim.animationloader);

    AnimationDrawable frameAnimation = (AnimationDrawable) ivLoader.getBackground();
    frameAnimation.start();
}
}

splashscreen.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="@android:color/white" >

 <ImageView
android:id="@+id/iclogo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/iclogo"
android:adjustViewBounds="true"
/>

 <ImageView
android:id="@+id/IVloadinganimation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
/>

    </LinearLayout>

Body:
Don't set image resource in xml code.

My XML is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:gravity="center"
android:keepScreenOn="true"
android:id="@+id/splashLayout"
android:background="@color/colorPrimary"
android:layout_height="match_parent">

<ImageView
    android:layout_width="230dp"
    android:layout_height="230dp"
    android:id="@+id/iv_splash"
    android:layout_marginTop="-80dp"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

In Activity i do

public class SplashActivity extends Activity {

ImageView iv_splash;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    iv_splash=(ImageView)findViewById(R.id.iv_splash);
    iv_splash.setBackgroundResource(R.drawable.splash);
    final AnimationDrawable progressAnimation =(AnimationDrawable)iv_splash.getBackground();
    progressAnimation.start();
    }
}

Drawable file

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >

<item android:drawable="@drawable/logo" android:duration="400"/>
<item android:drawable="@drawable/logo1" android:duration="400"/>

</animation-list>

It's Working Good  :)


来源: stackexchange

问:
I use regex for removing duplicate words in a string
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

```<code> String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");
</code>```

答:
As Dawood ibn Kareem points out in the comments, if you want a space between words, why don't you add a space in your replacement pattern, like so:</p>

```<code>String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1 $1");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
but it remove white space. I don't want to remove white space! What should I do?

Original text

I like like like this movie, it was so so so good good
  good.

Remove duplicates

I likelike this movie, it was soso goodgood.

Here is my code:

 String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1$1");

Body:
As Dawood ibn Kareem points out in the comments, if you want a space between words, why don't you add a space in your replacement pattern, like so:

String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1 $1");


问:
Yii2 - get data from innerJoinWith
I have two models like this,
Pipe -> outGoingPipe

This is the active record :

```<code>$model= Pipe::find()
        ->select(["
                    *,
                    sum(piece) as pieces,
                    sum(bundle) as bundles
                "])
        ->innerJoinWith('outgoingPipe',false)
        ->groupBy(['bundle_group'])
        ->where(['in', 'outgoing_pipe_id', $selectedPipe])
        ->orderBy(['container' => SORT_ASC])
        ->all();
</code>```

Now, if I check by print_r($model),

I cannot see the column that came from outgoingPipe.

All the item from Pipe is success selected.

Please advise.

答:
outgoingPipe is available through relation:

```<code>$model->outgoingPipe
</code>```

Notice that by setting second argument in innerJoinWith() to false you lazy-load this relation - it is available only after $model->outgoingPipe has been called.

Title: Yii2 - get data from innerJoinWith

Body:
I have two models like this,
Pipe -> outGoingPipe

This is the active record :

$model= Pipe::find()
        ->select(["
                    *,
                    sum(piece) as pieces,
                    sum(bundle) as bundles
                "])
        ->innerJoinWith('outgoingPipe',false)
        ->groupBy(['bundle_group'])
        ->where(['in', 'outgoing_pipe_id', $selectedPipe])
        ->orderBy(['container' => SORT_ASC])
        ->all();

Now, if I check by print_r($model),

I cannot see the column that came from outgoingPipe.

All the item from Pipe is success selected.

Please advise.

Body:
outgoingPipe is available through relation:

$model->outgoingPipe

Notice that by setting second argument in innerJoinWith() to false you lazy-load this relation - it is available only after $model->outgoingPipe has been called.


问:
Partition processing on same node?
Spark makes the logical partitions with in RDD. I have two questions on it  :-

1) Everywhere on Google it is said that partition helps in parallel processing where each partition can be processed on separate node. My question is if i have multi core
machine, can not i process the partition in same node ?

2) Say I read file from file system and spark created one RDD with four partition. Now can each partition be divided  further to RDD ? For Example :-

```<code> firstRDD=sc.textFile("hdfs://...")
 //firstRDD contains four partition which are processed on four diff nodes
 secondRDD=firstRDD.filter(someFunction);
// Now will each node create separate secondRDD  which will have further paritions ?
</code>```

答: An input text file split into 4 partitions which may be within a single node or up to 4 nodes will not be split into more partitions and will thus be evaluated by the same executor that read them in initially. However, you may repartition the RDD/data frame to increase parallelization (such as having 64 partitions for your 64 executors). This will force a shuffle which can be costly but worthwhile particularly in computationally expensive work. A common situation where this is a problem is reading in unsplittable  files like GZIP files. A single executor has to read in the file (and do the processing!!) regardless of size. Thus repartitioning it is hugely beneficial for many GZIP workloads because it facilitates parallelized computation.

Title: Partition processing on same node?

Body:
Spark makes the logical partitions with in RDD. I have two questions on it  :-

1) Everywhere on Google it is said that partition helps in parallel processing where each partition can be processed on separate node. My question is if i have multi core
machine, can not i process the partition in same node ?

2) Say I read file from file system and spark created one RDD with four partition. Now can each partition be divided  further to RDD ? For Example :-

 firstRDD=sc.textFile("hdfs://...")
 //firstRDD contains four partition which are processed on four diff nodes
 secondRDD=firstRDD.filter(someFunction);
// Now will each node create separate secondRDD  which will have further paritions ?


问:
How do I list all of the items in a dictionary by biggest value to lowest value using Python and Django?
So I have this as my html file.

```<code><form method="post">
    {% csrf_token %}
    Problem: <input type="text" name="poi" autofocus>
    <input type="submit" value="Submit">
    <hr>
</form>
<br>
<ul>
    {% for u in sort %}
        <li>{{ u|safe }}</li>
    {% endfor %}
<ul>
</code>```

and I have my variable called sort which takes all of the items in a dictionary dictionary = {'hi': 5, 'hey': 3, 'hiya': 1} and sort them by highest to lowest value using the following.

```<code>for w in sorted(dictionary, key=dictionary.get, reverse=True):
    sort.append(w)
</code>```

Now the list is in order from highest to lowest values. As you can see in the html file, I am trying to print them all in order. What's going wrong is that it's not printing anything. What am I doing wrong?

EDIT: See the following for render.

```<code>try:
    return HttpResponse(request, 'patrec.html', {'sort':sort})
except:
    return render(request, 'patrec.html')
</code>```

答:
You could do that with

```<code>import heapq
list1=heapq.nlargest(len(dict1), dict1, key=dict1.get)
print(list1)
</code>```

Where, dict1 is the dictionary name.

As heapq comes built in with Python 3, you don't need to pip install anything.

Body:
So I have this as my html file.

<form method="post">
    {% csrf_token %}
    Problem: <input type="text" name="poi" autofocus>
    <input type="submit" value="Submit">

</form>

    {% for u in sort %}

{{ u|safe }}

    {% endfor %}

and I have my variable called sort which takes all of the items in a dictionary dictionary = {'hi': 5, 'hey': 3, 'hiya': 1} and sort them by highest to lowest value using the following.

for w in sorted(dictionary, key=dictionary.get, reverse=True):
    sort.append(w)

Now the list is in order from highest to lowest values. As you can see in the html file, I am trying to print them all in order. What's going wrong is that it's not printing anything. What am I doing wrong?

EDIT: See the following for render.

try:
    return HttpResponse(request, 'patrec.html', {'sort':sort})
except:
    return render(request, 'patrec.html')

Body:
You could do that with

import heapq
list1=heapq.nlargest(len(dict1), dict1, key=dict1.get)
print(list1)

Where, dict1 is the dictionary name.

As heapq comes built in with Python 3, you don't need to pip install anything.


问:
How to run Flex samples
Well, this is embarrassing. I want to get into Flex development but I'm having problems even opening up sample Flex projects! (I'm running on Snow Leopard and trying to use Flash Builder 4)

Here are the projects that I was looking at: http://www.adobe.com/devnet/facebook/samples.html

I downloaded a sample project.. but couldn't find anything to open! There was an mxml file that OS X just wasn't going to let me open. I had to change the extension to xml to see the contents of the file.

I did finally manage to get the project open and loaded. I created a new Flex project in Flash Builder 4, added a swc file to my libs directory, and replaced the content of the mxml and xml files with what I downloaded. That compiled fine and I was able to run the project.

Surely, there's an easier way of opening sample projects... right? But, doing a bit of searching, I found this tutorial... and he basically did the same thing I did. I hate to whine, but having to do all this to open a sample project..?

Hopefully someone here will tell me there's a friendlier, easier way of doing this! Thanks!

答:
Just go to File -> Import FlashBuilder Project.  Select "Project Folder", and point it to the folder that is the root (the one that includes the src folder).

It should load up with no problem.  Press the Run button.  It should compile and run.

Sometimes, code is shipped as an FXP, which is really just a zipped up folder.  When you open it with File -> Import FlashBuilder Project and Select "file", it unzips the files into a folder and opens it the same way.

Good luck!
Brian

ContentLicense: CC BY-SA 2.5

Title: How to run Flex samples


问:
How to make UIImage round
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

```<code> //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}
</code>```

}

Currently looks like this on a map

答:
To make a square a circle, just set its corner radius to half its width/height.  </p>

```<code>imageView.layer.cornerRadius = 12.5 //Half the sideLength of the imageView
imageView.layer.masksToBounds = true
</code>```

Title: How to make UIImage round

Body:
I am trying to make the annotation.image round. But I don't know how. How would i go about making a UIImage round.

 //Customize Annotation
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let annotationIdentifier = "Identifier"

    var annotationView: MKAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)

    if annotationView != nil {
        annotationView.annotation = annotation
    } else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)

        annotationView.image = profileImage.image

        annotationView.canShowCallout = true
        annotationView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)

        annotationView.autoresizesSubviews = true
        annotationView.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) as UIView
    }

      return annotationView
}

}

Currently looks like this on a map

Body:
To make a square a circle, just set its corner radius to half its width/height.

imageView.layer.cornerRadius = 12.5 //Half the sideLength of the imageView
imageView.layer.masksToBounds = true

ContentLicense: CC BY-SA 4.0


问:
How to split the start time and end time?
This question is about how to clean up the time data.
I am doing a database migration.

Old system:
For the time column, I have values such as:

```<code>9:30am - 12.30pm
9.30am - 12.30pm
9:30am-12.30pm
3pm to 7pm
3-9pm
1900-2000
1900h-2000h
etc etc...
</code>```

New System:

```<code>Start time | End Time
0930 | 1230
0930 | 1230
0930 | 1230
1500 | 1900
1500 | 2100
1900 | 2000
1900 | 2000
</code>```

Problem: How to efficiently convert the OLD values into NEW system where there are two columns with start and end time? (Or must I do it manually? The database has over 10000 records)

答:
Although the data is of inconsistent format it looks quite easy to convert to the required format, mostly with a series of simple find/replace.  For example in this order (or equivalent):

to > -

. > :

space > nothing

a > spacea

p > spacep

h > nothing

It is already more consistent:

```<code>9:30 am-12:30 pm
9:30 am-12:30 pm
9:30 am-12:30 pm
3 pm-7 pm
3-9 pm
1900-2000
1900-2000
</code>```

Using Excel's Text to Columns with - as the delimited would then get to (in separate text columns):

```<code>9:30 am  12:30 pm
9:30 am  12:30 pm
9:30 am  12:30 pm
3 pm     7 pm
3        9 pm
1900     2000
1900     2000
</code>```

Entering 1 somewhere in the spreadsheet and copying that cell before selecting cells containing M (with Find All and Ctrl+A) and then Paste Special, Multiply would coerce the selection into Time for formatting as as hhmm, to give:

```<code>     0930     1230
     0930     1230
     0930     1230
     1500     1900
3             2100
1900     2000
1900     2000
</code>```

The likes of 3 would need some manual intervention (to guess whether AM or PM) but once that was addressed export as .csv should provide data ready for insertion.

Body:
This question is about how to clean up the time data.
I am doing a database migration.

Old system:
For the time column, I have values such as:

9:30am - 12.30pm
9.30am - 12.30pm
9:30am-12.30pm
3pm to 7pm
3-9pm
1900-2000
1900h-2000h
etc etc...

New System:

Start time | End Time
0930 | 1230
0930 | 1230
0930 | 1230
1500 | 1900
1500 | 2100
1900 | 2000
1900 | 2000

Problem: How to efficiently convert the OLD values into NEW system where there are two columns with start and end time? (Or must I do it manually? The database has over 10000 records)

Body:
Although the data is of inconsistent format it looks quite easy to convert to the required format, mostly with a series of simple find/replace.  For example in this order (or equivalent):

to > -

. > :

space > nothing

a > spacea

p > spacep

h > nothing

It is already more consistent:

9:30 am-12:30 pm
9:30 am-12:30 pm
9:30 am-12:30 pm
3 pm-7 pm
3-9 pm
1900-2000
1900-2000

Using Excel's Text to Columns with - as the delimited would then get to (in separate text columns):

9:30 am  12:30 pm
9:30 am  12:30 pm
9:30 am  12:30 pm
3 pm     7 pm
3        9 pm
1900     2000
1900     2000

Entering 1 somewhere in the spreadsheet and copying that cell before selecting cells containing M (with Find All and Ctrl+A) and then Paste Special, Multiply would coerce the selection into Time for formatting as as hhmm, to give:

     0930     1230
     0930     1230
     0930     1230
     1500     1900
3             2100
1900     2000
1900     2000

The likes of 3 would need some manual intervention (to guess whether AM or PM) but once that was addressed export as .csv should provide data ready for insertion.


问:
SQL multiples select and group by using "first 1"
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

```<code>---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------
</code>```

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

答:
If You don't have any condition for "first 1" you can simply try.</p>

```<code>SELECT * FROM yourTable GROUP BY TYPE
</code>```

Body:
Despite the confusing title, I think it's pretty simple
I have a database in the following format:
(EXAMPLE)

---------------------------------
| X101| X102      | X103 | X104 |
---------------------------------
| COD | PROD_NAME | TYPE | INFO |

| 05  | PROD A1   | 05   | ABC  |
| 019 | TAPE 01   | 05   | ABC  |
| 052 | MASTER 0  | 03   | ABC  |
| 111 | APPLE     | 03   | ABC  |
| 150 | RANDOM0   | 05   | ABC  |
| 235 | ITEM661   | 03   | ABC  |
| 290 | ITEM874   | 03   | ABC  |
---------------------------------

I've tried in many ways, but I have not come up with a result. The database has a little more than 20 thousand products, I wanted to know how to
'select first 1' of each TYPE('group by TYPE' and show only the 'first 1' of each type)

Database is Firebird 1.5.

Body:
If You don't have any condition for "first 1" you can simply try.

SELECT * FROM yourTable GROUP BY TYPE


问:
How do you specify which django version to use?
I am using ubuntu and I have installed django from the Ubuntu Software Center. For some projects I want to use the django cloned from the trunk instead of the default one. How can i do that ? Do I need to unistall the one provided by ubuntu?</p>

答:
if wsgi in use
then set the path to the desired django installation in the django.wsgi file. eg

```<code>import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path[:0] = ['/path/to/django/version/','/path/to/project/']
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code>```

If modpython then set the path in the apache configuration file

```<code>PythonPath "['/path/to/django/version','/path/to/project'] + sys.path"
</code>```

The docs might help:
http://docs.djangoproject.com/en/dev/howto/deployment/modpython/

Body:
if wsgi in use
then set the path to the desired django installation in the django.wsgi file. eg

import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path[:0] = ['/path/to/django/version/','/path/to/project/']
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

If modpython then set the path in the apache configuration file

PythonPath "['/path/to/django/version','/path/to/project'] + sys.path"

The docs might help:
http://docs.djangoproject.com/en/dev/howto/deployment/modpython/


问:
Replace Amazon EC2 SSH hostnames (text file) from terminal output
I have deployed an Amazon EC2 cluster of 3 Ubuntu machines (2 of them make up the cluster and the last one is just a client who submits jobs and manages their storage). I connect to all of them via password-less SSH.

What happens is that every time I restart these machines they get new public hostnames from Amazon which I want to replace in my SSH configuration file located in ~/.ssh/config

So far, I figured out a way to get their names and hostnames using Amazon CLI with the following command at my local machine (CentOS 7):

aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None"

This prints something like

```<code>ec2-XX-XX-XXX-XXX.us-east-2.compute.amazonaws.com
Name    datanode1
ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
Name    namenode
ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
Name    client
</code>```

i.e. the hostname, a new line, the corresponding name and so on. The IP fields above like XX-XX-XXX-XXX and so on, are basically 4 hyphen separated numbers of 2 or 3 digits. The grep command I have simply removes the last useless line. Now I want to find a way to replace these hostnames to the SSH configuration file or maybe regenerate it, which looks like

```<code>Host namenode
  HostName ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host datanode1
  HostName ec2-XX-XX-XXX-XX.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host client
  HostName ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem
</code>```

Please note that I don't know how the Amazon CLI command sorts the output. But of course, I can change the order of the machines in my SSH file or maybe it is a good idea to delete it and recreate it.

答:
Below is what I finally figured out and it works. This is Bash script you can just save as .sh file like script.sh and execute. If it can't run simply do chmod +x script.sh. I have added comments to clarify what I am doing.

```<code>#Ask Amazon CLI for your hostnames, remove the last line, replace the "Name\t" with "", combine every 2 consecutive lines and save to a txt file
aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None" | sed 's/Name\t//g' | sed 'N;s/\n/ /' > 'ec2instances.txt';

#Change the following variables based on your cluster
publicKey="mykey.pem";
username="ubuntu";

#Remove any preexisting SSH configuration file
rm config
touch config

while read line
do
    #Read the line, keep the 1st word and save it as the public DNS
    publicDns=$(echo "$line" | cut -d " " -f1);

    #Read the line, keep the 2nd word and save it as the hostname you will be using locally to connect to your Amazon EC2
    instanceHostname=$(echo "$line" | cut -d " " -f2);

    #OK, we are now ready to store to SSH known hosts
    sshEntry="Host $instanceHostname\n";
    sshEntry="$sshEntry HostName $publicDns\n";
    sshEntry="$sshEntry User $username\n";
    sshEntry="$sshEntry IdentityFile ~/.ssh/$publicKey\n";

    #Attach to the EOF, '-e' enables interpretation of backslash escapes
    echo -e "$sshEntry" >> config

#Below is the txt file you will be traversing in the loop
done < ec2instances.txt

#Done
rm ~/.ssh/config
mv config ~/.ssh/config
rm ec2instances.txt
</code>```

Body:
I have deployed an Amazon EC2 cluster of 3 Ubuntu machines (2 of them make up the cluster and the last one is just a client who submits jobs and manages their storage). I connect to all of them via password-less SSH.

What happens is that every time I restart these machines they get new public hostnames from Amazon which I want to replace in my SSH configuration file located in ~/.ssh/config

So far, I figured out a way to get their names and hostnames using Amazon CLI with the following command at my local machine (CentOS 7):

aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None"

This prints something like

ec2-XX-XX-XXX-XXX.us-east-2.compute.amazonaws.com
Name    datanode1
ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
Name    namenode
ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
Name    client

i.e. the hostname, a new line, the corresponding name and so on. The IP fields above like XX-XX-XXX-XXX and so on, are basically 4 hyphen separated numbers of 2 or 3 digits. The grep command I have simply removes the last useless line. Now I want to find a way to replace these hostnames to the SSH configuration file or maybe regenerate it, which looks like

Host namenode
  HostName ec2-YY-YY-YYY-YYY.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host datanode1
  HostName ec2-XX-XX-XXX-XX.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Host client
  HostName ec2-ZZ-ZZ-ZZZ-ZZZ.us-east-2.compute.amazonaws.com
  User ubuntu
  IdentityFile ~/.ssh/mykey.pem

Please note that I don't know how the Amazon CLI command sorts the output. But of course, I can change the order of the machines in my SSH file or maybe it is a good idea to delete it and recreate it.

Body:
Below is what I finally figured out and it works. This is Bash script you can just save as .sh file like script.sh and execute. If it can't run simply do chmod +x script.sh. I have added comments to clarify what I am doing.

#Ask Amazon CLI for your hostnames, remove the last line, replace the "Name\t" with "", combine every 2 consecutive lines and save to a txt file
aws ec2 describe-instances --query "Reservations[*].Instances[*].[PublicDnsName,Tags]" --output=text | grep -vwE "None" | sed 's/Name\t//g' | sed 'N;s/\n/ /' > 'ec2instances.txt';

#Change the following variables based on your cluster
publicKey="mykey.pem";
username="ubuntu";

#Remove any preexisting SSH configuration file
rm config
touch config

while read line
do
    #Read the line, keep the 1st word and save it as the public DNS
    publicDns=$(echo "$line" | cut -d " " -f1);

    #Read the line, keep the 2nd word and save it as the hostname you will be using locally to connect to your Amazon EC2
    instanceHostname=$(echo "$line" | cut -d " " -f2);

    #OK, we are now ready to store to SSH known hosts
    sshEntry="Host $instanceHostname\n";
    sshEntry="$sshEntry HostName $publicDns\n";
    sshEntry="$sshEntry User $username\n";
    sshEntry="$sshEntry IdentityFile ~/.ssh/$publicKey\n";

    #Attach to the EOF, '-e' enables interpretation of backslash escapes
    echo -e "$sshEntry" >> config

#Below is the txt file you will be traversing in the loop
done < ec2instances.txt

#Done
rm ~/.ssh/config
mv config ~/.ssh/config
rm ec2instances.txt


问:
ExpertPDF - How to know page number based on content in HTML
```<code>Suppose I have a HTML that have some heading & text like:

Heading 1
text......

Heading 2
text.....

Heading 3
text.....
</code>```

Now I have to print this template in PDF, during print out, I have to add index page which actually refer page number with heading. Means print out should be like this.

```<code>Heading 1 ....... 1 [page number]
Heading 2 ....... 2
Heading 3 ....... 3

Heading 1
text......

Heading 2
text.....

Heading 3
text.....
</code>```

So here I want to know, how to know page number based on text in HTML,  like heading 1 belong to which page number & for others.

```<code>Any suggestion or idea really appreciated.
</code>```

答:
pdfConverter.PdfFooterOptions.PageNumberTextFontSize = 10;
pdfConverter.PdfFooterOptions.ShowPageNumber = true;

Its done inside the body of this method :-

```<code>private void AddFooter(PdfConverter pdfConverter)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";

//enable footer
pdfConverter.PdfDocumentOptions.ShowFooter = true;
// set the footer height in points
pdfConverter.PdfFooterOptions.FooterHeight = 60;
//write the page number
pdfConverter.PdfFooterOptions.TextArea = new TextArea(0, 30, "This is page &p; of &P; ",
new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true;
pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right;
// set the footer HTML area
pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(headerAndFooterHtmlUrl);
pdfConverter.PdfFooterOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked;
}
</code>```

See this page for more details
http://www.expertpdf.net/expertpdf-html-to-pdf-converter-headers-and-footers/

Body:
Suppose I have a HTML that have some heading & text like:

Heading 1
text......

Heading 2
text.....

Heading 3
text.....

Now I have to print this template in PDF, during print out, I have to add index page which actually refer page number with heading. Means print out should be like this.

Heading 1 ....... 1 [page number]
Heading 2 ....... 2
Heading 3 ....... 3

Heading 1
text......

Heading 2
text.....

Heading 3
text.....

So here I want to know, how to know page number based on text in HTML,  like heading 1 belong to which page number & for others.

Any suggestion or idea really appreciated.

Body:
pdfConverter.PdfFooterOptions.PageNumberTextFontSize = 10;
pdfConverter.PdfFooterOptions.ShowPageNumber = true;

Its done inside the body of this method :-

private void AddFooter(PdfConverter pdfConverter)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";

//enable footer
pdfConverter.PdfDocumentOptions.ShowFooter = true;
// set the footer height in points
pdfConverter.PdfFooterOptions.FooterHeight = 60;
//write the page number
pdfConverter.PdfFooterOptions.TextArea = new TextArea(0, 30, "This is page &p; of &P; ",
new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true;
pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right;
// set the footer HTML area
pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(headerAndFooterHtmlUrl);
pdfConverter.PdfFooterOptions.HtmlToPdfArea.EmbedFonts = cbEmbedFonts.Checked;
}

See this page for more details
http://www.expertpdf.net/expertpdf-html-to-pdf-converter-headers-and-footers/


问:
ffmpeg: set the language of an audio stream
I have 3 files: video.mp4, audionl.mp4 & audioeng.mp4.
I tried adding them all together in 1 output.mp4 file like this:

```<code>ffmpeg -y -i video.mp4 -i audionl.mp4 -i audioeng.mp4  -map 0:v -map 1:a -map 2:a -metadata:s:a:0 language=nl -metadata:s:a:0 title="NL" -metadata:s:a:1 language=eng  -metadata:s:a:1 title="ENG" -acodec copy -bsf:a aac_adtstoasc -vcodec copy  -movflags faststart output.mp4 2>&1
</code>```

This is the output I see from ffmpeg:

```<code>ffmpeg version 2.6.9 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 4.9.2 (Debian 4.9.2-10)
  configuration: --prefix=/usr --extra-cflags='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security ' --extra-ldflags='-Wl,-z,relro' --cc='ccache cc' --enable-shared --enable-libmp3lame --enable-gpl --enable-nonfree --enable-libvorbis --enable-pthreads --enable-libfaac --enable-libxvid --enable-postproc --enable-x11grab --enable-libgsm --enable-libtheora --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libx264 --enable-libspeex --enable-nonfree --disable-stripping --enable-libvpx --enable-libschroedinger --disable-encoder=libschroedinger --enable-version3 --enable-libopenjpeg --enable-librtmp --enable-avfilter --enable-libfreetype --enable-libvo-aacenc --disable-decoder=amrnb --enable-libvo-amrwbenc --enable-libaacplus --libdir=/usr/lib/x86_64-linux-gnu --disable-vda --enable-libbluray --enable-libcdio --enable-gnutls --enable-frei0r --enable-openssl --enable-libass --enable-libopus --enable-fontconfig --enable-libpulse --disable-mips32r2 --disable-mipsdspr1 --disable-mipsdspr2 --enable-libvidstab --enable-libzvbi --enable-avresample --disable-htmlpages --disable-podpages --enable-libutvideo --enable-libfdk-aac --enable-libx265 --enable-libiec61883 --enable-vaapi --enable-libdc1394 --disable-altivec --shlibdir=/usr/lib/x86_64-linux-gnu
  libavutil      54. 20.100 / 54. 20.100
  libavcodec     56. 26.100 / 56. 26.100
  libavformat    56. 25.101 / 56. 25.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 11.102 /  5. 11.102
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomavc1mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.80, start: 0.000000, bitrate: 1172 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : VideoHandler
      encoder         : VideoHandler
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from 'audionl.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomM4A mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.80, start: 0.000000, bitrate: 96 kb/s
    Stream #1:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 93 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
Input #2, mov,mp4,m4a,3gp,3g2,mj2, from 'audioeng.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomM4A mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.78, start: 0.000000, bitrate: 64 kb/s
    Stream #2:0(eng): Audio: aac (HE-AAC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
Output #0, mp4, to 'output.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomavc1mp42dash
    encoder         : Lavf56.25.101
    Stream #0:0(eng): Video: h264 ([33][0][0][0] / 0x0021), yuv420p, 640x360 [SAR 1:1 DAR 16:9], q=2-31, 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 90k tbc (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : VideoHandler
      encoder         : VideoHandler
    Stream #0:1(nl): Audio: aac ([64][0][0][0] / 0x0040), 48000 Hz, stereo, 93 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
      title           : NL
    Stream #0:2(eng): Audio: aac ([64][0][0][0] / 0x0040), 48000 Hz, stereo, 62 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
      title           : ENG
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #1:0 -> #0:1 (copy)
  Stream #2:0 -> #0:2 (copy)
Press [q] to stop, [?] for help
[mp4 @ 0xbb1320] Starting second pass: moving the moov atom to the beginning of the file
frame=31320 fps=20993 q=-1.0 Lsize=  204217kB time=00:20:52.79 bitrate=1335.4kbits/s
video:178734kB audio:23867kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.797284%
</code>```

As you can see in there: "Stream #0:0(eng)", "Stream #0:1(nl)" & "Stream #0:2(eng)".
So that looks fine.

But when I open it in VLC, I see under Audio tracks:
NL - [English]
ENG - [English]

So I went back to check on ffmpeg with "ffmpeg -i output.mp4":

```<code>Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'output.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.25.101
  Duration: 00:20:52.80, start: 0.000000, bitrate: 1335 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 93 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
    Stream #0:2(eng): Audio: aac (HE-AAC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
</code>```

And here they are English again...

Afterwards I tried this:

```<code>ffmpeg -y -i audionl.mp4 -c:a copy -metadata:s:a:0 language=nl output.mp4
</code>```

But also that failed to set the correct language on the output file...
I'm at a loss here and hope someone can help me set these languages correctly.

Thanks a lot!

答:
FFmpeg expects ISO 639-2 codes for languages, so for Dutch, it's either

```<code>-metadata:s:a:0 language=dut
</code>```

or

```<code>-metadata:s:a:0 language=nld
</code>```

Body:
I have 3 files: video.mp4, audionl.mp4 & audioeng.mp4.
I tried adding them all together in 1 output.mp4 file like this:

ffmpeg -y -i video.mp4 -i audionl.mp4 -i audioeng.mp4  -map 0:v -map 1:a -map 2:a -metadata:s:a:0 language=nl -metadata:s:a:0 title="NL" -metadata:s:a:1 language=eng  -metadata:s:a:1 title="ENG" -acodec copy -bsf:a aac_adtstoasc -vcodec copy  -movflags faststart output.mp4 2>&1

This is the output I see from ffmpeg:

ffmpeg version 2.6.9 Copyright (c) 2000-2016 the FFmpeg developers
  built with gcc 4.9.2 (Debian 4.9.2-10)
  configuration: --prefix=/usr --extra-cflags='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security ' --extra-ldflags='-Wl,-z,relro' --cc='ccache cc' --enable-shared --enable-libmp3lame --enable-gpl --enable-nonfree --enable-libvorbis --enable-pthreads --enable-libfaac --enable-libxvid --enable-postproc --enable-x11grab --enable-libgsm --enable-libtheora --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libx264 --enable-libspeex --enable-nonfree --disable-stripping --enable-libvpx --enable-libschroedinger --disable-encoder=libschroedinger --enable-version3 --enable-libopenjpeg --enable-librtmp --enable-avfilter --enable-libfreetype --enable-libvo-aacenc --disable-decoder=amrnb --enable-libvo-amrwbenc --enable-libaacplus --libdir=/usr/lib/x86_64-linux-gnu --disable-vda --enable-libbluray --enable-libcdio --enable-gnutls --enable-frei0r --enable-openssl --enable-libass --enable-libopus --enable-fontconfig --enable-libpulse --disable-mips32r2 --disable-mipsdspr1 --disable-mipsdspr2 --enable-libvidstab --enable-libzvbi --enable-avresample --disable-htmlpages --disable-podpages --enable-libutvideo --enable-libfdk-aac --enable-libx265 --enable-libiec61883 --enable-vaapi --enable-libdc1394 --disable-altivec --shlibdir=/usr/lib/x86_64-linux-gnu
  libavutil      54. 20.100 / 54. 20.100
  libavcodec     56. 26.100 / 56. 26.100
  libavformat    56. 25.101 / 56. 25.101
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 11.102 /  5. 11.102
  libavresample   2.  1.  0 /  2.  1.  0
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  1.100 /  1.  1.100
  libpostproc    53.  3.100 / 53.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomavc1mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.80, start: 0.000000, bitrate: 1172 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : VideoHandler
      encoder         : VideoHandler
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from 'audionl.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomM4A mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.80, start: 0.000000, bitrate: 96 kb/s
    Stream #1:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 93 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
Input #2, mov,mp4,m4a,3gp,3g2,mj2, from 'audioeng.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomM4A mp42dash
    creation_time   : 2017-06-04 06:35:06
  Duration: 00:20:52.78, start: 0.000000, bitrate: 64 kb/s
    Stream #2:0(eng): Audio: aac (HE-AAC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
Output #0, mp4, to 'output.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isomavc1mp42dash
    encoder         : Lavf56.25.101
    Stream #0:0(eng): Video: h264 ([33][0][0][0] / 0x0021), yuv420p, 640x360 [SAR 1:1 DAR 16:9], q=2-31, 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 90k tbc (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : VideoHandler
      encoder         : VideoHandler
    Stream #0:1(nl): Audio: aac ([64][0][0][0] / 0x0040), 48000 Hz, stereo, 93 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
      title           : NL
    Stream #0:2(eng): Audio: aac ([64][0][0][0] / 0x0040), 48000 Hz, stereo, 62 kb/s (default)
    Metadata:
      creation_time   : 2017-06-04 06:35:06
      handler_name    : SoundHandler
      title           : ENG
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #1:0 -> #0:1 (copy)
  Stream #2:0 -> #0:2 (copy)
Press [q] to stop, [?] for help
[mp4 @ 0xbb1320] Starting second pass: moving the moov atom to the beginning of the file
frame=31320 fps=20993 q=-1.0 Lsize=  204217kB time=00:20:52.79 bitrate=1335.4kbits/s
video:178734kB audio:23867kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.797284%

As you can see in there: "Stream #0:0(eng)", "Stream #0:1(nl)" & "Stream #0:2(eng)".
So that looks fine.

But when I open it in VLC, I see under Audio tracks:
NL - [English]
ENG - [English]

So I went back to check on ffmpeg with "ffmpeg -i output.mp4":

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'output.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.25.101
  Duration: 00:20:52.80, start: 0.000000, bitrate: 1335 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 1168 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 93 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
    Stream #0:2(eng): Audio: aac (HE-AAC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 62 kb/s (default)
    Metadata:
      handler_name    : SoundHandler

And here they are English again...

Afterwards I tried this:

ffmpeg -y -i audionl.mp4 -c:a copy -metadata:s:a:0 language=nl output.mp4

But also that failed to set the correct language on the output file...
I'm at a loss here and hope someone can help me set these languages correctly.

Thanks a lot!

Body:
FFmpeg expects ISO 639-2 codes for languages, so for Dutch, it's either

-metadata:s:a:0 language=dut

or

-metadata:s:a:0 language=nld


问:
How to calculate maximum from pivot table in python
I have written code to calculate the count of feature3 groupby feature1 and feature2

```<code>pd.pivot_table(data=train, index=['feature1', 'feature2'], values=['feature3'], aggfunc='count')
</code>```

Who's output is:

```<code>feature1 feature2 feature3
129001  0   4
        1   10
        2   11
        3   22
        4   26
        5   38
129002  0   6
        2   45
        5   25
</code>```

Now I want to calculate max of feature3 groupby feature1

```<code>feature1 feature3
129001    38
129002    45
</code>```

Body:
I have written code to calculate the count of feature3 groupby feature1 and feature2

pd.pivot_table(data=train, index=['feature1', 'feature2'], values=['feature3'], aggfunc='count')

Who's output is:

feature1 feature2 feature3
129001  0   4
        1   10
        2   11
        3   22
        4   26
        5   38
129002  0   6
        2   45
        5   25

Now I want to calculate max of feature3 groupby feature1

feature1 feature3
129001    38
129002    45

Body:
You can do it this way:

In [21]: df
Out[21]:
                   feature3
feature1 feature2
129001   0                4
         1               10
         2               11
         3               22
         4               26
         5               38
129002   0                6
         2               45
         5               25

In [22]: df.max(level='feature1')
Out[22]:
          feature3
feature1
129001          38
129002          45


问:
When using java 8 map, filter and collect, does it create new objects or modify existing objects?
I have the code below where I am doing filtering using a filter and replace function inside my map and then I am doing a collect to replace my original array. My question is whether my original objects in inputArr are being discarded and new objects are created or are the same objects being modified when I am doing a collect?</p>

```<code>public static void test () {
    inputArr.stream().filter(s -> toRemove.contains(s)).
            forEach(u -> u.replaceAll("2","X"));
    inputArr = inputArr.stream().map(x -> filterReplace(x,toRemove)).collect(Collectors.toList());
    System.out.println(inputArr);
}

static String filterReplace(String input, Set<String> toRemove) {
    if (toRemove.contains(input)) {
        return "X";
    }
    else
        return input;
}
</code>```

答:
Any method that modifies a string must return a new object, because strings are immutable by definition. Thus,

```<code>forEach(u -> u.replaceAll("2","X"))
</code>```

creates a new string for each element in the stream and then immediately discards it, because the return value is ignored.

As for the filterReplace() method in the second stream, that's not modifying at all, it simply returns the input string or another predefined value ("X"). The original objects in inputArr may be discarded once that variable is reassigned, but there are no new objects created within the stream.

Body:
I have the code below where I am doing filtering using a filter and replace function inside my map and then I am doing a collect to replace my original array. My question is whether my original objects in inputArr are being discarded and new objects are created or are the same objects being modified when I am doing a collect?

public static void test () {
    inputArr.stream().filter(s -> toRemove.contains(s)).
            forEach(u -> u.replaceAll("2","X"));
    inputArr = inputArr.stream().map(x -> filterReplace(x,toRemove)).collect(Collectors.toList());
    System.out.println(inputArr);
}

static String filterReplace(String input, Set<String> toRemove) {
    if (toRemove.contains(input)) {
        return "X";
    }
    else
        return input;
}

Body:
Any method that modifies a string must return a new object, because strings are immutable by definition. Thus,

forEach(u -> u.replaceAll("2","X"))

creates a new string for each element in the stream and then immediately discards it, because the return value is ignored.

As for the filterReplace() method in the second stream, that's not modifying at all, it simply returns the input string or another predefined value ("X"). The original objects in inputArr may be discarded once that variable is reassigned, but there are no new objects created within the stream.


问:
Java throws Exception :Selenium 3.4.0,Gecko driver 16.01,FF 53.01
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.</p>

```<code>    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");
</code>```

答:
Initiate FirefoxDriver instead of marionette driver.

```<code>WebDriver driver = new FirefoxDriver(capabilities);
</code>```

Hope this helps you. Thanks.

Body:
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");

Body:
Initiate FirefoxDriver instead of marionette driver.

WebDriver driver = new FirefoxDriver(capabilities);

Hope this helps you. Thanks.


问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答:
If you need to do many append operations to build a large string, you can use StringIO or cStringIO. The interface is like a file. ie: you write to append text to it.

If you're just appending two strings then just use +.

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.


问:
How sync TabLayout with ViewPager when using TabItem
I want to use TabLayout with TabItem with following code:

```<code>  <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_primary"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/gray_light">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:icon="@drawable/ic_language" />

        <!-- other tabs ... -->

    </android.support.design.widget.TabLayout>
</code>```

And this is show me Icons correctly like this:

But the problem is when I want to add my TabLayout to ViewPager, with following code, all of them exist and clickable but disappear. Did I miss something?

```<code> MyPagerAdapter adapter = new MyPagerAdapter(getFragmentManager());
 pager.setAdapter(adapter);

 tabLayout.setupWithViewPager(pager);
</code>```

and this is result:

答:
This is helpful :

/////// Syncing!!!

Replace

```<code>setupWithViewPager();
</code>```

With

```<code>tablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
</code>```

Body:
I want to use TabLayout with TabItem with following code:

  <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_primary"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/gray_light">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:icon="@drawable/ic_language" />

    </android.support.design.widget.TabLayout>

And this is show me Icons correctly like this:

But the problem is when I want to add my TabLayout to ViewPager, with following code, all of them exist and clickable but disappear. Did I miss something?

 MyPagerAdapter adapter = new MyPagerAdapter(getFragmentManager());
 pager.setAdapter(adapter);

 tabLayout.setupWithViewPager(pager);

and this is result:

Body:
This is helpful :

/////// Syncing!!!

Replace

setupWithViewPager();

With

tablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));


问:
ng-click is not working in table header
Hi I am new to AngularJS. I am creating a sample application to sort the data in a table by clicking the table header. On the first click it should arrange it in ascending order. Second click it should arrange it to descending.
Below provided are the cshtml code.

```<code><div ng-controller="myController">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th ng-click="sortData('firstname')">First Name</th>
<th>Last Name</th>
<th>Salary</th>
 </tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees|orderBy:'sortColumn'">
<td>{{employee.firstname | lowercase}}</td>
<td>{{employee.lastname| uppercase}}</td>
<td>{{employee.salary |currency:"$":1}}</td>
</tr>
</tbody>
</table>
</div>
</code>```

Below provided are script for module

```<code>var myApp = angula
 .module("myModule", [])
 .controller("myController", function ($scope) {
  var employee = [

 { firstname: "First", lastname: "Trueman", salary: "20001" },
 { firstname: "Second", lastname: "someone", salary: "20002" },
 { firstname: "Third", lastname: "apple", salary: "20003" },
 { firstname: "Fourth", lastname: "parrot", salary: "20004" },
 { firstname: "Fifth", lastname: "mat", salary: "20005" },
 ];
 $scope.employees = employee;
 $scope.sortColumn = "firstname";
 $scope.reverseSort = false;
 $scope.sortData = function (column) {
 $scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
});
</code>```

For some reason ng-click is not working. Does anyone face the same issue before., If yes can you help me with this.

答:
There were two things needed to be fixed:

sortColumn should be used without the single quote as it is a variable
add reverseSort variable to the orderBy.

```<code><table class="table table-bordered table-striped table-hover">
<thead>
  <tr>
    <th ng-click="sortData('firstname')">First Name</th>
    <th>Last Name</th>
    <th>Salary</th>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="employee in employees|orderBy: sortColumn : reverseSort">
    <td>{{employee.firstname | lowercase}}</td>
    <td>{{employee.lastname| uppercase}}</td>
    <td>{{employee.salary |currency:"$":1}}</td>
  </tr>
</tbody>
</code>```

I've created a working plnkr here.

Title: ng-click is not working in table header

Body:
Hi I am new to AngularJS. I am creating a sample application to sort the data in a table by clicking the table header. On the first click it should arrange it in ascending order. Second click it should arrange it to descending.
Below provided are the cshtml code.

First Name
Last Name
Salary

{{employee.firstname | lowercase}}
{{employee.lastname| uppercase}}
{{employee.salary |currency:"$":1}}

Below provided are script for module

var myApp = angula
 .module("myModule", [])
 .controller("myController", function ($scope) {
  var employee = [

 { firstname: "First", lastname: "Trueman", salary: "20001" },
 { firstname: "Second", lastname: "someone", salary: "20002" },
 { firstname: "Third", lastname: "apple", salary: "20003" },
 { firstname: "Fourth", lastname: "parrot", salary: "20004" },
 { firstname: "Fifth", lastname: "mat", salary: "20005" },
 ];
 $scope.employees = employee;
 $scope.sortColumn = "firstname";
 $scope.reverseSort = false;
 $scope.sortData = function (column) {
 $scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
});

For some reason ng-click is not working. Does anyone face the same issue before., If yes can you help me with this.

Body:
There were two things needed to be fixed:

sortColumn should be used without the single quote as it is a variable
add reverseSort variable to the orderBy.

<table class="table table-bordered table-striped table-hover">
<thead>
  <tr>
    <th ng-click="sortData('firstname')">First Name</th>
    <th>Last Name</th>
    <th>Salary</th>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="employee in employees|orderBy: sortColumn : reverseSort">
    <td>{{employee.firstname | lowercase}}</td>
    <td>{{employee.lastname| uppercase}}</td>
    <td>{{employee.salary |currency:"$":1}}</td>
  </tr>
</tbody>

I've created a working plnkr here.


问:
Passing large amount of rows as a User defined Table value Parameter to SP in Sql Azure taking long time
We need to pass around 80K rows to a SP in sql Azure. Previously we are able to do so without any glitches. But currently once we call the SP from c#, it's some times taking 10-15 minutes to start execution in DB and many times the SP is not getting Executed.
one thing I have noticed once we make the call from c#, some operation is getting started in DB. And If I try to alter the Sp, the mentioned operation blocks it. The info about the blocking sessionid is not available in sp_who2 or from "sys.dm_exec_requests"
Any help to resolve this issue is highly appreciated.</p>

答: I am able to fix the issue with Setting the maxLength of the Columns of the datatable which I sent to DB</p>


问:
Testing same API for multiple response sets
We've been trying to test an API exposed from a microservice (say GET /contacts) which is being consumed by another microservice.

In order to avoid integration tests, we created consumer-driven contract tests where the consumer microservice created pacts and published them to a broker from where the producer would verify the pact separately.

We've used Pact IO to achieve this and it has been quite good so far.

Now we are facing issues when trying to do exhaustive tests where we would want to see how an empty list is returned from GET /contacts.

The problem is: while adding interactions, we could use Provider States but we couldn't find a way to differentiate between writing tests for getting a list of contacts from GET /contacts once and getting an empty list in another test.

This is how we create pact tests in our consumer microservice:

```<code>mockServer.start()
        .then(() => {
          provider = pact({
            // config
          })
          return provider.addInteraction({
            state: 'Get all contacts',
            uponReceiving: 'Get all contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: //list of all contacts
            }
          })
        .then(() => {
          return provider.addInteraction({
            state: 'Get empty list of contacts',
            uponReceiving: 'Get empty list of contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: [] // empty list
            }
          })
        })
</code>```

We cannot find a way to differentiate between these interations in our tests! :(

Any help would be appreciated!

Thanks.

答:
Assume you're using something like Mocha, you should separate these interactions into individual tests - e.g. call addInteraction in each describe block that's contextual to the test case you're running (possibly in the before to make your tests clearer).

Your general structure might look like the below (pseudo-code):

```<code>context("Contacts exist")
  describe("call some API")
    before()
      provider.addInteraction(interactionWithContacts)

    it("Returns a list of contact objects")
      # your test code here
      # Verify - this will also clear interactions so
      # your next test won't conflict
      provider.verify()

context("No contacts exist")
  describe("call some API")
    before()
      provider.addInteraction(interactionWithNoContacts)

    it("Returns an empty list of contacts")
      # your test code here
      # Verify - this will also clear interactions so
      # your next test won't conflict
      provider.verify()
</code>```

Body:
We've been trying to test an API exposed from a microservice (say GET /contacts) which is being consumed by another microservice.

In order to avoid integration tests, we created consumer-driven contract tests where the consumer microservice created pacts and published them to a broker from where the producer would verify the pact separately.

We've used Pact IO to achieve this and it has been quite good so far.

Now we are facing issues when trying to do exhaustive tests where we would want to see how an empty list is returned from GET /contacts.

The problem is: while adding interactions, we could use Provider States but we couldn't find a way to differentiate between writing tests for getting a list of contacts from GET /contacts once and getting an empty list in another test.

This is how we create pact tests in our consumer microservice:

mockServer.start()
        .then(() => {
          provider = pact({
            // config
          })
          return provider.addInteraction({
            state: 'Get all contacts',
            uponReceiving: 'Get all contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: //list of all contacts
            }
          })
        .then(() => {
          return provider.addInteraction({
            state: 'Get empty list of contacts',
            uponReceiving: 'Get empty list of contacts',
            withRequest: {
              method: 'GET',
              path: '/contacts',
              headers: {
                Accept: 'application/json; charset=utf-8'
              }
            },
            willRespondWith: {
              status: 200,
              body: [] // empty list
            }
          })
        })

We cannot find a way to differentiate between these interations in our tests! :(

Any help would be appreciated!

Thanks.

Body:
Assume you're using something like Mocha, you should separate these interactions into individual tests - e.g. call addInteraction in each describe block that's contextual to the test case you're running (possibly in the before to make your tests clearer).

Your general structure might look like the below (pseudo-code):

context("Contacts exist")
  describe("call some API")
    before()
      provider.addInteraction(interactionWithContacts)

    it("Returns a list of contact objects")
      # your test code here
      # Verify - this will also clear interactions so
      # your next test won't conflict
      provider.verify()

context("No contacts exist")
  describe("call some API")
    before()
      provider.addInteraction(interactionWithNoContacts)

    it("Returns an empty list of contacts")
      # your test code here
      # Verify - this will also clear interactions so
      # your next test won't conflict
      provider.verify()


问:
python about multiple %s in a string
```<code>str = 'I love %s and %s, he loves %s and %s.'
</code>```

I want to use this format to display

I love apple and pitch, he loves apple and pitch.

Only add two variable please, but need a way to use it twice in one sentence.

答:
```<code>>>> str = 'I love %(1)s and %(2)s, he loves %(1)s and %(2)s.' % {"1" : "apple", "2" : "pitch"}
>>> str
'I love apple and pitch, he loves apple and pitch.'
</code>```

Of course you can use other names besides '1' and '2'. :)

Title: python about multiple %s in a string

Body:
str = 'I love %s and %s, he loves %s and %s.'

I want to use this format to display

I love apple and pitch, he loves apple and pitch.

Only add two variable please, but need a way to use it twice in one sentence.

Body:
>>> str = 'I love %(1)s and %(2)s, he loves %(1)s and %(2)s.' % {"1" : "apple", "2" : "pitch"}
>>> str
'I love apple and pitch, he loves apple and pitch.'

Of course you can use other names besides '1' and '2'. :)


问:
Read from a file which is being actively written to
I have two programs: one (program1) writes to a file continuously, and I want the other program (program2) to read the file continuously. What is happening is that my second program is only reading up to the data point which was written when the second code was executed and stops instead of continuously reading.

Is there any way to achieve the thing?

Basically, I want the output of program1 to be used as the input of program2. Is there any way to read and write in RAM instead of file as disk read costs more time.

Code 2:

```<code>#include <stdio.h>

int main(){

    FILE *fptr;

    fptr = fopen("gbbct1.seq","r");

    char c;
    c = fgetc(fptr);

    while (c != EOF){

        printf("%c", c);
        c = fgetc(fptr);

    }

}
</code>```

I am looking for platform independent approach. If that's not possible, I would like to know for Linux platform.   I don't need to preserve the data once read. I don't want to block program1.

答:
I have two programs: one (program1) writes to a file continuously, and I want the other program (program2) to read the file continuously.

What happens then is platform-specific. BTW, the mere ability to run several programs at once (in several processes) is provided by the operating system (and is not defined in, since outside of, the C11 standard). Read Operating Systems : Three Easy Pieces (freely downloadable chapters).

IIRC, on Windows (that I don't know and never used) that is not allowed to happen (one of the programs would be blocked or would have its file open fail).

However, if on Linux with a native local file system (such as Ext4), you could consider using inotify(7) facilities (which won't work with remote file systems à la NFS, and probably won't work on FAT filesystems like e.g. some USB key; but you need to check).

Basically, I want the output of program1 to be used as the input of program2. Is there any way to read and write in RAM instead of file as disk read costs more time.

(I am supposing you wrote both program1 and program2, or at least have their source code and can modify it)

BTW, application programs don't read directly from RAM; they work in virtual memory and each process has its own virtual address space. See this answer.

You surely want to have some inter-process communications, which are provided by your operating system.

On Linux there are many ways of doing that (you should read Advanced Linux Programming whose chapters are freely downloadable). I suggest considering some fifo(7), or some pipe(7) (if both running programs can be started from a common process), or some unix(7) sockets.
You surely need to multiplex for I/O (in both processes) e.g. by having some event loop around a poll(2).

Windows also has inter-process communication facilities. But I don't know them.

(I strongly recommend to spend a few days reading, notably Advanced Linux Programming or some other similar book, before writing a single line of code. You lack an overall picture on OSes and on Linux)

I would recommend using a pipe(7), or else some named fifo(7), or else some unix(7) socket. You could then write code portable on all POSIX systems. I don't recommend to use a file and inotify(7)  (which is complex and Linux specific). See also popen(3).

You might find some framework libraries (e.g. Glib from GTK, QtCore, POCO, libevent, 0mq) to help you write portable code able to run on many platforms.

Body:
I have two programs: one (program1) writes to a file continuously, and I want the other program (program2) to read the file continuously. What is happening is that my second program is only reading up to the data point which was written when the second code was executed and stops instead of continuously reading.

Is there any way to achieve the thing?

Basically, I want the output of program1 to be used as the input of program2. Is there any way to read and write in RAM instead of file as disk read costs more time.

Code 2:

#include <stdio.h>

int main(){

    FILE *fptr;

    fptr = fopen("gbbct1.seq","r");

    char c;
    c = fgetc(fptr);

    while (c != EOF){

        printf("%c", c);
        c = fgetc(fptr);

    }

}

I am looking for platform independent approach. If that's not possible, I would like to know for Linux platform.   I don't need to preserve the data once read. I don't want to block program1.


问:
C# Convert exact durations (mm:ss,xx) in ss,xx
My question is how to fix a fail at converting of a time span(m:ss,10th of sec.) in (ss,tenth of seconds);

The Problem is that the Output if this is completely wrong.

```<code>timeInString = "1:09.01";
tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0] * 60) + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));
</code>```

The Output must be 69,01, but is 2949.01.

答:
you missed hour in your time.

if do not care hour then you must passed zero to it. flow bottom C# code:

```<code>        var timeInString = "0:1:09.01";
        var timeInTimeSpan = TimeSpan.Parse(timeInString);
</code>```

Body:
My question is how to fix a fail at converting of a time span(m:ss,10th of sec.) in (ss,tenth of seconds);

The Problem is that the Output if this is completely wrong.

timeInString = "1:09.01";
tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0] * 60) + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));

The Output must be 69,01, but is 2949.01.

Body:
you missed hour in your time.

if do not care hour then you must passed zero to it. flow bottom C# code:

        var timeInString = "0:1:09.01";
        var timeInTimeSpan = TimeSpan.Parse(timeInString);


问:
Electron app - logging to file in production
I want to get logs if something wrong happens to my electron app when in production mode i.e after giving .exe file to a user wrt windows platform.

How to go about it, how can i basically write my errors to a file which will be in cyclic in nature.

答:
Take a look at electron log

```<code>// Setup file logging
const log = require('electron-log');
log.transports.file.level = 'info';
log.transports.file.file = __dirname + 'log.log';

// Log a message
log.info('log message');
</code>```

EDIT:

As mentioned in the comments the "log.transports.file.file" is deprecated.

Instead I would suggest to use the following method.

```<code>log.transports.file.resolvePath = () => __dirname + "/log.log";
</code>```

Body:
Take a look at electron log

// Setup file logging
const log = require('electron-log');
log.transports.file.level = 'info';
log.transports.file.file = __dirname + 'log.log';

// Log a message
log.info('log message');

EDIT:

As mentioned in the comments the "log.transports.file.file" is deprecated.

Instead I would suggest to use the following method.

log.transports.file.resolvePath = () => __dirname + "/log.log";


问:
How to run GTK# (C#) on a Mac OSX
I have a GTK# project that has been developed using C#, on Xamarin Studio, on Windows.

I can generate an .exe file for my application but I can't run this on a Mac. Is there a way for me to convert this .exe file to a .dmg / .app OR to run this .exe on a Mac without using Windows (Bootcamp)?

Note: WineBottler has not worked for my project.

答:
If you have Mono installed on your Mac then the .exe compiled on Windows should run unless you've got a dependency on something that is specific to windows. Some Windows libraries have not been ported to Mono for Mac or Linux, and if you are using ILMerge (windows) or ILRepack (*nix) then you will also potentially run into issues.

You don't need to use MacPack to build an app file, you can do it manually fairly simply as long as Mono is installed on your target Mac machine. There is a structure to an .app package folder which you can build manually.

Let me know if you need any more help, Cheers, M.

Title: How to run GTK# (C#) on a Mac OSX


问:
Populate a React form with data if it exists
I'm trying to pre-populate a form with data from my mongoDB. I think I'm supposed to use componentDidUpdate() to setState the state of the form field, however, the page goes into an infinite loop. Very new to react so this might be an obvious question, I just haven't been able to find a solution.

Path: ContactDetailsComponent.js

```<code>export default class ContactDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      'name.first': '',
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    var profileCandidate = this.props.profileCandidate;
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

    this.setState({
      'name.first': firstName,
    })

  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit} noValidate>

          <input
            name="name.first"
            type="text"
            value={this.state['name.first']}
            onChange={this.handleInputChange}
            className={this.state.errors['name.first'] ? "validate invalid" : "validate" }
          />

        </form>
      </div>

    )
  }
}

ContactDetails.propTypes = {
  profileCandidate: PropTypes.object,
};
</code>```

答:
You can slightly modify you following method

```<code>componentWillReceiveProps(nextProps) {
  var profileCandidate = nextProps.profileCandidate;
  var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

  this.setState({
    'name.first': firstName,
  })

}
</code>```

This will set the updated props to state.
Thanks

Body:
I'm trying to pre-populate a form with data from my mongoDB. I think I'm supposed to use componentDidUpdate() to setState the state of the form field, however, the page goes into an infinite loop. Very new to react so this might be an obvious question, I just haven't been able to find a solution.

Path: ContactDetailsComponent.js

export default class ContactDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      'name.first': '',
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    var profileCandidate = this.props.profileCandidate;
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

    this.setState({
      'name.first': firstName,
    })

  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (

        <form onSubmit={this.handleSubmit} noValidate>

          <input
            name="name.first"
            type="text"
            value={this.state['name.first']}
            onChange={this.handleInputChange}
            className={this.state.errors['name.first'] ? "validate invalid" : "validate" }
          />

        </form>

    )
  }
}

ContactDetails.propTypes = {
  profileCandidate: PropTypes.object,
};

Body:
You can slightly modify you following method

componentWillReceiveProps(nextProps) {
  var profileCandidate = nextProps.profileCandidate;
  var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

  this.setState({
    'name.first': firstName,
  })

}

This will set the updated props to state.
Thanks


问:
Silverlight: How to work with layouts relative to screen size?
I'm working with Silverlight 4. I have a control that is wide enough that it goes off the screen. If I expand the window enough, I can see it, but I'd rather the control shrink so that it's visible in a smaller window. How can I specify this?</p>

答:
Also, it might be helpful to look at the Silverlight Toolkit Samples.  The LayoutTransformer example does some resizing like you describe.

http://www.silverlight.net/content/samples/sl4/toolkitcontrolsamples/run/default.html#/Navigation/Page2.xaml


问:
Placing UIView To Cover TabBar & NavBar
I am trying to make a popup (UIView) with a transparent background (another UIView). Everything is working fine for the 'popup UIView' but I couldn't figure out how to bring 'transparent background UIView' (above NavigationBar and TabBar).

First I created the UIView in the Storyboard and connected the outlet:

```<code>popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
self.view.addSubview(popupView)
popupView.clipsToBounds = true
popupView.alpha = 0
</code>```

Then, while displaying popupView I am creating the transparent background UIView:

```<code> func clicked() {
    self.popupView.alpha = 1

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let opaqueView = UIView()
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    opaqueView.backgroundColor = UIColor.blackColor()
    opaqueView.alpha = 0.5

    self.view.addSubview(opaqueView)
 }
</code>```

However, the background view doesn't get over NavigationBar or TabBar. I tried this but nothing changes:

```<code>myTabBar.view.bringSubviewToFront(opaqueView)
</code>```

What I want to achieve is that, while having popup UIView at the very front, having opaque UIView over everything including NavBar and TabBar, but behind popup UIView

Update:

Regarding @Alex's answer, with this chunk, I achieved displaying opaqueView over TabBar & NavBar; but now it's also going above the popupView.

```<code>func display() {
   popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
    self.view.addSubview(popupView)
    popupView.clipsToBounds = true

    let opaqueView = UIView()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView)
}
</code>```

How can I place opaqueView below popupView while opaqueView is above everything else?

答:
```<code>    func addButtonTapped(){
              if self.transparentBackground == nil{
                  self.transparentBackground = UIView(frame: UIScreen.main.bounds)
                  self.transparentBackground.backgroundColor = UIColor(white: 0.0, alpha: 0.54)
                  UIApplication.shared.keyWindow!.addSubview(self.transparentBackground)
                  self.opaqueView = self.setupOpaqueView()
                  self.transparentBackground.addSubview(opaqueView)
                  UIApplication.shared.keyWindow!.bringSubview(toFront: self.transparentBackground)
                  self.view.bringSubview(toFront: transparentBackground)
              }
          }

          func setupOpaqueView() -> UIView{
                let mainView = UIView(frame: CGRect(x: 16, y: 100, width: Int(UIScreen.main.bounds.width-32), height: 200))
                mainView.backgroundColor = UIColor.white
                let titleLabel = UILabel(frame: CGRect(x: 16, y: 20, width: Int(mainView.frame.width-32), height: 100))
                titleLabel.text = "This is the opaque"
                titleLabel.textAlignment = .center
                titleLabel.font = font
                titleLabel.textColor = UIColor(white: 0.0, alpha: 0.54)
                mainView.addSubview(titleLabel)

                let  OKbutton = UIButton(frame: CGRect(x: 16, y: Int(mainView.frame.height-60), width: Int(mainView.frame.width-32), height: 45))
                OKbutton.backgroundColor = UIColor(red: 40.0 / 255.0, green: 187.0 / 255.0, blue: 187.0 / 255.0, alpha: 1)
                OKbutton.layer.cornerRadius = 10
                mainView.addSubview(OKbutton)
                OKbutton.setTitle("OK", for: .normal)
                OKbutton.setTitleColor(UIColor.white, for: .normal)
                OKbutton.titleLabel?.font = font
                OKbutton.addTarget(self, action:  #selector(FirstViewController.handleOKButtonTapped(_:)), for: .touchUpInside)

                return mainView

          }

          func handleOKButtonTapped(_ sender: UIButton){
              UIView.animate(withDuration: 0.3, animations: {
                  self.transparentBackground.alpha = 0
              }) { done in
                  self.transparentBackground.removeFromSuperview()
                  self.transparentBackground = nil

              }
          }
</code>```

Title: Placing UIView To Cover TabBar & NavBar

Body:
I am trying to make a popup (UIView) with a transparent background (another UIView). Everything is working fine for the 'popup UIView' but I couldn't figure out how to bring 'transparent background UIView' (above NavigationBar and TabBar).

First I created the UIView in the Storyboard and connected the outlet:

popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
self.view.addSubview(popupView)
popupView.clipsToBounds = true
popupView.alpha = 0

Then, while displaying popupView I am creating the transparent background UIView:

 func clicked() {
    self.popupView.alpha = 1

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let opaqueView = UIView()
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    opaqueView.backgroundColor = UIColor.blackColor()
    opaqueView.alpha = 0.5

    self.view.addSubview(opaqueView)
 }

However, the background view doesn't get over NavigationBar or TabBar. I tried this but nothing changes:

myTabBar.view.bringSubviewToFront(opaqueView)

What I want to achieve is that, while having popup UIView at the very front, having opaque UIView over everything including NavBar and TabBar, but behind popup UIView

Update:

Regarding @Alex's answer, with this chunk, I achieved displaying opaqueView over TabBar & NavBar; but now it's also going above the popupView.

func display() {
   popupView.center = CGPointMake(CGRectGetMidX(self.view.bounds), tableView.center.y);
    self.view.addSubview(popupView)
    popupView.clipsToBounds = true

    let opaqueView = UIView()
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    opaqueView.frame.size = CGSize(width: screenSize.width, height: screenSize.height)
    UIApplication.sharedApplication().keyWindow!.insertSubview(opaqueView, belowSubview: popupView)
}

How can I place opaqueView below popupView while opaqueView is above everything else?


问:
Dynamically Change WCF Service URL in ASP.NET MVC
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

```<code><client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>
</code>```

答:
Not sure if I understand you correctly but you could use below snippet, if it suits.</p>

```<code>//assuming you get string URL. Change type as per need.
string reqdURL = GetServiceURL(typeof(userObject));

private string GetServiceURL(Type userType)
{
    if (userType == typeof(UserType1))
    {
        // currently hardcoded but you can replace your own fetch logic
        return "localhost:6227/Service1.svc";
    }
    if (userType == typeof(UserType2))
    {
        return "localhost:6227/Service2.svc";
    }
    //and so on
}
</code>```

Body:
I have one solution in which I have 2 projects with:

ASP.NET MVC Application to consume wcf services.

5 WCF services.

I have added one web service reference in the project 1. Now, I need to use different services based on the user e.g.

User Type 1: Only allow to consume Service 1.

User Type 2: Only allow to consume Service 2.
etc.

I have Service URL's like localhost:6227/Service1.svc, localhost:6227/Service2.svc etc.

I have stored all service URL's in the db and I need to change URL for each user type to consume his allowed service only without adding more end points and only change URL from the backend based on user type. I need relevant link or code to solve this problem.

Edit

In Web Config
I have added just this endpoint in the mvc application and I don't want to use web config to change address in here but I want to change address in the code for each user type while application is running.

<client>
      <endpoint address="http://localhost:6227/Service1.svc"
        binding="customBinding" bindingConfiguration="CustomBinding_IService1"
        contract="Service1.IService1" name="CustomBinding_IService1" />
    </client>

Body:
Not sure if I understand you correctly but you could use below snippet, if it suits.

//assuming you get string URL. Change type as per need.
string reqdURL = GetServiceURL(typeof(userObject));

private string GetServiceURL(Type userType)
{
    if (userType == typeof(UserType1))
    {
        // currently hardcoded but you can replace your own fetch logic
        return "localhost:6227/Service1.svc";
    }
    if (userType == typeof(UserType2))
    {
        return "localhost:6227/Service2.svc";
    }
    //and so on
}


问:
Delete rows containing @ symbol in mySQL
Hi I would like to know if there is any way of deleting any row containing the @ symbol in a text string.

I already tried :

```<code>DELETE FROM FilteredJobs WHERE Description LIKE '%[@]%'
</code>```

but this returns 0 rows (I know there are 4)

I need to get this done within mySQL since there will be other mySQL functions to follow this task.

答:
You can use locate, it returns the position of the sub string in the main value...

```<code>DELETE FROM FilteredJobs WHERE locate('@', Description) > 0;
</code>```

Body:
Hi I would like to know if there is any way of deleting any row containing the @ symbol in a text string.

I already tried :

DELETE FROM FilteredJobs WHERE Description LIKE '%[@]%'

but this returns 0 rows (I know there are 4)

I need to get this done within mySQL since there will be other mySQL functions to follow this task.

Body:
You can use locate, it returns the position of the sub string in the main value...

DELETE FROM FilteredJobs WHERE locate('@', Description) > 0;