问:
React Native app purely in Swift
I created my first react native app using the following command.

```<code>react-native init PropertyFinder
</code>```

This created a project for ios in Objective-C. The problem is I don't know Objective-C but I work on Swift.

This gist shows how to link react-components to a swift project.
But is there a way to directly create the project in Swift language?

答:
This actually works for me:</p>

```<code>import Foundation

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var bridge: RCTBridge!

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let jsCodeLocation: URL

    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.ios", fallbackResource:nil)
    let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "REPLACE_WITH_YOUR_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions)
    let rootViewController = UIViewController()
    rootViewController.view = rootView

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()

    return true
  }
}
</code>```

Title: React Native app purely in Swift

Body:
I created my first react native app using the following command.

react-native init PropertyFinder

This created a project for ios in Objective-C. The problem is I don't know Objective-C but I work on Swift.

This gist shows how to link react-components to a swift project.
But is there a way to directly create the project in Swift language?

Body:
This actually works for me:

import Foundation

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var bridge: RCTBridge!

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let jsCodeLocation: URL

    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.ios", fallbackResource:nil)
    let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "REPLACE_WITH_YOUR_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions)
    let rootViewController = UIViewController()
    rootViewController.view = rootView

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()

    return true
  }
}


来源: stackexchange

问:
Flutter - Custom Font not displaying
This is an excerpt of my pubspec.yaml file:

```<code>flutter:
  uses-material-design: true
  fonts:
   - family: Coiny
     fonts:
       - asset: fonts/Coiny-Regular.ttf
</code>```

I am trying to use the font called "Coiny" from the Google Fonts page. I created a fonts folder inside my root directory and put it in there.

In my code, I do this:

```<code>new Text("Testtext", style: new TextStyle(fontFamily: "Coiny")),
</code>```

But it has no effect. I have encountered a similar problem in the past with the Barrio font. But it seemed to work after some time, which is not the case with this one.

答: You might want to try removing the app from the device and reinstalling it. Depending on how you're launching, it might not be writing over the old install file.</p>

ContentLicense: CC BY-SA 3.0

Title: Flutter - Custom Font not displaying

Body:
This is an excerpt of my pubspec.yaml file:

flutter:
  uses-material-design: true
  fonts:
   - family: Coiny
     fonts:
       - asset: fonts/Coiny-Regular.ttf

I am trying to use the font called "Coiny" from the Google Fonts page. I created a fonts folder inside my root directory and put it in there.

In my code, I do this:

new Text("Testtext", style: new TextStyle(fontFamily: "Coiny")),

But it has no effect. I have encountered a similar problem in the past with the Barrio font. But it seemed to work after some time, which is not the case with this one.


问:
Saving and reusing spark mllib LinearRegression model on new data
I have a LinearRegression model trained on historical data, now I am trying to re-use the same model on the new data to make predictions.

I know that we can save and load model using model.save and LinearRegression.load methods respectively, however, I am unable to find a way to pass in new data to loaded model for predictions.

Code for creating and training model is pasted below:

```<code>val assembler = new VectorAssembler().setInputCols(Array("total", "connected", "c_403", "c_480", "c_503", "hour", "day_of_week")).setOutputCol("features")

val output = assembler.transform(df).select($"label", $"features")
val Array(training, test) = output.select("label", "features").randomSplit(Array(0.7, 0.3), seed = 12)

val lr = new LinearRegression()

val paramGrid = new ParamGridBuilder().addGrid(lr.regParam, Array(0.1, 0.01)).addGrid(lr.fitIntercept).addGrid(lr.elasticNetParam, Array(0.0, 0.25, 0.5, 0.75, 1.0)).build()

val trainvalSplit = new TrainValidationSplit().setEstimator(lr).setEvaluator(new RegressionEvaluator()).setEstimatorParamMaps(paramGrid).setTrainRatio(0.75)
val model = trainvalSplit.fit(training)

val holdout = model.transform(test).select("prediction","label")
</code>```

答:
Ok that's straight forward actually but you'll need to use the TrainValidationSplitModel and not the LinearRegressionModel to load your model considering that you have saved your model with model.save("/home/waqas/models/lreg") :

```<code>scala> import org.apache.spark.ml.tuning.TrainValidationSplitModel

scala> val model2 = TrainValidationSplitModel.load("/home/waqas/models/lreg")
// model2: org.apache.spark.ml.tuning.TrainValidationSplitModel = tvs_99887a2f788d

scala> model2.transform(newData).show(3)
// +-----+--------------------+--------------------+
// |label|            features|          prediction|
// +-----+--------------------+--------------------+
// |  0.0|(692,[121,122,123...| 0.11220528529664375|
// |  0.0|(692,[122,123,148...|  0.1727599038728312|
// |  0.0|(692,[123,124,125...|-0.09619225628995537|
// +-----+--------------------+--------------------+
// only showing top 3 rows
</code>```

Body:
I have a LinearRegression model trained on historical data, now I am trying to re-use the same model on the new data to make predictions.

I know that we can save and load model using model.save and LinearRegression.load methods respectively, however, I am unable to find a way to pass in new data to loaded model for predictions.

Code for creating and training model is pasted below:

val assembler = new VectorAssembler().setInputCols(Array("total", "connected", "c_403", "c_480", "c_503", "hour", "day_of_week")).setOutputCol("features")

val output = assembler.transform(df).select($"label", $"features")
val Array(training, test) = output.select("label", "features").randomSplit(Array(0.7, 0.3), seed = 12)

val lr = new LinearRegression()

val paramGrid = new ParamGridBuilder().addGrid(lr.regParam, Array(0.1, 0.01)).addGrid(lr.fitIntercept).addGrid(lr.elasticNetParam, Array(0.0, 0.25, 0.5, 0.75, 1.0)).build()

val trainvalSplit = new TrainValidationSplit().setEstimator(lr).setEvaluator(new RegressionEvaluator()).setEstimatorParamMaps(paramGrid).setTrainRatio(0.75)
val model = trainvalSplit.fit(training)

val holdout = model.transform(test).select("prediction","label")

Body:
Ok that's straight forward actually but you'll need to use the TrainValidationSplitModel and not the LinearRegressionModel to load your model considering that you have saved your model with model.save("/home/waqas/models/lreg") :

scala> import org.apache.spark.ml.tuning.TrainValidationSplitModel

scala> val model2 = TrainValidationSplitModel.load("/home/waqas/models/lreg")
// model2: org.apache.spark.ml.tuning.TrainValidationSplitModel = tvs_99887a2f788d

scala> model2.transform(newData).show(3)
// +-----+--------------------+--------------------+
// |label|            features|          prediction|
// +-----+--------------------+--------------------+
// |  0.0|(692,[121,122,123...| 0.11220528529664375|
// |  0.0|(692,[122,123,148...|  0.1727599038728312|
// |  0.0|(692,[123,124,125...|-0.09619225628995537|
// +-----+--------------------+--------------------+
// only showing top 3 rows


问:
giving ftp user a random password
So I'm trying to create a new ftp user and directory and give him only permissions for that directory. But the problem is when setting a password for created user. It creates user but i get this when i try to set a password for him

Creating home directory /home/kwgazl69' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: user 'test123' does not exist

What am i doing wrong ? Here is the code

```<code>$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("passwd test123");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();
</code>```

Adding user ln2i78yt' ... Adding new groupln2i78yt' (1010) ... Adding new user ln2i78yt' (1010) with groupln2i78yt' ... Creating home directory /home/ln2i78yt' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: unrecognized option '--stdin' Usage: passwd [options] [LOGIN] Options: -a, --all report password status on all accounts -d, --delete delete the password for the named account -e, --expire force expire the password for the named account -h, --help display this help message and exit -k, --keep-tokens change password only if expired -i, --inactive INACTIVE set password inactive after expiration to INACTIVE -l, --lock lock the password of the named account -n, --mindays MIN_DAYS set minimum number of days before password change to MIN_DAYS -q, --quiet quiet mode -r, --repository REPOSITORY change password in REPOSITORY repository -R, --root CHROOT_DIR directory to chroot into -S, --status report password status on the named account -u, --unlock unlock the password of the named account -w, --warndays WARN_DAYS set expiration warning days to WARN_DAYS -x, --maxdays MAX_DAYS set maximum number of days before password change to MAX_DAYS

答:
passwd expects 1st parameter to be username, and after that it asks for password twice. You can try to use another command called chpasswd. It expects username and password separated by colon.

```<code>$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("echo \"$randomNum:test123\" | chpasswd");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();
</code>```

Title: giving ftp user a random password

Body:
So I'm trying to create a new ftp user and directory and give him only permissions for that directory. But the problem is when setting a password for created user. It creates user but i get this when i try to set a password for him

Creating home directory /home/kwgazl69' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: user 'test123' does not exist

What am i doing wrong ? Here is the code

$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("passwd test123");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();

Adding user ln2i78yt' ... Adding new groupln2i78yt' (1010) ... Adding new user ln2i78yt' (1010) with groupln2i78yt' ... Creating home directory /home/ln2i78yt' ... Copying files from/etc/skel' ... Enter new UNIX password: passwd: unrecognized option '--stdin' Usage: passwd [options] [LOGIN] Options: -a, --all report password status on all accounts -d, --delete delete the password for the named account -e, --expire force expire the password for the named account -h, --help display this help message and exit -k, --keep-tokens change password only if expired -i, --inactive INACTIVE set password inactive after expiration to INACTIVE -l, --lock lock the password of the named account -n, --mindays MIN_DAYS set minimum number of days before password change to MIN_DAYS -q, --quiet quiet mode -r, --repository REPOSITORY change password in REPOSITORY repository -R, --root CHROOT_DIR directory to chroot into -S, --status report password status on the named account -u, --unlock unlock the password of the named account -w, --warndays WARN_DAYS set expiration warning days to WARN_DAYS -x, --maxdays MAX_DAYS set maximum number of days before password change to MAX_DAYS

Body:
passwd expects 1st parameter to be username, and after that it asks for password twice. You can try to use another command called chpasswd. It expects username and password separated by colon.

$src = $request->path;
$dest = "/home/$randomNum/serverFiles";

echo $ssh->exec("adduser --force-badname $randomNum");
echo $ssh->exec("echo \"$randomNum:test123\" | chpasswd");

echo $ssh->exec("cp -r $src $dest");
echo $ssh->exec("usermod -d $dest $randomNum");

echo $ssh->exec("cd $dest && ./samp03svr");

$ssh->disconnect();


问:
How to create a new object and set layout_centerVertical to true programatically?
I'm creating an ImageView programatically and I want to set layout_centerVertical="true" and android:layout_centerHorizontal="true".

I tried this code:

```<code>    ImageView myImage = new ImageView(this);
    Resources res = getApplicationContext().getResources();
    myImage.setImageResource(res.getIdentifier((card.getColor() + "_" + card.getFigure()).toLowerCase(), "drawable", this.getPackageName()));
    myImage.setTag(IMAGEVIEW_TAG);

    myImage.setOnTouchListener(new MyTouchListener());

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.toplinear);
    layout.addView(myImage);

    View positiveButton = myImage.getRootView();
    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    positiveButton.setLayoutParams(layoutParams);
</code>```

However logcat throws an error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void android.widget.RelativeLayout$LayoutParams.addRule(int,
  int)' on a null object reference
              at pl.ds13ds14.ucp.CardsActivity.AddCard(CardsActivity.java:55)

The line 55 contains:

```<code>layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
</code>```

答:
Try this:

```<code>    RelativeLayout layout = (RelativeLayout) findViewById(R.id.toplinear);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL);
    params.addRule(RelativeLayout.CENTER_VERTICAL);
    myImage.setLayoutParams(params);
    layout.addView(myImage, params);
</code>```

Body:
I'm creating an ImageView programatically and I want to set layout_centerVertical="true" and android:layout_centerHorizontal="true".

I tried this code:

    ImageView myImage = new ImageView(this);
    Resources res = getApplicationContext().getResources();
    myImage.setImageResource(res.getIdentifier((card.getColor() + "_" + card.getFigure()).toLowerCase(), "drawable", this.getPackageName()));
    myImage.setTag(IMAGEVIEW_TAG);

    myImage.setOnTouchListener(new MyTouchListener());

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.toplinear);
    layout.addView(myImage);

    View positiveButton = myImage.getRootView();
    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    positiveButton.setLayoutParams(layoutParams);

However logcat throws an error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void android.widget.RelativeLayout$LayoutParams.addRule(int,
  int)' on a null object reference
              at pl.ds13ds14.ucp.CardsActivity.AddCard(CardsActivity.java:55)

The line 55 contains:

layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

Body:
Try this:

    RelativeLayout layout = (RelativeLayout) findViewById(R.id.toplinear);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.CENTER_HORIZONTAL);
    params.addRule(RelativeLayout.CENTER_VERTICAL);
    myImage.setLayoutParams(params);
    layout.addView(myImage, params);


问:
Query Fine Tuning
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

```<code> Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );
</code>```

Any assistance is greatly appreciated.

Thanks.

答:
You can use exists:

```<code>select *
from emp
where exists(
    select 1 from dept_emp where dept_emp.emp_no = emp.emp_no and dept_no = 'd002'
)
</code>```

also maybe inner join work:

```<code>select emp.*
from emp
join dept_emp
on dept_emp.emp_no = emp.emp_no
and dept_no = 'd002'
</code>```

Title: Query Fine Tuning

Body:
I am fairly new to sql and would like to ask for your assistance regarding this query. Is there another way to rewrite this?

 Select *
 From emp
 Where emp_no IN (
     Select emp_no
     From dept_emp
     Where dept_no = 'd002'
     );

Any assistance is greatly appreciated.

Thanks.

Body:
You can use exists:

select *
from emp
where exists(
    select 1 from dept_emp where dept_emp.emp_no = emp.emp_no and dept_no = 'd002'
)

also maybe inner join work:

select emp.*
from emp
join dept_emp
on dept_emp.emp_no = emp.emp_no
and dept_no = 'd002'


问:
Converting SQL server table data from a column structure to a different column structure
i have just taken over development at my place a work and have basically been thrown in the deep end with the SQL server, i'm not very knowledgeable with query's and the format so please go easy on me.

i'm using Microsoft SQL server 2012 and basically what i'm trying to achieve is to take data from one database table reformat it into a different structure then import this into a new database. I've been given the code below from the developers who created the software. i have a basic understanding of what it is doing but i'm getting a fair few errors i cant seem to trace no matter what i fix and need a little bit of help making sure is formatted correctly as the devs take a long time to answer any email questions

```<code>--Specify the database, table and columns we want to insert into
INSERT INTO new_database.dbo.QuizQuestions (uuid, [type], question, answer, created_date, modified_date,
master_category, master_decade, master_difficulty, is_editable, is_deletable, media)

--Get the data from the old database (old_database) and map the media filename to the media2 table in the new database

select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable,
   media.id as mediaid
from
(
   select NEWID() as uuid,
   CASE
          WHEN qqt.TypeName = 'Sound' THEN 'Audio'
          ELSE qqt.TypeName
   END AS newtype,
   qq.QuestionText, qq.AnswerText,
   qq.CreatedDate,
   CASE
          WHEN qq.ModifiedDate is NOT NULL THEN qq.ModifiedDate
          ELSE GETDATE()
   END as ModifiedDate,
   CASE
          WHEN cat.id is NOT NULL THEN cat.id
          ELSE 1
   END as master_category,
   qqdc.QuizQuestionDecadeID as master_decade,
   qd.id as master_difficulty,
   qq.IsEditable, qq.IsDeletable,
   qq.FilePath,
   SUBSTRING(
          qq.FilePath,
          len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2,
          (len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 1) as fname
   --len(qq.FilePath) - charindex('.', reverse(qq.FilePath)) as positionoflastdot,
   --len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) as positionoflastslash
   from old_database.dbo.QuizQuestion qq
   left join old_database.dbo.QuizQuestionType qqt on qq.QuizQuestionTypeID = qqt.QuizQuestionTypeID
   left join old_database.dbo.QuizQuestionDifficulty qqd on qq.QuizQuestionDifficultyID = qqd.QuizQuestionDifficultyID
   left join old_database.dbo.QuizQuestionCategory qqc on qq.QuizQuestionCategoryID = qqc.QuizQuestionCategoryID
   left join old_database.dbo.QuizQuestionDecade qqdc on qq.QuizQuestionDecadeID = qqdc.QuizQuestionDecadeID
   left join old_database.dbo.QuizQuestionCategory qqmc on qq.MasterCategoryID = qqmc.MasterQuestionCategoryID
   left join old_database_Demo.dbo.QuizCategories cat on qqc.CategoryName = cat.name
   left join old_database_Demo.dbo.QuizDifficulties qd on qd.id = qq.MasterDifficultyID
   where qq.MasterCategoryID is not null
) as questions
left join new_database.dbo.Media2 media on media.name = REPLACE(fname,'QUIZ','')
</code>```

at first i was getting

```<code>Msg 537, Level 16, State 2, Line 2
Invalid length parameter passed to the LEFT or SUBSTRING function.
The statement has been terminated.
</code>```

so I've added moved the media from the end of the line and put it next to answers
and adjusted the select list to match as this is how the table is structured

```<code>--Specify the database, table and columns we want to insert into
INSERT INTO new_database.dbo.QuizQuestions (uuid, [type], question, answer,  media, created_date, modified_date,
master_category, master_decade, master_difficulty, is_editable, is_deletable)

--Get the data from the old database (old_database) and map the media filename to the media2 table in the new database

select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   media.id as mediaid,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable,

 from
(
   select NEWID() as uuid,
   CASE
          WHEN qqt.TypeName = 'Sound' THEN 'Audio'
          ELSE qqt.TypeName
   END AS newtype,
   qq.QuestionText, qq.AnswerText,
   qq.CreatedDate,
   CASE
          WHEN qq.ModifiedDate is NOT NULL THEN qq.ModifiedDate
          ELSE GETDATE()
   END as ModifiedDate,
   CASE
          WHEN cat.id is NOT NULL THEN cat.id
          ELSE 1
   END as master_category,
   qqdc.QuizQuestionDecadeID as master_decade,
   qd.id as master_difficulty,
   qq.IsEditable, qq.IsDeletable,
   qq.FilePath,
   SUBSTRING(
          qq.FilePath,
          len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2,
          (len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 1) as fname
   --len(qq.FilePath) - charindex('.', reverse(qq.FilePath)) as positionoflastdot,
   --len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) as positionoflastslash
   from old_database.dbo.QuizQuestion qq
   left join old_database.dbo.QuizQuestionType qqt on qq.QuizQuestionTypeID = qqt.QuizQuestionTypeID
   left join old_database.dbo.QuizQuestionDifficulty qqd on qq.QuizQuestionDifficultyID = qqd.QuizQuestionDifficultyID
   left join old_database.dbo.QuizQuestionCategory qqc on qq.QuizQuestionCategoryID = qqc.QuizQuestionCategoryID
   left join old_database.dbo.QuizQuestionDecade qqdc on qq.QuizQuestionDecadeID = qqdc.QuizQuestionDecadeID
   left join old_database.dbo.QuizQuestionCategory qqmc on qq.MasterCategoryID = qqmc.MasterQuestionCategoryID
   left join old_database_Demo.dbo.QuizCategories cat on qqc.CategoryName = cat.name
   left join old_database_Demo.dbo.QuizDifficulties qd on qd.id = qq.MasterDifficultyID
   where qq.MasterCategoryID is not null
) as questions
left join new_database.dbo.Media2 media on media.name = REPLACE(fname,'QUIZ','')
</code>```

now when i execute im getting

```<code>Msg 156, Level 15, State 1, Line 19
Incorrect syntax near the keyword 'from'.
Msg 156, Level 15, State 1, Line 55
Incorrect syntax near the keyword 'as'.
</code>```

this is where i'm currently stuck and have no idea how to move forward to get this to execute correctly and I've googled and researched allot i even had our customer database guy who deals with access to take a look and hes just a puzzled as i am.

any help to show me where i'm going wrong would be great

best regards
dan

答:
I've managed to get the query to work by placing the from at the end of the select list instead of underneath,

```<code>select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   media.id as mediaid,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable from
(
</code>```

and also changing from -1 to -0 on the subquery to remove any negative values

```<code>select
(len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2),`

`(len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 0) as fname
</code>```

but it didn't map the media files correctly and returned null to the media column in the new table but i can work around this.

Thank you to everyone who posted for your help.

Body:
i have just taken over development at my place a work and have basically been thrown in the deep end with the SQL server, i'm not very knowledgeable with query's and the format so please go easy on me.

i'm using Microsoft SQL server 2012 and basically what i'm trying to achieve is to take data from one database table reformat it into a different structure then import this into a new database. I've been given the code below from the developers who created the software. i have a basic understanding of what it is doing but i'm getting a fair few errors i cant seem to trace no matter what i fix and need a little bit of help making sure is formatted correctly as the devs take a long time to answer any email questions

--Specify the database, table and columns we want to insert into
INSERT INTO new_database.dbo.QuizQuestions (uuid, [type], question, answer, created_date, modified_date,
master_category, master_decade, master_difficulty, is_editable, is_deletable, media)

--Get the data from the old database (old_database) and map the media filename to the media2 table in the new database

select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable,
   media.id as mediaid
from
(
   select NEWID() as uuid,
   CASE
          WHEN qqt.TypeName = 'Sound' THEN 'Audio'
          ELSE qqt.TypeName
   END AS newtype,
   qq.QuestionText, qq.AnswerText,
   qq.CreatedDate,
   CASE
          WHEN qq.ModifiedDate is NOT NULL THEN qq.ModifiedDate
          ELSE GETDATE()
   END as ModifiedDate,
   CASE
          WHEN cat.id is NOT NULL THEN cat.id
          ELSE 1
   END as master_category,
   qqdc.QuizQuestionDecadeID as master_decade,
   qd.id as master_difficulty,
   qq.IsEditable, qq.IsDeletable,
   qq.FilePath,
   SUBSTRING(
          qq.FilePath,
          len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2,
          (len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 1) as fname
   --len(qq.FilePath) - charindex('.', reverse(qq.FilePath)) as positionoflastdot,
   --len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) as positionoflastslash
   from old_database.dbo.QuizQuestion qq
   left join old_database.dbo.QuizQuestionType qqt on qq.QuizQuestionTypeID = qqt.QuizQuestionTypeID
   left join old_database.dbo.QuizQuestionDifficulty qqd on qq.QuizQuestionDifficultyID = qqd.QuizQuestionDifficultyID
   left join old_database.dbo.QuizQuestionCategory qqc on qq.QuizQuestionCategoryID = qqc.QuizQuestionCategoryID
   left join old_database.dbo.QuizQuestionDecade qqdc on qq.QuizQuestionDecadeID = qqdc.QuizQuestionDecadeID
   left join old_database.dbo.QuizQuestionCategory qqmc on qq.MasterCategoryID = qqmc.MasterQuestionCategoryID
   left join old_database_Demo.dbo.QuizCategories cat on qqc.CategoryName = cat.name
   left join old_database_Demo.dbo.QuizDifficulties qd on qd.id = qq.MasterDifficultyID
   where qq.MasterCategoryID is not null
) as questions
left join new_database.dbo.Media2 media on media.name = REPLACE(fname,'QUIZ','')

at first i was getting

Msg 537, Level 16, State 2, Line 2
Invalid length parameter passed to the LEFT or SUBSTRING function.
The statement has been terminated.

so I've added moved the media from the end of the line and put it next to answers
and adjusted the select list to match as this is how the table is structured

--Specify the database, table and columns we want to insert into
INSERT INTO new_database.dbo.QuizQuestions (uuid, [type], question, answer,  media, created_date, modified_date,
master_category, master_decade, master_difficulty, is_editable, is_deletable)

--Get the data from the old database (old_database) and map the media filename to the media2 table in the new database

select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   media.id as mediaid,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable,

 from
(
   select NEWID() as uuid,
   CASE
          WHEN qqt.TypeName = 'Sound' THEN 'Audio'
          ELSE qqt.TypeName
   END AS newtype,
   qq.QuestionText, qq.AnswerText,
   qq.CreatedDate,
   CASE
          WHEN qq.ModifiedDate is NOT NULL THEN qq.ModifiedDate
          ELSE GETDATE()
   END as ModifiedDate,
   CASE
          WHEN cat.id is NOT NULL THEN cat.id
          ELSE 1
   END as master_category,
   qqdc.QuizQuestionDecadeID as master_decade,
   qd.id as master_difficulty,
   qq.IsEditable, qq.IsDeletable,
   qq.FilePath,
   SUBSTRING(
          qq.FilePath,
          len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2,
          (len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 1) as fname
   --len(qq.FilePath) - charindex('.', reverse(qq.FilePath)) as positionoflastdot,
   --len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) as positionoflastslash
   from old_database.dbo.QuizQuestion qq
   left join old_database.dbo.QuizQuestionType qqt on qq.QuizQuestionTypeID = qqt.QuizQuestionTypeID
   left join old_database.dbo.QuizQuestionDifficulty qqd on qq.QuizQuestionDifficultyID = qqd.QuizQuestionDifficultyID
   left join old_database.dbo.QuizQuestionCategory qqc on qq.QuizQuestionCategoryID = qqc.QuizQuestionCategoryID
   left join old_database.dbo.QuizQuestionDecade qqdc on qq.QuizQuestionDecadeID = qqdc.QuizQuestionDecadeID
   left join old_database.dbo.QuizQuestionCategory qqmc on qq.MasterCategoryID = qqmc.MasterQuestionCategoryID
   left join old_database_Demo.dbo.QuizCategories cat on qqc.CategoryName = cat.name
   left join old_database_Demo.dbo.QuizDifficulties qd on qd.id = qq.MasterDifficultyID
   where qq.MasterCategoryID is not null
) as questions
left join new_database.dbo.Media2 media on media.name = REPLACE(fname,'QUIZ','')

now when i execute im getting

Msg 156, Level 15, State 1, Line 19
Incorrect syntax near the keyword 'from'.
Msg 156, Level 15, State 1, Line 55
Incorrect syntax near the keyword 'as'.

this is where i'm currently stuck and have no idea how to move forward to get this to execute correctly and I've googled and researched allot i even had our customer database guy who deals with access to take a look and hes just a puzzled as i am.

any help to show me where i'm going wrong would be great

best regards
dan

Body:
I've managed to get the query to work by placing the from at the end of the select list instead of underneath,

select
   questions.uuid,
   questions.newtype,
   questions.QuestionText,
   questions.AnswerText,
   media.id as mediaid,
   questions.CreatedDate,
   questions.ModifiedDate,
   questions.master_category,
   questions.master_decade,
   questions.master_difficulty,
   questions.IsEditable,
   questions.IsDeletable from
(

and also changing from -1 to -0 on the subquery to remove any negative values

select
(len(qq.FilePath) - charindex('/', reverse(qq.FilePath)) + 2),`

`(len(qq.FilePath) - charindex('.', reverse(qq.FilePath))) - (len(qq.FilePath) - charindex('/', reverse(qq.FilePath))) - 0) as fname

but it didn't map the media files correctly and returned null to the media column in the new table but i can work around this.

Thank you to everyone who posted for your help.


问:
stop observables in Observable.zip while empty response comes
I am working on angular  and Typescript. I have one code like

```<code>const activePairs = Observable
    .zip(ActiveCustomerChoices, ActiveLocations)
    .map(([ccs, locs]) => makePairs(ccs, locs));
</code>```

but  ActiveCustomerChoices may return empty data. If it does, I need to extract it and stop the execution. How can I stop observables?

答:
You can use takeWhile

```<code>const activePairs = ActiveCustomerChoices
    .takeWhile(ccs => ccs.length > 0)
    .zip(ActiveLocations)
    .map(([ccs, locs]) => makePairs(ccs, locs))
</code>```

Body:
I am working on angular  and Typescript. I have one code like

const activePairs = Observable
    .zip(ActiveCustomerChoices, ActiveLocations)
    .map(([ccs, locs]) => makePairs(ccs, locs));

but  ActiveCustomerChoices may return empty data. If it does, I need to extract it and stop the execution. How can I stop observables?

Body:
You can use takeWhile

const activePairs = ActiveCustomerChoices
    .takeWhile(ccs => ccs.length > 0)
    .zip(ActiveLocations)
    .map(([ccs, locs]) => makePairs(ccs, locs))


问:
Copy SQL data from one server to another using c# threading
I am new to Threading in c#, hence asking this question. Please correct me if i am wrong anywhere in my below question, it might be because of lacking of knowledge in C# threading.

I have an array (type of string) that contains all the Table Names (of SQL server), now I want to read data of these tables using sql query and write to another server. i can do it using synchronous programming, but this will take time. Can we do it using async/await or ThreadPool or Threading.

I want 4 (or 5) threads that can run parallaly and read the string array, collect table name and read the table data from sql server, post these activities this thread should create the table in my local server and write the data.

答: Oracle has something called database link. Probably SQL server has something similar too. I would recommend creating a db link. Then you can select the data from the source server to target server just using sql query without loading it into your C# code. Meanwhile, you can use your app for submitting the queries to the db. You can do it concurrently, one query per thread and all the threads are doing is submitting the query and waiting for its completion.  </p>


问:
Cordova application using Angular 2
Instead of ionic I would like to use cordova framework.

So far,

Step 1:

I have created an angular 2 application.

Step 2:

I have created an cordova application and integrated angular 2 application in it.

Its running successfully.

Step 3:

Next step is to load cordova.js file on load

Step 4:

Add cordova plugin(like camera , device ext) in my project.

Step 1 and 2  completed.

Please help me out to complete step 3 and step 4.

When I call plugin its throws an error as follows,

答: When are you calling the plugin - are you waiting for onDeviceReady to fire?</p>

Title: Cordova application using Angular 2


问:
Is Paypal Adaptive Payment API depreached
We are researching a way to automatically pay the developers of e-commerce modules we sell on our web shop. A lot of reading suggest the Paypal Adaptive Parallel Payment should be the solution. But Paypal developer docs seem to say that this API is now restricted and no option. If so, is there a new API from Paypal. The Braintree marketplace is no option for us in Europe</p>

答:
Actually Adaptive Payments are still supported now. You may try access below page to apply for an APP ID. If your application is approved, you may still continue integrate with Adaptive Payments.

https://www.paypal-apps.com/user/my-account/applications


问:
Making VBA Form TextBox accept Numbers only (including +, - and .)
I have simple textBox and I want to validate its input including "+" , "-"  and "." here is what I have tried

```<code>Private Sub DisplayValue_TextBox_Change()
If Not IsNumeric(DisplayValue_TextBox.Value) Then
               MsgBox "Only numbers allowed"

      End If
End Sub
</code>```

But this only accepts numbers 0-9 no negative, positive value or float value..

答:
Having relied up till now on string parsing to do this job, I'm glad I decided to check and see how other people do it and found this Q.

I've refined Ruben Alvarez's excellent answer.  The below will allow numerical entries only, and only one decimal point.

```<code>Private Sub txtShift1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

    Select Case KeyAscii
        Case 46
            If InStr(1, txtShift1, ".") > 0 Then KeyAscii = 0
        Case 48 To 57
        Case Else
            KeyAscii = 0
    End Select

End Sub
</code>```

This could be further refined to allow only a single "+", "-" etc. as necessary.

Body:
I have simple textBox and I want to validate its input including "+" , "-"  and "." here is what I have tried

Private Sub DisplayValue_TextBox_Change()
If Not IsNumeric(DisplayValue_TextBox.Value) Then
               MsgBox "Only numbers allowed"

      End If
End Sub

But this only accepts numbers 0-9 no negative, positive value or float value..

Body:
Having relied up till now on string parsing to do this job, I'm glad I decided to check and see how other people do it and found this Q.

I've refined Ruben Alvarez's excellent answer.  The below will allow numerical entries only, and only one decimal point.

Private Sub txtShift1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

    Select Case KeyAscii
        Case 46
            If InStr(1, txtShift1, ".") > 0 Then KeyAscii = 0
        Case 48 To 57
        Case Else
            KeyAscii = 0
    End Select

End Sub

This could be further refined to allow only a single "+", "-" etc. as necessary.


问:
mysqli_insert_id() expects exactly 1 parameter, 0 given in CodeIgniter
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

```<code>class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

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

And this is partly code in Controller
$data = array(

```<code>        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here
</code>```

And this My error:

答:
You are using codeigniter, so it would be better if you use codeigniter functions only to perform database operation.

Definitely you will get result using mysqli_insert_id(db_connection_object)
But it would be better if you use inbuilt function of codeigniter

```<code>    $this->db->insert_id();
</code>```

Body:
I have a problem, Please Help me. I'm using Code igniter
This is my code.

my Models (M_register.php)

class M_register extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function add_account($data)
    {
        $this->load->database();
        $this->db->insert('login',$data);
        **return  mysqli_insert_id();**
    }

    function changeActiveState($key)
    {
        $this->load->database();
        $data = array(
           'active' => 1
        );

        $this->db->where('md5(id)', $key);
        $this->db->update('login', $data);

        return true;
    }
}

And this is partly code in Controller
$data = array(

        'username' => $username,
        'password' => $password,
        'nama' => $nama,
        'email' => $email,
        'active' => 0
    );
    $this->load->model('m_register');
    **$id = $this->m_register->add_account($data);**
    $encrypted_id = md5($id);
enter code here

And this My error:

Body:
You are using codeigniter, so it would be better if you use codeigniter functions only to perform database operation.

Definitely you will get result using mysqli_insert_id(db_connection_object)
But it would be better if you use inbuilt function of codeigniter

    $this->db->insert_id();


问:
babel es5 to es6 converting less extension to css on imports
I wrote some npm scripts that builds the ./lib directory before publish to npm.

1. script is responsible to convert all es6 *.js files in ./src/components/ to es5 syntax and then copy the files to ./lib (same structure).

This is the script:

```<code>"cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files"
</code>```

And this is the .babelrc file:

```<code>{
  "presets": [
    "react",
    "stage-1"
  ],
  "env": {
    "development": {
      "presets": [
        "latest",
        "react-hmre"
      ]
    },
    "production": {
      "presets": [
        [
          "latest",
          "es2015"
        ]
      ],
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-remove-prop-types",
        [
          "transform-imports",
          {
            "react-bootstrap": {
              "transform": "react-bootstrap/lib/${member}",
              "preventFullImport": true
            },
            "lodash": {
              "transform": "lodash/${member}",
              "preventFullImport": true
            }
          }
        ]
      ]
    },
    "test": {
      "presets": [
        "latest"
      ]
    }
  }
}
</code>```

I have another script that responsible to convert .less files to .css and copy them to ./lib (same structure):

```<code>"lessc-glob ./src/components/**/*.less lib"
</code>```

Everything works well as expected, but i have one problem now. The import that i have inside the .js files are referring to .less files, but i need it to change to .css extensions.

To make things clear,

What i have now is:

```<code>import css from './styles.less';
</code>```

Converted into this:

```<code>var _styles = require('./styles.less');
</code>```

But i want it to convert to this:

```<code>var _styles = require('./styles.css');
</code>```

答:
replace can be installed and utilized to find instances of .less and replace them with .css in your resultant ES5 .js file/s.

npm script

Add a replace script to your package.json as follows:

...
"scripts": {
  ...
  "replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
},
...
```

<p>A call to the <code>replace</code> script can then be chained to the end your script that is responsible for converting all es6 <code>*.js</code> files. E.g.</p>

<pre class="lang-json prettyprint-override"><code>...
"scripts": {
  ...
  "quux": "cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files && npm run replace",
  "replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
  ...
},
...
</code>```

Note the && npm run replace part added to the end of your current quux script.

I've assumed the components folder is copied to the lib folder too. If it's not then the ./lib/components/ part in the replace script will need to be changed to ./lib/.

Body:
I wrote some npm scripts that builds the ./lib directory before publish to npm.

1. script is responsible to convert all es6 *.js files in ./src/components/ to es5 syntax and then copy the files to ./lib (same structure).

This is the script:

"cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files"

And this is the .babelrc file:

{
  "presets": [
    "react",
    "stage-1"
  ],
  "env": {
    "development": {
      "presets": [
        "latest",
        "react-hmre"
      ]
    },
    "production": {
      "presets": [
        [
          "latest",
          "es2015"
        ]
      ],
      "plugins": [
        "transform-react-constant-elements",
        "transform-react-remove-prop-types",
        [
          "transform-imports",
          {
            "react-bootstrap": {
              "transform": "react-bootstrap/lib/${member}",
              "preventFullImport": true
            },
            "lodash": {
              "transform": "lodash/${member}",
              "preventFullImport": true
            }
          }
        ]
      ]
    },
    "test": {
      "presets": [
        "latest"
      ]
    }
  }
}

I have another script that responsible to convert .less files to .css and copy them to ./lib (same structure):

"lessc-glob ./src/components/**/*.less lib"

Everything works well as expected, but i have one problem now. The import that i have inside the .js files are referring to .less files, but i need it to change to .css extensions.

To make things clear,

What i have now is:

import css from './styles.less';

Converted into this:

var _styles = require('./styles.less');

But i want it to convert to this:

var _styles = require('./styles.css');

Body:
replace can be installed and utilized to find instances of .less and replace them with .css in your resultant ES5 .js file/s.

npm script

Add a replace script to your package.json as follows:

...
"scripts": {
  ...
  "replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
},
...

A call to the replace script can then be chained to the end your script that is responsible for converting all es6 *.js files. E.g.

...
"scripts": {
  ...
  "quux": "cross-env NODE_ENV=production babel ./src/components --out-dir ./lib --ignore spec.js --copy-files && npm run replace",
  "replace": "replace \".less\" \".css\" ./lib/components/ -r --include=\"*.js\""
  ...
},
...

Note the && npm run replace part added to the end of your current quux script.

I've assumed the components folder is copied to the lib folder too. If it's not then the ./lib/components/ part in the replace script will need to be changed to ./lib/.


问:
Cleaning URL using mod_rewrite
I am trying to cleanup my URL using mod_rewrite.

In my URLs I have:

```<code>http://blog.com/cat/post1/index.html
http://blog.com/cat/post2/index.html
http://blog.com/cat/post3/index.html
etc....
</code>```

.htaccess

```<code>RewriteEngine on
RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
RewriteRule (.*)index\.(php|html)$ /$1 [R=301,L]
</code>```

When I enter the URL mentioned above I get:

```<code>http://blog.com/post1/
</code>```

But I want:

```<code>http://blog.com/cat/post1/
</code>```

What am I doing wrong here???

答:
```<code>RewriteEngine on
RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
RewriteRule (.*) http://blog.com/cat/$1 [R=301, L]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Cleaning URL using mod_rewrite

Body:
I am trying to cleanup my URL using mod_rewrite.

In my URLs I have:

http://blog.com/cat/post1/index.html
http://blog.com/cat/post2/index.html
http://blog.com/cat/post3/index.html
etc....

.htaccess

RewriteEngine on
RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
RewriteRule (.*)index\.(php|html)$ /$1 [R=301,L]

When I enter the URL mentioned above I get:

http://blog.com/post1/

But I want:

http://blog.com/cat/post1/

What am I doing wrong here???


问:
I want to remove double quotes from JSON.stringify object for pass it to amchart
I want to remove double quotes from JSON.stringify object for pass it to amchart

```<code> var data = JSON.stringify(ChartData);
</code>```

this line gives me the result given below..

```<code>"[{"USD":"Prod 1","FY 2016":2256},{"USD":"Prod 2","FY 2016":510},{"USD":"Prod 3","FY 2016":503}]"
</code>```

I want to remove begin and last double quotes from the result so that i can pass it to dataprovider of amchart.

Please go through the screenshot.

答:
why you stringfy your data?using this you can direct get your json result.

```<code> var jsonResult = Json(Data, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;
</code>```

Body:
I want to remove double quotes from JSON.stringify object for pass it to amchart

 var data = JSON.stringify(ChartData);

this line gives me the result given below..

"[{"USD":"Prod 1","FY 2016":2256},{"USD":"Prod 2","FY 2016":510},{"USD":"Prod 3","FY 2016":503}]"

I want to remove begin and last double quotes from the result so that i can pass it to dataprovider of amchart.

Please go through the screenshot.

Body:
why you stringfy your data?using this you can direct get your json result.

 var jsonResult = Json(Data, JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;


问:
How did Pentium III CPUs handle multiple instruction prefixes from the same group?
The Intel x86 specification states that using more than one instruction prefix from the same group results in undefined behavior. In practice, how did Pentium III Coppermine CPUs react in that situation? Sadly I don't have a chip to test.</p>

答:
Although you already know this, I'll start by stating it for clarity. x86 instructions can have up to 4 prefixes (each from a different group) that alter the processor's interpretation of the instruction. From the Intel IA-32 Architecture Manual, Volume 2A, Section 2.1:

2.1 INSTRUCTION FORMAT FOR PROTECTED MODE, REAL-ADDRESS MODE, AND VIRTUAL-8086 MODE

The Intel 64 and IA-32 architectures instruction encodings are subsets of the format shown in Figure 2-1. Instructions consist of optional instruction prefixes (in any order), primary opcode bytes (up to three bytes), an addressing-form specifier (if required) consisting of the ModR/M byte and sometimes the SIB (Scale-Index-Base) byte, a displacement (if required), and an immediate data field (if required).

  Figure 2-1. Intel 64 and IA-32 Architectures Instruction Format

2.1.1 Instruction Prefixes

Instruction prefixes are divided into four groups, each with a set of allowable prefix codes. For each instruction, it is only useful to include up to one prefix code from each of the four groups (Groups 1, 2, 3, 4). Groups 1 through 4 may be placed in any order relative to each other.

Group 1

Lock and repeat prefixes:

LOCK prefix is encoded using F0H.

REPNE/REPNZ prefix is encoded using F2H. Repeat-Not-Zero prefix applies only to string and
  input/output instructions. (F2H is also used as a mandatory prefix for some instructions.)

REP or REPE/REPZ is encoded using F3H. The repeat prefix applies only to string and input/output instructions. F3H is also used as a mandatory prefix for POPCNT, LZCNT and ADOX instructions.

Bound prefix is encoded using F2H if the following conditions are true:

CPUID.(EAX=07H, ECX=0):EBX.MPX[bit 14] is set.

BNDCFGU.EN and/or IA32_BNDCFGS.EN is set.

When the F2 prefix precedes a near CALL, a near RET, a near JMP, or a near Jcc instruction (see Chapter 17, “Intel® MPX,” of the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 1).

Group 2

Segment override prefixes:

2EH—CS segment override (use with any branch instruction is reserved).

36H—SS segment override prefix (use with any branch instruction is reserved).

3EH—DS segment override prefix (use with any branch instruction is reserved).

26H—ES segment override prefix (use with any branch instruction is reserved).

64H—FS segment override prefix (use with any branch instruction is reserved).

65H—GS segment override prefix (use with any branch instruction is reserved).

Branch hints (no longer used; reserved):

2EH—Branch not taken (used only with Jcc instructions).

3EH—Branch taken (used only with Jcc instructions).

Group 3

Operand-size override prefix is encoded using 66H (66H is also used as a mandatory prefix for some
  instructions).

Group 4

67H—Address-size override prefix.

The LOCK prefix (F0H) forces an operation that ensures exclusive use of shared memory in a multiprocessor environment. See “LOCK—Assert LOCK# Signal Prefix” in Chapter 3, “Instruction Set Reference, A-L,” for a description of this prefix.

Repeat prefixes (F2H, F3H) cause an instruction to be repeated for each element of a string. Use these prefixes only with string and I/O instructions (MOVS, CMPS, SCAS, LODS, STOS, INS, and OUTS). Use of repeat prefixes and/or undefined opcodes with other Intel 64 or IA-32 instructions is reserved; such use may cause unpredictable behavior.

Some instructions may use F2H,F3H as a mandatory prefix to express distinct functionality.

Branch hint prefixes (2EH, 3EH) allow a program to give a hint to the processor about the most likely code path for a branch. Use these prefixes only with conditional branch instructions (Jcc). Other use of branch hint prefixes and/or other undefined opcodes with Intel 64 or IA-32 instructions is reserved; such use may cause unpredictable behavior.

The operand-size override prefix allows a program to switch between 16- and 32-bit operand sizes. Either size can be the default; use of the prefix selects the non-default size.

Some SSE2/SSE3/SSSE3/SSE4 instructions and instructions using a three-byte sequence of primary opcode bytes may use 66H as a mandatory prefix to express distinct functionality.

Other use of the 66H prefix is reserved; such use may cause unpredictable behavior.

The address-size override prefix (67H) allows programs to switch between 16- and 32-bit addressing. Either size can be the default; the prefix selects the non-default size. Using this prefix and/or other undefined opcodes when operands for the instruction do not reside in memory is reserved; such use may cause unpredictable behavior.

Notice that it doesn't actually say that multiple instruction prefixes from the same group result in "undefined behavior." Rather, it just says that it is "only useful" to include up to one from each group. That leaves things pretty unspecified.

Looks to me like the only formal guarantees you get from the specification are that certain, specific combinations of instructions and prefixes can result in either "unpredictable behavior" or an exception, and that any single instruction longer than 15 bytes results in an "Invalid Opcode" exception.

That leaves us to test empirically multiple prefixes from each group on instructions where they are otherwise supported. To that end, and as requested, I ran the following tests on a Pentium III Coppermine1:

Group 1: Various combinations of multiple REPE (F3) and REPNE (F2) prefixes on a CMPSB instruction (A6).

Only the last prefix that is encountered has an effect; other prefixes from the same group that precede it are ignored.

In fact, this appears to be standard behavior for all x86 processors, and is consistent with how Microsoft's disassembler shows the code. The leading (ignored) prefixes are not shown as being part of the instruction.

Group 2: Multiple segment override prefixes on a load (MOV) instruction.

Again, the very last prefix is the only one that matters. All others are ignored. And again, this seems to be standard for all x86 processors.

(I didn't bother to test branch-hint prefixes, either alone or in combination with segment-override prefixes, as these branch hints are ignored on all processors but the Pentium 4.)

Group 3: Multiple operand-size override prefixes (66h).

Repeated prefixes are ignored, so multiple 66h prefixes have exactly the same effect as one 66h prefix. They do not cancel each other out or any such thing.

Various sources online confirm that this is standard behavior for all x86 processors.

Group 4: Multiple address-size override prefixes (67h).

Same as Group 3: repeated prefixes are ignored.

In summary: In effect, all but the last prefix from a particular group are ignored. The very last prefix encountered on an instruction is the one that takes effect. All preceding redundant or meaningless prefixes are ignored. This appears to be true for all x86 processors, meaning that emulation code does not need to special-case this behavior for any particular generation/microarchitecture. However, prefixes that have no effect in one context might be re-purposed to have some meaning on future processors, so this is something to watch out for.

If possible, to save yourself the headache, you might consider offloading this interpretational work to your decoder. Specifically, one written by Intel, the Intel XED library (repository here on GitHub). You just give it anywhere from 1 to 15 bytes, and it returns the decoded opcode (including prefixes) and operands. Decoding is the hard part of x86, so this should save you a lot of headaches. It implements the same algorithm as described here—see, e.g., these notes and this code.

__

1 Specifically, an Intel Pentium III EB @ 866 MHz (Family 6, Model 8, Stepping 6, Revision cC0). This is a Socket 370 FC-PGA chip, running on a Compaq Deskpro EN system with an Intel 815-based motherboard (133 MHz FSB). In case it matters (and it obviously shouldn't), the operating environment was Windows 2000 SP4. I used MASM and Visual Studio's debugger for testing.


问:
Java - "no buffer space available" socket error cause?
I'm writing a networking program in Java. I use ServerSocket and Socket objects to send and receive messages using TCP. My program runs fine if run for a short time however if I run it for a longer time, I get the following error:

```<code>java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
</code>```

I thought it might be because I do not close all sockets but I've changed my code: I have one class that I create when I want a new socket and have added a finalize method to close it. I also have a finalize method to close the ServerSocket so I don't know what the problem is.

Also after I get the error, if I run the program again straight away, it runs into the problem quicker than before. Then if I wait for a while and run it, it goes back to like the original time.

I really cannot work out the problem and I've been trying to figure it out for ages. Does anyone have any idea what the problem is?

Thanks in advance!

UPDATE:

So I've figured out where the error is coming from and it's really weird. I have the following code which is causing the problem:

```<code>try {
        sock = new Socket(InetAddress.getByName(ipaddr), port);
        sock.close();

        // os = sock.getOutputStream();
        // byte[] arr = s.getBytes();
        // os.write(arr);
        // os.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            sock.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

As you can see, the code should open a socket and write to it. However even when all the functional code is commented out as above, so the socket is just opened then immediately closed, I still get the "no buffer space" error.

I really cannot work out why this is. The program is multi threaded and each thread creates objects periodically with the above method in and call it. When the lines to create and close the socket are removed, I no longer get the error but when they are there, even though the socket is opened then closed immediately, I get the error.

Does anyone have any clue why this is happening?

Many thanks.

答:
I have one class that I create when I want a new socket and have added a finalize method to close it. I also have a finalize method to close the ServerSocket so I don't know what the problem is.

Bzzt. Stop. Check. Finalizers are non-deterministic when they run (except some time after the object is no longer reachable, although perhaps not even if the Java app terminates!) -- see Destroying and Finalizing. Make sure you are using a explicit contract such as Closable and invoking it through and through (don't wait for the GC to come about!).

This problem is most indicative of "leaking" external resources -- since the GC cares mostly about memory and memory pressure, if there is little pressure and/or the GC is not aggressive it is very easy to run out of the external resources first because the finalizers are not run (yet). In general, finalizer are a safety-net (that doesn't always work), but are not a replacement for other forms of external resource management.

From the link above:

Java makes no guarantees about when garbage collection will occur or in what order objects will be collected. Therefore, Java can make no guarantees about when (or even whether) a finalizer will be invoked, in what order finalizers will be invoked, or what thread will execute finalizers.

Happy coding.

Edit: See this related question: Why would you ever implement finalize()?. I like the 2nd response from Steve Jessop.

Body:
I'm writing a networking program in Java. I use ServerSocket and Socket objects to send and receive messages using TCP. My program runs fine if run for a short time however if I run it for a longer time, I get the following error:

java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)

I thought it might be because I do not close all sockets but I've changed my code: I have one class that I create when I want a new socket and have added a finalize method to close it. I also have a finalize method to close the ServerSocket so I don't know what the problem is.

Also after I get the error, if I run the program again straight away, it runs into the problem quicker than before. Then if I wait for a while and run it, it goes back to like the original time.

I really cannot work out the problem and I've been trying to figure it out for ages. Does anyone have any idea what the problem is?

Thanks in advance!

UPDATE:

So I've figured out where the error is coming from and it's really weird. I have the following code which is causing the problem:

try {
        sock = new Socket(InetAddress.getByName(ipaddr), port);
        sock.close();

        // os = sock.getOutputStream();
        // byte[] arr = s.getBytes();
        // os.write(arr);
        // os.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            sock.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

As you can see, the code should open a socket and write to it. However even when all the functional code is commented out as above, so the socket is just opened then immediately closed, I still get the "no buffer space" error.

I really cannot work out why this is. The program is multi threaded and each thread creates objects periodically with the above method in and call it. When the lines to create and close the socket are removed, I no longer get the error but when they are there, even though the socket is opened then closed immediately, I get the error.

Does anyone have any clue why this is happening?

Many thanks.


答:
you can use an inner join </p>

```<code>select *
from emp
inner join (
    Select emp_no
     From dept_emp
     Where dept_no = 'd002'

) t on emp_no.id = t.emp_no
</code>```

<p>or  without subselect </p>

```<code>select *
from emp
inner join dept_emp on emp_no.id = dept_emp.emp_no
   and dept_emp.dept_no = 'd002'
</code>```

Title: Query Fine Tuning

Body:
you can use an inner join

select *
from emp
inner join (
    Select emp_no
     From dept_emp
     Where dept_no = 'd002'

) t on emp_no.id = t.emp_no

or  without subselect

select *
from emp
inner join dept_emp on emp_no.id = dept_emp.emp_no
   and dept_emp.dept_no = 'd002'


问:
Display a xib view into a UITableView Cell
I made a view in a xib file which is loaded in the main ViewController called "ExperienceScreen". Adding this xib view to the ExperienceScreen works perfectly. The problem is that I would like to add this xib view in a UITableViewCel. I am using the following code to do that :

```<code>   let experiences = service.getExperiences()

    // 3. Loop through the array of experiences
    for element in experiences {

        if let customView = Bundle.main.loadNibNamed("ExperienceDetail", owner: self, options: nil)?.first as? ExperienceDetail
        {
            customView.lblTitle.text = element.title
            customView.lblCompany.text = element.company
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
            cell.addSubview(customView)
            cell.bringSubview(toFront: customView)
        }
    }

    tableView.reloadData()
</code>```

When launching, the subview is not shown in the UITableViewCell. The customView View is filled correctly with the xib View. I checked this using a breakpoint.

Someone knows what I'am doing wrong?

Many thanks for helping !!

答:
Don't try to set up your cells all at once.

You should implement the UITableViewDataSource protocol and configure each cell using the method tableView(_:cellForRowAt:). In this method, you can call register(_:forCellReuseIdentifier:) to use your XIB for newly created cells.

There are lots of tutorials on creating table views where you can find step-by-step instructions on doing this.

Body:
I made a view in a xib file which is loaded in the main ViewController called "ExperienceScreen". Adding this xib view to the ExperienceScreen works perfectly. The problem is that I would like to add this xib view in a UITableViewCel. I am using the following code to do that :

   let experiences = service.getExperiences()

    // 3. Loop through the array of experiences
    for element in experiences {

        if let customView = Bundle.main.loadNibNamed("ExperienceDetail", owner: self, options: nil)?.first as? ExperienceDetail
        {
            customView.lblTitle.text = element.title
            customView.lblCompany.text = element.company
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
            cell.addSubview(customView)
            cell.bringSubview(toFront: customView)
        }
    }

    tableView.reloadData()

When launching, the subview is not shown in the UITableViewCell. The customView View is filled correctly with the xib View. I checked this using a breakpoint.

Someone knows what I'am doing wrong?

Many thanks for helping !!


问:
How to call a function to execute on the url
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

```<code>$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."<br />";
        }
    }
}
</code>```

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?

答: In this case, you have to break the url to get the last parameter after the index.php, in your case it is day. On the behalf of this parameter make different code blocks and execute them as per the parameter passed.

Body:
I wrote a code which is working fine but now I want it to be in a function so as to call it on the url. I will really appreciate if you guys can help.

Here is my code.

$conn = mysqli_connect("localhost","root","","db");
if(mysqli_connect_errno()){
    echo "Unable to connect".mysqli_connect_error();
}

function day(){
$sql = "SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y') FROM ts_user
        WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY";
    if($result = mysqli_query($conn,$sql)){
        while($row = mysqli_fetch_assoc($result)){
            echo $row['user_uname']."
";
        }
    }
}

And am calling it on the url as
http://localhost/test/index.php/day

Please telling me what am doing wrong. am I calling it wrongly on the url?


问:
How to Query Azure Storage metrics for last five minutes using Java SDK
I have written a stand alone code to get the metrics for Azure Storage Blob Services but i want to get only last 5mins metric how can i get it from $MetricsMinutePrimaryTransactionsBlob please suggest</p>

```<code>CloudTable cloudMetric = tableClient.getTableReference(cloud
                .getHourMetricsTable(StorageService.BLOB).getName());
        String partitionFilter2 = TableQuery.generateFilterCondition(
                "PartitionKey", QueryComparisons.EQUAL, "20170602T1400");
        String rowFilter3 = TableQuery.generateFilterCondition("RowKey",
                QueryComparisons.EQUAL, "user;All");
        String combinedFilter = TableQuery.combineFilters(partitionFilter2,
                Operators.AND, rowFilter3);
        TableQuery<MetricsPojo> partitionQuery2 = TableQuery.from(
                MetricsPojo.class).where(combinedFilter);
        for (MetricsPojo capacityMetrics2 : cloudMetric
                .execute(partitionQuery2)) {
            System.out.println(capacityMetrics2);
            System.out.println(capacityMetrics2.getPartitionKey() + "\n"
                    + capacityMetrics2.getRowKey() + "\n"
                    + capacityMetrics2.getTimestamp());
</code>```

答:
According to your description and @FrancisYu-MSFT reply, I wrote a sample code and reproduced your current issue.

Here is my sample code.

```<code>String connectionString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s", ACCOUNT_NAME, ACCOUNT_KEY);
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudAnalyticsClient client = account.createCloudAnalyticsClient();
CloudTable metrics = client.getMinuteMetricsTable(StorageService.BLOB);
System.out.println(metrics.getName());
String queryString = TableQuery.combineFilters(
                TableQuery.generateFilterCondition("PartitionKey", QueryComparisons.GREATER_THAN_OR_EQUAL, "20170602T1400"),
                Operators.AND,
                TableQuery.generateFilterCondition("PartitionKey", QueryComparisons.LESS_THAN_OR_EQUAL, "20170602T1420"));
TableQuery<TableServiceEntity> query = TableQuery.from(TableServiceEntity.class).where(queryString);
for(TableServiceEntity entity : metrics.execute(query)) {
    System.out.println(entity.getPartitionKey()+"\t"+entity.getRowKey());
}
</code>```

Then I got the same issue when running my code, which was caused by the metrics table $MetricsMinutePrimaryTransactionsBlob not exists, so you need to enable the related Diagnostics options to create it, as the figure below.

Body:
I have written a stand alone code to get the metrics for Azure Storage Blob Services but i want to get only last 5mins metric how can i get it from $MetricsMinutePrimaryTransactionsBlob please suggest

CloudTable cloudMetric = tableClient.getTableReference(cloud
                .getHourMetricsTable(StorageService.BLOB).getName());
        String partitionFilter2 = TableQuery.generateFilterCondition(
                "PartitionKey", QueryComparisons.EQUAL, "20170602T1400");
        String rowFilter3 = TableQuery.generateFilterCondition("RowKey",
                QueryComparisons.EQUAL, "user;All");
        String combinedFilter = TableQuery.combineFilters(partitionFilter2,
                Operators.AND, rowFilter3);
        TableQuery<MetricsPojo> partitionQuery2 = TableQuery.from(
                MetricsPojo.class).where(combinedFilter);
        for (MetricsPojo capacityMetrics2 : cloudMetric
                .execute(partitionQuery2)) {
            System.out.println(capacityMetrics2);
            System.out.println(capacityMetrics2.getPartitionKey() + "\n"
                    + capacityMetrics2.getRowKey() + "\n"
                    + capacityMetrics2.getTimestamp());

Body:
According to your description and @FrancisYu-MSFT reply, I wrote a sample code and reproduced your current issue.

Here is my sample code.

String connectionString = String.format("DefaultEndpointsProtocol=http;AccountName=%s;AccountKey=%s", ACCOUNT_NAME, ACCOUNT_KEY);
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudAnalyticsClient client = account.createCloudAnalyticsClient();
CloudTable metrics = client.getMinuteMetricsTable(StorageService.BLOB);
System.out.println(metrics.getName());
String queryString = TableQuery.combineFilters(
                TableQuery.generateFilterCondition("PartitionKey", QueryComparisons.GREATER_THAN_OR_EQUAL, "20170602T1400"),
                Operators.AND,
                TableQuery.generateFilterCondition("PartitionKey", QueryComparisons.LESS_THAN_OR_EQUAL, "20170602T1420"));
TableQuery<TableServiceEntity> query = TableQuery.from(TableServiceEntity.class).where(queryString);
for(TableServiceEntity entity : metrics.execute(query)) {
    System.out.println(entity.getPartitionKey()+"\t"+entity.getRowKey());
}

Then I got the same issue when running my code, which was caused by the metrics table $MetricsMinutePrimaryTransactionsBlob not exists, so you need to enable the related Diagnostics options to create it, as the figure below.


问:
Enumeration is throwing concurrentModification Exception. why?
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

```<code>public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}
</code>```

Find the error message below

```<code>Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)
</code>```

答:
Your Enumeration uses an Iterator internally. While iterating over the elements, you can't use the vector itself to remove items. You have to use the iterator. But you don't have access to it. Create an iterator instead:

```<code>public static void main(String[] args) {

    final Vector<String> v = new Vector<String>();
    v.add("Amit");
    v.add("Raj");

    // Use an Iterator to remove the value you are iterating over
    final Iterator<String> iterator = v.iterator();

    while (iterator.hasNext()) {
        final String value = iterator.next();
        System.out.println(value);
        iterator.remove();
    }
}
</code>```

Though Vector is practically deprecated anyways. You should propably use a List instead:

The imports for the correct Lists (don't use the awt.List for this):

```<code>import java.util.ArrayList;
import java.util.List;
</code>```

The changed code:

```<code>public static void main(String[] args) {

    final List<String> v = new ArrayList<>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");

    final Iterator<String> iterator = v.iterator();

    while (iterator.hasNext()) {
        final String value = iterator.next();
        System.out.println(value);
        iterator.remove();
    }
}
</code>```

Also note you can use the interface as Type which is generally preferred to using the implementation.

Edit:

Looking at your example, maybe what you really need is a queue:

```<code>public static void main(String[] args) {

    final Queue<String> v = new LinkedList<>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");

    System.out.println("Size: " + v.size());
    for (String element = v.poll(); element != null; element = v.poll()) {
        System.out.println(element);
    }
    System.out.println("Size: " + v.size());
}
</code>```

Output:

```<code>Size: 3
Amit
Raj
Pathak
Size: 0
</code>```

This works the same as your example. For more info on Collections see The official Collections Java Trail

Body:
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}

Find the error message below

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)

Body:
Your Enumeration uses an Iterator internally. While iterating over the elements, you can't use the vector itself to remove items. You have to use the iterator. But you don't have access to it. Create an iterator instead:

public static void main(String[] args) {

    final Vector<String> v = new Vector<String>();
    v.add("Amit");
    v.add("Raj");

    // Use an Iterator to remove the value you are iterating over
    final Iterator<String> iterator = v.iterator();

    while (iterator.hasNext()) {
        final String value = iterator.next();
        System.out.println(value);
        iterator.remove();
    }
}

Though Vector is practically deprecated anyways. You should propably use a List instead:

The imports for the correct Lists (don't use the awt.List for this):

import java.util.ArrayList;
import java.util.List;

The changed code:

public static void main(String[] args) {

    final List<String> v = new ArrayList<>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");

    final Iterator<String> iterator = v.iterator();

    while (iterator.hasNext()) {
        final String value = iterator.next();
        System.out.println(value);
        iterator.remove();
    }
}

Also note you can use the interface as Type which is generally preferred to using the implementation.

Edit:

Looking at your example, maybe what you really need is a queue:

public static void main(String[] args) {

    final Queue<String> v = new LinkedList<>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");

    System.out.println("Size: " + v.size());
    for (String element = v.poll(); element != null; element = v.poll()) {
        System.out.println(element);
    }
    System.out.println("Size: " + v.size());
}

Output:

Size: 3
Amit
Raj
Pathak
Size: 0

This works the same as your example. For more info on Collections see The official Collections Java Trail


问:
Are multiple operations for string formatting allowed in Python?
Could be a basic one:

I am just trying to do multiple operations on one of the key in a dictionary with encoding the first element of the key, splitting it further based on a character and also joining with another string as below:

```<code>images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
</code>```

Code snippet in which I am doing the above formatting:

```<code>from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests

@require_http_methods(["GET"])
def images_info(request):
    response = requests.get("http://127.0.0.1:6000/images/json")
    table = []
    images_list = {}
    for image in response.json():
        try:
            images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8")
        except TypeError:
            images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
        images_list["Id"] = image["Id"].encode("utf-8")[7:19]
        table.append(images_list)
        images_list = {}

    return JsonResponse(table,safe=False)
</code>```

Can someone tell me whether is it the right way to do these many operations in a single line? or in another way Does it follows the python standards ?

If not does python standards suggest any limited operations in a single line or so?

Reason for asking this is that the number of characters should not exceed 79 characters as per pep-8.

答:
It is asked not to exceed 79 characters, but we can do it.

```<code>    images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + \
    ":none"
</code>```

OR

```<code>images_list["RepoTag"] = \
    image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
</code>```

Body:
Could be a basic one:

I am just trying to do multiple operations on one of the key in a dictionary with encoding the first element of the key, splitting it further based on a character and also joining with another string as below:

images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"

Code snippet in which I am doing the above formatting:

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests

@require_http_methods(["GET"])
def images_info(request):
    response = requests.get("http://127.0.0.1:6000/images/json")
    table = []
    images_list = {}
    for image in response.json():
        try:
            images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8")
        except TypeError:
            images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
        images_list["Id"] = image["Id"].encode("utf-8")[7:19]
        table.append(images_list)
        images_list = {}

    return JsonResponse(table,safe=False)

Can someone tell me whether is it the right way to do these many operations in a single line? or in another way Does it follows the python standards ?

If not does python standards suggest any limited operations in a single line or so?

Reason for asking this is that the number of characters should not exceed 79 characters as per pep-8.

Body:
It is asked not to exceed 79 characters, but we can do it.

    images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + \
    ":none"

OR

images_list["RepoTag"] = \
    image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"


问:
Python - Best way to append a sequence of numbers to a text file?
Let's say that I have textfile of a series of numbers that looks like this:

```<code>18,18,19,19,16,20,19,20,18,20,21
</code>```

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

```<code>text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))
</code>```

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

答:
```<code>text_file = open("sequence.txt", "r")
src = text_file.read()
src = src.split(',')
src = map(int, src) #this works on python 2.x, for python3 do src = list(map(int, src))
print src
text_file.close()
</code>```

Output:

```<code>[18, 18, 19, 19, 16, 20, 19, 20, 18, 20, 21]
</code>```

Body:
Let's say that I have textfile of a series of numbers that looks like this:

18,18,19,19,16,20,19,20,18,20,21

That's only a preview of hundreds of numbers separated by commas. I want to be able to manipulate the data in python in a [list]. So I have a variable src that I want to append the integer values to from the text file.

Like so:

text_file = open("sequence.txt","r")
src = []

for entry in text_file.read():
    if(entry != ','):
        src.append(int(entry))

Obviously this get's rid of the ',' between each entry in my textfile however values like 20 in the textfile will be appended to the list as two separate entries [2,0].

What's the best way to append these values ?
Thanks !

Body:
text_file = open("sequence.txt", "r")
src = text_file.read()
src = src.split(',')
src = map(int, src) #this works on python 2.x, for python3 do src = list(map(int, src))
print src
text_file.close()

Output:

[18, 18, 19, 19, 16, 20, 19, 20, 18, 20, 21]


问:
PDO if condition on row
I am in the process of making a login system using PDO. What I am finding is that users are able to log in despite their info not being in the database.

My PHP code is as follows:

```<code> $error = "";
if(isset($_POST["submit"])){

    if(empty($_POST["youremaildesktop"]) || empty($_POST["yourpassworddesktop"]))
        {$error = "Both fields are required.";}

    else{

        $username=$_POST['youremaildesktop'];
        $password=$_POST['yourpassworddesktop'];

        $username = stripslashes($username);
        $password = stripslashes($password);
        $password = md5($password);

        /*PDO Version*/
        $resulter = $dbh->prepare("
            SELECT uid
            FROM customer
            WHERE username = '$username'
            AND password = '$password'
        ");

 $resulter->fetchColumn();

if($resulter)
{
    $_SESSION['localstorage'] = $username;
    header("Location: userpage.php");
}
else {
$error = "Incorrect username or password.";
}

    }
 }
</code>```

The $dbh PHP variable corresponds to my database connection credentials. The POST values correspond to my login form on my main page.

The goal is to connect users to userpage.php only if their credentials are correct. However, I am able to log in regardless of whether the user details correspond to users in my database.

答:
Here's how I would of tackled the situation myself..

```<code>if (isset($_POST['submit']))
{
    $username = $_POST['youremaildesktop'];
    $password = $_POST['yourpasswordesktop'];

    if (!empty($username) && !empty($password))
    {
        $res = $dbh->prepare("SELECT * FROM `customer` WHERE `username` = ?");
        $res->execute([$username]);

        $row = $res->fetch(PDO::FETCH_ASSOC);

        if ($res->rowCount() > 0)
        {
            if (password_verify($password, $row['password']))
            {
                $_SESSION['user_session'] = $row['uid'];

                header('Location: vm913.php');
            } else {
                // echo incorrect pass
            }
        } else {
            // echo no such user...
        }
    } else {
        // echo something...
    }
}
</code>```

Edited as I missed an echo on the wrong password bit!

You'll see password_verify() rather than using md5 which really isn't recommended. You'll also see within my query I have bound the param.

Note: Obviously you will need to use password_hash() within the registration side of things before password_verify() will work.

Up to you at the end of the day, but it's always best practice to cover your backside.

I'd also, always assign the session to the userid rather than the username.

As an optional extra, may be worth adding login logs and failed logs to your system also.

Title: PDO if condition on row

Body:
I am in the process of making a login system using PDO. What I am finding is that users are able to log in despite their info not being in the database.

My PHP code is as follows:

 $error = "";
if(isset($_POST["submit"])){

    if(empty($_POST["youremaildesktop"]) || empty($_POST["yourpassworddesktop"]))
        {$error = "Both fields are required.";}

    else{

        $username=$_POST['youremaildesktop'];
        $password=$_POST['yourpassworddesktop'];

        $username = stripslashes($username);
        $password = stripslashes($password);
        $password = md5($password);

        /*PDO Version*/
        $resulter = $dbh->prepare("
            SELECT uid
            FROM customer
            WHERE username = '$username'
            AND password = '$password'
        ");

 $resulter->fetchColumn();

if($resulter)
{
    $_SESSION['localstorage'] = $username;
    header("Location: userpage.php");
}
else {
$error = "Incorrect username or password.";
}

    }
 }

The $dbh PHP variable corresponds to my database connection credentials. The POST values correspond to my login form on my main page.

The goal is to connect users to userpage.php only if their credentials are correct. However, I am able to log in regardless of whether the user details correspond to users in my database.

Body:
Here's how I would of tackled the situation myself..

if (isset($_POST['submit']))
{
    $username = $_POST['youremaildesktop'];
    $password = $_POST['yourpasswordesktop'];

    if (!empty($username) && !empty($password))
    {
        $res = $dbh->prepare("SELECT * FROM `customer` WHERE `username` = ?");
        $res->execute([$username]);

        $row = $res->fetch(PDO::FETCH_ASSOC);

        if ($res->rowCount() > 0)
        {
            if (password_verify($password, $row['password']))
            {
                $_SESSION['user_session'] = $row['uid'];

                header('Location: vm913.php');
            } else {
                // echo incorrect pass
            }
        } else {
            // echo no such user...
        }
    } else {
        // echo something...
    }
}

Edited as I missed an echo on the wrong password bit!

You'll see password_verify() rather than using md5 which really isn't recommended. You'll also see within my query I have bound the param.

Note: Obviously you will need to use password_hash() within the registration side of things before password_verify() will work.

Up to you at the end of the day, but it's always best practice to cover your backside.

I'd also, always assign the session to the userid rather than the username.

As an optional extra, may be worth adding login logs and failed logs to your system also.


问:
Changing a CSS property of an element when that element scrolls past a line
I'm working on a website, within this website, there is a scroll icon that has a fixed position and thus scrolls with the user. Because of the duotone design of the website, I'd like this icon to change color when it goes from a light to a dark background. Small example:

As you can see, the scroll text is now white, on a dark background. However, when it scrolls over to the white side, I'd like the scroll text to become dark.

What I did try to do is use the waypoints library to make every light section a waypoint and then change colors like this:

```<code>$('.light').waypoint(function(direction) {
    $(".scroll").find('span').css('color', '#000');
});
</code>```

However, this would only activate when the user reaches the bottom of the .light element.

Is there a way to do this in a smoother fashion? Thanks.

edit Like asked in the comments, here's a codepen:
https://codepen.io/anon/pen/ZyYBKM

答:
Of course this is possible.
To achieve this effect you will have to set an offset.
In this case the offset would be 100%.

The updated code:

```<code>$('.light').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    }
  },
  offset: '100%'
});
$('.dark').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    }
  },
  offset: '100%'
});
</code>```

Link to a codepen

Body:
I'm working on a website, within this website, there is a scroll icon that has a fixed position and thus scrolls with the user. Because of the duotone design of the website, I'd like this icon to change color when it goes from a light to a dark background. Small example:

As you can see, the scroll text is now white, on a dark background. However, when it scrolls over to the white side, I'd like the scroll text to become dark.

What I did try to do is use the waypoints library to make every light section a waypoint and then change colors like this:

$('.light').waypoint(function(direction) {
    $(".scroll").find('span').css('color', '#000');
});

However, this would only activate when the user reaches the bottom of the .light element.

Is there a way to do this in a smoother fashion? Thanks.

edit Like asked in the comments, here's a codepen:
https://codepen.io/anon/pen/ZyYBKM

Body:
Of course this is possible.
To achieve this effect you will have to set an offset.
In this case the offset would be 100%.

The updated code:

$('.light').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    }
  },
  offset: '100%'
});
$('.dark').waypoint({
  handler: function(direction) {
    if(direction == "down") {
     $(".scroll").find('div').css('background', '#ffffff');
     $(".scroll").find('span').css('color', '#ffffff');
    } else {
      // Scrolling up, reverse the process
     $(".scroll").find('div').css('background', '#252A2F');
     $(".scroll").find('span').css('color', '#252A2F');
    }
  },
  offset: '100%'
});

Link to a codepen


问:
UIWebview won't zoom even after setting scalesPageToFit to YES
I have a UIWebview that is loaded as a subview when a user selects a tab on a UISegmentedControl. For some reason, I can not get it to allow pinch/zooming.
I set the following code in the viewDidLoad: method, so it should work.

```<code>self.myWebView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: myWebView];
</code>```

I tried loading a UIWebView from a NIB and creating it programmatically with no avail. Is there something I'm missing? What could be causing the webview to ignore pinching and zooming?

Thanks!

答:
```<code>  [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom = 5.0;"];
</code>```

seem to be the suitable solution

Body:
I have a UIWebview that is loaded as a subview when a user selects a tab on a UISegmentedControl. For some reason, I can not get it to allow pinch/zooming.
I set the following code in the viewDidLoad: method, so it should work.

self.myWebView = [[[UIWebView alloc] initWithFrame:self.view.frame] autorelease];
self.myWebView.backgroundColor = [UIColor whiteColor];
self.myWebView.scalesPageToFit = YES;
self.myWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.myWebView.delegate = self;
[self.view addSubview: myWebView];

I tried loading a UIWebView from a NIB and creating it programmatically with no avail. Is there something I'm missing? What could be causing the webview to ignore pinching and zooming?

Thanks!

Body:
  [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom = 5.0;"];

seem to be the suitable solution