问:
SQL Server : get IN value for which it was found that row
I'm having difficulties for solving this problem. I'm using Microsoft SQL Server 2014 (ver. 12.0.4100.1).

I have two tables contacts and business. I have an array of contact usernames. I'm fetching a business list from this username array with a subquery in the WHERE, like this:

```<code>SELECT business.id, business.name, business.notes
FROM business
WHERE business.id IN (SELECT contacts.business_id
                      FROM contacts
                      WHERE contacts.username IN ('username1', 'username2', 'username3'))
</code>```

This query is working correctly, but I can't figure out how to select also the value for which every row was found; for example: if I fetch the business from the contact with username 'username1', I want to fetch it and see the result:

```<code>business.id = 1
business.name = 'Business 1'
business.notes = 'Notes from business 1.'
contacts.username = 'username1'
</code>```

Getting that result, I could see easily from what contact came every business.

Thank you in advance!

EDIT: There may be more than one contact for every business, so doing an INNER JOIN would return duplicated business results for every contact. I want to know exactly what contact was the one which was selected on the subquery.

答:
I think you are looking for a join:

```<code>SELECT b.id, b.name, b.notes, c.username
FROM business b JOIN
     contacts c
     ON b.id = c.business_id
WHERE c.username IN ('username1', 'username2', 'username3');
</code>```

Body:
I'm having difficulties for solving this problem. I'm using Microsoft SQL Server 2014 (ver. 12.0.4100.1).

I have two tables contacts and business. I have an array of contact usernames. I'm fetching a business list from this username array with a subquery in the WHERE, like this:

SELECT business.id, business.name, business.notes
FROM business
WHERE business.id IN (SELECT contacts.business_id
                      FROM contacts
                      WHERE contacts.username IN ('username1', 'username2', 'username3'))

This query is working correctly, but I can't figure out how to select also the value for which every row was found; for example: if I fetch the business from the contact with username 'username1', I want to fetch it and see the result:

business.id = 1
business.name = 'Business 1'
business.notes = 'Notes from business 1.'
contacts.username = 'username1'

Getting that result, I could see easily from what contact came every business.

Thank you in advance!

EDIT: There may be more than one contact for every business, so doing an INNER JOIN would return duplicated business results for every contact. I want to know exactly what contact was the one which was selected on the subquery.

Body:
I think you are looking for a join:

SELECT b.id, b.name, b.notes, c.username
FROM business b JOIN
     contacts c
     ON b.id = c.business_id
WHERE c.username IN ('username1', 'username2', 'username3');


来源: stackexchange

问:
How can I avoid connection timeout when the same php file runs multiple times
Please I need your help with a php script I am trying to build.
I have created this script to send multiple sms to some recipients.All data are stored into a database table (data > 1500 rows).I use select query with LIMIT 0, 1. When the message goes I delete the specific row and I include the file again to proceed to the next row. The problem is that at the time the rows = 300 I have a CONNECTION TIMEOUT ERROR. Please let me know how can I solve this or if there is another way to figure this out..

答:
You need to change in your php.ini file these two lines based on your requiredment

```<code> max_execution_time = 60;  // sec
</code>```

Or Put this line at the top of your page

```<code>set_time_limit(100);   // Sec
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You need to change in your php.ini file these two lines based on your requiredment

 max_execution_time = 60;  // sec

Or Put this line at the top of your page

set_time_limit(100);   // Sec


问:
Eclipse faceted project metadata file could not be read
Every now and then, I get this error in one of my Eclipse projects:

Faceted project metadata file "/project/.settings/org.eclipse.wst.common.project.facet.core.xml" could not be read.

This is a team project using Git. The ".settings" directory does not exist at all.

I'm not sure what project "facets" in Eclipse really are. Does anyone know what this error means or how to fix it?

答: not sure why it even looks for facets in my case since i don't use it, was solved for me by going to project facets, ticking one facet and then apply then removing the facet then apply again</p>


问:
JavaFX Preloader never called from main
My IDE is IntelliJ. I tried this document to learn preloader but for some reason preloader never gets called from my main class, or even its methods get called.

So here is my main class:

```<code>public class LongInitApp extends Application {
Stage stage;
BooleanProperty ready = new SimpleBooleanProperty(false);
private void longStart() {
    //simulate long init in background
    Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int max = 10;
            for (int i = 1; i <= max; i++) {
                Thread.sleep(200);
                notifyPreloader(new ProgressNotification(((double) i)/max));
            }
            ready.setValue(Boolean.TRUE);

            notifyPreloader(new StateChangeNotification(
                StateChangeNotification.Type.BEFORE_START));
           return null;
        }};
    new Thread(task).start();
}

 public static void main(String args[]) {
    launch(args);
  }

@Override
public void start(final Stage stage) throws Exception {
    longStart();
    stage.setScene(new Scene(new Label("Application started"),400, 400));
    ready.addListener(new ChangeListener<Boolean>(){
        public void changed(
            ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if (Boolean.TRUE.equals(t1)) {
                    Platform.runLater(new Runnable() {
                        public void run() {
                            stage.show();
                        }});}}});;}}
</code>```

And my preloader class:

```<code>public class LongAppInitPreloader extends Preloader {
ProgressBar bar;
Stage stage;
boolean noLoadingProgress = true;

private Scene createPreloaderScene() {
    bar = new ProgressBar(0);
    BorderPane p = new BorderPane();
    p.setCenter(bar);
    return new Scene(p, 300, 150);
}

public void start(Stage stage) throws Exception {
    this.stage = stage;
    stage.setScene(createPreloaderScene());
    stage.show();
}

@Override
public void handleProgressNotification(ProgressNotification pn) {
    if (pn.getProgress() != 1.0 || !noLoadingProgress) {
      bar.setProgress(pn.getProgress()/2);
      if (pn.getProgress() > 0) {
          noLoadingProgress = false;
      }
    }
}

@Override
public void handleStateChangeNotification(StateChangeNotification evt) {
    //ignore, hide after application signals it is ready
}

@Override
public void handleApplicationNotification(PreloaderNotification pn) {
    if (pn instanceof ProgressNotification) {
       double v = ((ProgressNotification) pn).getProgress();
       if (!noLoadingProgress) {
           v = 0.5 + v/2;
       }
       bar.setProgress(v);
    } else if (pn instanceof StateChangeNotification) {
        stage.hide();
    }
}
 }
</code>```

You can check this http://docs.oracle.com/javafx/2/deployment/preloaders.htm document too. This codes belong to example 9-11 and 9-12.

答:
You are missing Main method in LongInitApp class</p>

```<code>public static void main(String args[]) {
    launch(args);
}
</code>```

Title: JavaFX Preloader never called from main

Body:
My IDE is IntelliJ. I tried this document to learn preloader but for some reason preloader never gets called from my main class, or even its methods get called.

So here is my main class:

public class LongInitApp extends Application {
Stage stage;
BooleanProperty ready = new SimpleBooleanProperty(false);
private void longStart() {
    //simulate long init in background
    Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int max = 10;
            for (int i = 1; i <= max; i++) {
                Thread.sleep(200);
                notifyPreloader(new ProgressNotification(((double) i)/max));
            }
            ready.setValue(Boolean.TRUE);

            notifyPreloader(new StateChangeNotification(
                StateChangeNotification.Type.BEFORE_START));
           return null;
        }};
    new Thread(task).start();
}

 public static void main(String args[]) {
    launch(args);
  }

@Override
public void start(final Stage stage) throws Exception {
    longStart();
    stage.setScene(new Scene(new Label("Application started"),400, 400));
    ready.addListener(new ChangeListener<Boolean>(){
        public void changed(
            ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
                if (Boolean.TRUE.equals(t1)) {
                    Platform.runLater(new Runnable() {
                        public void run() {
                            stage.show();
                        }});}}});;}}

And my preloader class:

public class LongAppInitPreloader extends Preloader {
ProgressBar bar;
Stage stage;
boolean noLoadingProgress = true;

private Scene createPreloaderScene() {
    bar = new ProgressBar(0);
    BorderPane p = new BorderPane();
    p.setCenter(bar);
    return new Scene(p, 300, 150);
}

public void start(Stage stage) throws Exception {
    this.stage = stage;
    stage.setScene(createPreloaderScene());
    stage.show();
}

@Override
public void handleProgressNotification(ProgressNotification pn) {
    if (pn.getProgress() != 1.0 || !noLoadingProgress) {
      bar.setProgress(pn.getProgress()/2);
      if (pn.getProgress() > 0) {
          noLoadingProgress = false;
      }
    }
}

@Override
public void handleStateChangeNotification(StateChangeNotification evt) {
    //ignore, hide after application signals it is ready
}

@Override
public void handleApplicationNotification(PreloaderNotification pn) {
    if (pn instanceof ProgressNotification) {
       double v = ((ProgressNotification) pn).getProgress();
       if (!noLoadingProgress) {
           v = 0.5 + v/2;
       }
       bar.setProgress(v);
    } else if (pn instanceof StateChangeNotification) {
        stage.hide();
    }
}
 }

You can check this http://docs.oracle.com/javafx/2/deployment/preloaders.htm document too. This codes belong to example 9-11 and 9-12.

Body:
You are missing Main method in LongInitApp class

public static void main(String args[]) {
    launch(args);
}


问:
zsh attach to tmux by key binding
I am trying to make Alt-M in zsh attach to a tmux session.

Content of .zshrc:

```<code>tmux-open() {
  tmux attach
}
zle -N tmux-open
bindkey '^[m' tmux-open
</code>```

When I press Alt-M, instead of attaching to the tmux session, I get:

open terminal failed: not a terminal

Calling tmux-open from the zsh prompt attaches to the tmux session. What is the problem with the key binding?

答:
A possible alternative is to make a keybinding that just types the command tmux attach:

```<code>bindkey -s '^[m' 'tmux attach\n'
</code>```

That will work when the prompt is on an empty command line

Title: zsh attach to tmux by key binding

Body:
I am trying to make Alt-M in zsh attach to a tmux session.

Content of .zshrc:

tmux-open() {
  tmux attach
}
zle -N tmux-open
bindkey '^[m' tmux-open

When I press Alt-M, instead of attaching to the tmux session, I get:

open terminal failed: not a terminal

Calling tmux-open from the zsh prompt attaches to the tmux session. What is the problem with the key binding?

Body:
A possible alternative is to make a keybinding that just types the command tmux attach:

bindkey -s '^[m' 'tmux attach\n'

That will work when the prompt is on an empty command line


答:
There is max_execution_time limit in php.ini file, the file will execute 30seconds (default execution time in php), so you can add this code in top of your file.

```<code>ini_set('max_execution_time', 600);
</code>```

here 600 means seconds.

Title: How can I avoid connection timeout when the same php file runs multiple times

Body:
Please I need your help with a php script I am trying to build.
I have created this script to send multiple sms to some recipients.All data are stored into a database table (data > 1500 rows).I use select query with LIMIT 0, 1. When the message goes I delete the specific row and I include the file again to proceed to the next row. The problem is that at the time the rows = 300 I have a CONNECTION TIMEOUT ERROR. Please let me know how can I solve this or if there is another way to figure this out..

Body:
There is max_execution_time limit in php.ini file, the file will execute 30seconds (default execution time in php), so you can add this code in top of your file.

ini_set('max_execution_time', 600);

here 600 means seconds.


问:
Generate chained setters
I want to create a big Java object with 20 fileds, most of IDE's provide a generate function, wich allows me to generate getters and setters for all the fiels of my object.

The thing is, I am a big fan of method chaining and I am using it on all my objects, but I have to add return this at the end of each setters, which is not very handy.

Is it possible to generate setters with a special plugin form an IDE ?

答:
It's possible in IntelliJ IDEA:

call "Generate > Setter" menu

select template "Builder".

Select all fields you want to generate setter

click 'Ok'.

Here is generated result (for 1 field):

```<code>public MyClass setParam(String param) {
        this.param = param;
        return this;
    }
</code>```

It's also possible to create your own template there)

Title: Generate chained setters

Body:
It's possible in IntelliJ IDEA:

call "Generate > Setter" menu

select template "Builder".

Select all fields you want to generate setter

click 'Ok'.

Here is generated result (for 1 field):

public MyClass setParam(String param) {
        this.param = param;
        return this;
    }

It's also possible to create your own template there)


问:
Date and time of the applications last launch
In my application, you need to get the date and time of the all applications last  launch on the device. Can I somehow get this information by standard means?</p>

答:
You can do that with creating an Application class and set it from your app's manifest file. Step by step:

Create a class extends Application:

```<code>public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        // save date to sharedpref
        PreferenceManager.getDefaultSharedPreferences(this).
            edit().putLong("LAST_LAUNCH_DATE_MS", new Date().getTime()).apply();
    }
}
</code>```

Set it to your app from manifest file:

```<code><application
    android:name="com.my.project.MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    .....
    .....
</application>
</code>```

You can get last launch time as milliseconds from SharedPreferences now.

Body:
You can do that with creating an Application class and set it from your app's manifest file. Step by step:

Create a class extends Application:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        // save date to sharedpref
        PreferenceManager.getDefaultSharedPreferences(this).
            edit().putLong("LAST_LAUNCH_DATE_MS", new Date().getTime()).apply();
    }
}

Set it to your app from manifest file:

<application
    android:name="com.my.project.MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    .....
    .....
</application>

You can get last launch time as milliseconds from SharedPreferences now.


问:
How to get the value of a selected radio button
I want to get the selected value from a group of radio buttons.

Here's my HTML:

  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate

```
<p>Here's my JavaScript code:</p>
```var rates = document.getElementById('rates').value;
var rate_value;
if(rates == 'Fixed Rate'){
    rate_value = document.getElementById('r1').value;

}else if(rates == 'Variable Rate'){
    rate_value = document.getElementById('r2').value;

}else if(rates == 'Multi Rate'){
    rate_value = document.getElementById('r3').value;
}

document.getElementById('results').innerHTML = rate_value;
```

I keep getting undefined.

答:
```<code>var rates = document.getElementById('rates').value;
</code>```

cannot get values of a radio button like that instead use

```<code>rate_value = document.getElementById('r1').value;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get the selected value from a group of radio buttons.

Here's my HTML:

  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate

Here's my JavaScript code:

var rates = document.getElementById('rates').value;
var rate_value;
if(rates == 'Fixed Rate'){
    rate_value = document.getElementById('r1').value;

}else if(rates == 'Variable Rate'){
    rate_value = document.getElementById('r2').value;

}else if(rates == 'Multi Rate'){
    rate_value = document.getElementById('r3').value;
}

document.getElementById('results').innerHTML = rate_value;

I keep getting undefined.

Body:
var rates = document.getElementById('rates').value;

cannot get values of a radio button like that instead use

rate_value = document.getElementById('r1').value;


问:
in Cesium, dynamic rotating compass resets backwards to 0 when it passes 360
I have this simple code to animate a compass icon to reflect the current orientation of the camera in Cesium, whenever I pass through 360 degrees however, the compass spins left to reset at 0, rather than spinning through. Code is below:</p>

```<code>viewer.camera.changed.addEventListener(rotateCompass);
viewer.camera.moveEnd.addEventListener(rotateCompass);

function rotateCompass() {
    document.getElementById('compass').style.transform =
        `rotate(-${viewer.camera.heading}rad)`;
}
</code>```

答:
Found a solution, bound listener to viewer.clock.onTick instead of on the camera changes itself. compass now reflects camera heading quite nicely with just 1 listener and 1 function:

```<code>viewer.clock.onTick.addEventListener(rotateCompass);

function rotateCompass() {
    compass.style.transform = `rotate(${viewer.camera.heading}rad)`;
}
</code>```

Body:
I have this simple code to animate a compass icon to reflect the current orientation of the camera in Cesium, whenever I pass through 360 degrees however, the compass spins left to reset at 0, rather than spinning through. Code is below:

viewer.camera.changed.addEventListener(rotateCompass);
viewer.camera.moveEnd.addEventListener(rotateCompass);

function rotateCompass() {
    document.getElementById('compass').style.transform =
        `rotate(-${viewer.camera.heading}rad)`;
}

Body:
Found a solution, bound listener to viewer.clock.onTick instead of on the camera changes itself. compass now reflects camera heading quite nicely with just 1 listener and 1 function:

viewer.clock.onTick.addEventListener(rotateCompass);

function rotateCompass() {
    compass.style.transform = `rotate(${viewer.camera.heading}rad)`;
}


问:
When I Branch from Trunk I need to create a new Virtual Directory. Anyway around this?
the Trunk of my app points to

```<code><IISUrl>http:///localhost/MyApp/</IISUrl>
</code>```

Whenever I create a new branch, I end up having to edit MyApp.csproj to change the target URL to

```<code><IISUrl>http:///localhost/MyAppBranchName/</IISUrl>
</code>```

Is there any way that I don't need to do this? The reason is the number of branches are starting to add up and there's a lot of virtual directories in IIS. I suppose I could use the ASP.NET Dev server, but as this solution is already configured to use IIS, I'd prefer to keep using that.

答:
What I do is delete the Virtual Directory for trunk - it is a manual task and a bit of a pain but it gets the job done and I don't have to worry about breaking my colleagues environments after I merge back to trunk. VS will prompt you to create an IIS VD when you open the branch solution.

So essentially you have a small manual task and only one Virtual Directory at a time.

ContentLicense: CC BY-SA 2.5

Body:
the Trunk of my app points to

<IISUrl>http:///localhost/MyApp/</IISUrl>

Whenever I create a new branch, I end up having to edit MyApp.csproj to change the target URL to

<IISUrl>http:///localhost/MyAppBranchName/</IISUrl>

Is there any way that I don't need to do this? The reason is the number of branches are starting to add up and there's a lot of virtual directories in IIS. I suppose I could use the ASP.NET Dev server, but as this solution is already configured to use IIS, I'd prefer to keep using that.


问:
div Img background doesn't work in my CSS
So this is my CSS code:

```<code>#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;
</code>```

}

And it won't work at all. I placed the picture in the same map as my HTML file.

答:
What you can try is you can enclose your id details in a style tag and you can make id name to any tag like paragraph tag and after that all your code will be alright.

```<code><style>
 #plaatje{
    background-image: url('Plaatjes/slider_two_temp.jpg');
    width: 100%;
    height: 600px;
    position: absolute;
    top: 0px;
    left: 0px;
    }
</style>
    <p id="plaatje"></p>
</code>```

If you want to try this by

```<code> <div id="plaatje"></div>
</code>```

it will also work fine for div tag

Body:
So this is my CSS code:

#plaatje {
background-image: url('Plaatjes\slider_two_temp.jpg');
width: 100%;
height: 600px;
position: absolute;
top: 0px;
left: 0px;

}

And it won't work at all. I placed the picture in the same map as my HTML file.

Body:
What you can try is you can enclose your id details in a style tag and you can make id name to any tag like paragraph tag and after that all your code will be alright.

<style>
 #plaatje{
    background-image: url('Plaatjes/slider_two_temp.jpg');
    width: 100%;
    height: 600px;
    position: absolute;
    top: 0px;
    left: 0px;
    }
</style>
    <p id="plaatje"></p>

If you want to try this by

 <div id="plaatje"></div>

it will also work fine for div tag


问:
How to read file chunk by chunk from S3 using aws-java-sdk
I am trying to  read large file into chunks from S3  without cutting any line for parallel processing.

Let me explain by example:
There is file of size 1G on S3. I want to divide this file into chucks of 64 MB. It is easy I can do it like  :

```<code>S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));

InputStream stream = s3object.getObjectContent();

byte[] content = new byte[64*1024*1024];

while (stream.read(content)  != -1) {

//process content here

}
</code>```

but problem with chunk is it may have 100 complete line and one incomplete. but I can not process incomplete line and don't want to discard it.

Is any way to handle this situations ? means all chucks have no partial line.

答:
The aws-java-sdk already provides streaming functionality for your S3 objects. You have to call "getObject" and the result will be an InputStream.

1) AmazonS3Client.getObject(GetObjectRequest getObjectRequest) -> S3Object

2) S3Object.getObjectContent()

Note: The method is a simple getter and does not actually create a
  stream. If you retrieve an S3Object, you should close this input
  stream as soon as possible, because the object contents aren't
  buffered in memory and stream directly from Amazon S3. Further,
  failure to close this stream can cause the request pool to become
  blocked.

aws java docs

Body:
I am trying to  read large file into chunks from S3  without cutting any line for parallel processing.

Let me explain by example:
There is file of size 1G on S3. I want to divide this file into chucks of 64 MB. It is easy I can do it like  :

S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));

InputStream stream = s3object.getObjectContent();

byte[] content = new byte[64*1024*1024];

while (stream.read(content)  != -1) {

//process content here

}

but problem with chunk is it may have 100 complete line and one incomplete. but I can not process incomplete line and don't want to discard it.

Is any way to handle this situations ? means all chucks have no partial line.


问:
Get day of week from current date and specifying first day of week
I am migrating a legacy VB6 project into C#.

I want to obtain the equivalent in C# from expression below:

```<code>Weekday(Date, vbMonday)
</code>```

I know there is a function in C#:

```<code>int dayOfWeek = (int)DateTime.Today.DayOfWeek;
</code>```

but how to specify that the first day of the week  is Monday and then function DayOfWeek take it into account and return the correct value?

I need to obtain an int value.

答:
You can get the first day of the week by calling CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek, but I think you can do without that.

The Weekday function returns 1 for Monday, just like DayOfWeek. The only special case is Sunday, which .NET returns as 0, while VB returns 7.

Just do the math:

```<code>int dayOfWeek = DateTime.Today.DayOfWeek == DayOfWeek.Sunday
                 ? 7
                 : (int)DateTime.Today.DayOfWeek;
</code>```

Body:
I am migrating a legacy VB6 project into C#.

I want to obtain the equivalent in C# from expression below:

Weekday(Date, vbMonday)

I know there is a function in C#:

int dayOfWeek = (int)DateTime.Today.DayOfWeek;

but how to specify that the first day of the week  is Monday and then function DayOfWeek take it into account and return the correct value?

I need to obtain an int value.

Body:
You can get the first day of the week by calling CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek, but I think you can do without that.

The Weekday function returns 1 for Monday, just like DayOfWeek. The only special case is Sunday, which .NET returns as 0, while VB returns 7.

Just do the math:

int dayOfWeek = DateTime.Today.DayOfWeek == DayOfWeek.Sunday
                 ? 7
                 : (int)DateTime.Today.DayOfWeek;


问:
Blank page with error - TypeError: Object.assign is undefined (Angular)
I have created a myang project where I have used nodejs V8.0.0 and npm Version 5.0.3 on Ubuntu version 14.04 LTS.

I have installed Angular with the command npm install -g @angular/cli.

When I use ng serve, the application works property and i have checked it on a  browser with http://localhost:4200.

Every thing has been installed correctly, but I get the below error:

Type Error: Object.assign is undefined

I have attached the screen shots. Please check and help me display a hello message on browser.

Type error that I am getting on the console

When i use ng serve web pack with everything installed successfully -

Output showing a blank page

答:
I am very happy to say problem solved.

Open this file polyfills.ts available in src, you will find that these polyfills for IE11 are commented out:

```<code>    /** IE9, IE10 and IE11 requires all of the following polyfills. **/
    // import 'core-js/es6/symbol';
    // import 'core-js/es6/object';
    // import 'core-js/es6/function';
    // import 'core-js/es6/parse-int';
    // import 'core-js/es6/parse-float';
    // import 'core-js/es6/number';
    // import 'core-js/es6/math';
    // import 'core-js/es6/string';
    // import 'core-js/es6/date';
    // import 'core-js/es6/array';
    // import 'core-js/es6/regexp';
    // import 'core-js/es6/map';
    // import 'core-js/es6/set';
</code>```

Body:
I am very happy to say problem solved.

Open this file polyfills.ts available in src, you will find that these polyfills for IE11 are commented out:

    /** IE9, IE10 and IE11 requires all of the following polyfills. **/
    // import 'core-js/es6/symbol';
    // import 'core-js/es6/object';
    // import 'core-js/es6/function';
    // import 'core-js/es6/parse-int';
    // import 'core-js/es6/parse-float';
    // import 'core-js/es6/number';
    // import 'core-js/es6/math';
    // import 'core-js/es6/string';
    // import 'core-js/es6/date';
    // import 'core-js/es6/array';
    // import 'core-js/es6/regexp';
    // import 'core-js/es6/map';
    // import 'core-js/es6/set';


问:
Azure KeyVault iterate over all secrets in a vault
For the sake of simplicity let assume I want to build a dictionary from all the secrets in specific vault with the Secret Name and the Secret Value, using Azure REST API.

The problem I'm facing is that the Get Secrets API call returns SecretListResult which contains a list of SecretItem. the SecretItem has ID element, but not a Name, nor the Value. The GetSecret API needs the secret name and not the secret ID, and so far I cant find a way the translate an ID to name.

any suggestions would be highly appreciated

Thank you.

答:
// Get list of secrets

GET https://alice.vault.azure.net/secrets?api-version=2015-06-01

Response Body:
{
  "value": [
    {
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret1",
      "attributes": {
        "enabled": true,
        "created": 1496749576,
        "updated": 1496749576
      }
    },
    {
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret2",
      "attributes": {
        "enabled": true,
        "created": 1496749590,
        "updated": 1496749590
      }
    }
  ],
  "nextLink": null
}
```

<h3>// Get secret properties and value</h3>

<p>Parse <code>id</code>, look for last occurrence of <code>/</code> to get secret name. One call per item.</p>

<pre class="lang-json prettyprint-override"><code>GET https://alice.vault.azure.net/secrets/secret1/?api-version=2015-06-01

Response Body:
{
  "value": "5up3r1ee7s3cr3t",
  "contentType": "text",
  "id": "https://alice.vault.azure.net/secrets/secret1/6ac15a48877148e094276504d73e95a1",
  "attributes": {
    "enabled": true,
    "created": 1496749576,
    "updated": 1496749576
  }
}

GET https://alice.vault.azure.net/secrets/secret2/?api-version=2015-06-01

Response Body:
{
  "value": "@n0th3r5up3r1ee7s3cr3t",
  "contentType": "text",
  "id": "https://alice.vault.azure.net/secrets/secret2/2b34de363d6445ba83bb23bafaea6658",
  "attributes": {
    "enabled": true,
    "created": 1496749590,
    "updated": 1496749590
  }
}
</code>```

Source: I just looked at what Azure PowerShell calls on the wire with -Debug, e.g.:

Get-AzureKeyVaultSecret -VaultName Alice -Debug
Get-AzureKeyVaultSecret -VaultName Alice -Name secret1 -Debug
```

Body:
// Get list of secrets

GET https://alice.vault.azure.net/secrets?api-version=2015-06-01

Response Body:
{
  "value": [
    {
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret1",
      "attributes": {
        "enabled": true,
        "created": 1496749576,
        "updated": 1496749576
      }
    },
    {
      "contentType": "text",
      "id": "https://alice.vault.azure.net/secrets/secret2",
      "attributes": {
        "enabled": true,
        "created": 1496749590,
        "updated": 1496749590
      }
    }
  ],
  "nextLink": null
}

// Get secret properties and value

Parse id, look for last occurrence of / to get secret name. One call per item.

GET https://alice.vault.azure.net/secrets/secret1/?api-version=2015-06-01

Response Body:
{
  "value": "5up3r1ee7s3cr3t",
  "contentType": "text",
  "id": "https://alice.vault.azure.net/secrets/secret1/6ac15a48877148e094276504d73e95a1",
  "attributes": {
    "enabled": true,
    "created": 1496749576,
    "updated": 1496749576
  }
}

GET https://alice.vault.azure.net/secrets/secret2/?api-version=2015-06-01

Response Body:
{
  "value": "@n0th3r5up3r1ee7s3cr3t",
  "contentType": "text",
  "id": "https://alice.vault.azure.net/secrets/secret2/2b34de363d6445ba83bb23bafaea6658",
  "attributes": {
    "enabled": true,
    "created": 1496749590,
    "updated": 1496749590
  }
}

Source: I just looked at what Azure PowerShell calls on the wire with -Debug, e.g.:

Get-AzureKeyVaultSecret -VaultName Alice -Debug
Get-AzureKeyVaultSecret -VaultName Alice -Name secret1 -Debug


问:
java parsing a string like "0:ADD(10)"
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

答:
You can use a regular expression like this:

```<code>\\((\\d+)\\)
</code>```

to extract the number from between the brackets. More information on java regex can be found here and here
Note: Since java adds, by default, the ^ and $ at the beginning and end respectively, we have to add the .* before and after the pattern we want to match.

```<code>String[] str  = new String[]{"0:ADD(10)","1:ADD(20)"};
        Pattern pattern = Pattern.compile("^.*\\((\\d+)\\).*$");
        for (int i = 0; i < str.length; i++)
        {
            Matcher m = pattern.matcher(str[i]);
            System.out.println(m.matches());
            System.out.println(m.group(1));
        }
</code>```

Prints:

true

10

true

20

Title: java parsing a string like "0:ADD(10)"

Body:
You can use a regular expression like this:

\\((\\d+)\\)

to extract the number from between the brackets. More information on java regex can be found here and here
Note: Since java adds, by default, the ^ and $ at the beginning and end respectively, we have to add the .* before and after the pattern we want to match.

String[] str  = new String[]{"0:ADD(10)","1:ADD(20)"};
        Pattern pattern = Pattern.compile("^.*\\((\\d+)\\).*$");
        for (int i = 0; i < str.length; i++)
        {
            Matcher m = pattern.matcher(str[i]);
            System.out.println(m.matches());
            System.out.println(m.group(1));
        }

Prints:

true

10

true

20


问:
sed -e unknown option to `s' - Not a delimiter issue
I'm using Cmder on Windows and trying to execute the following statement:

```<code>echo "c:\Sources\" + (echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")
</code>```

Whenever I issue that command I get the annoying error

```<code>sed: -e expression #1, char 13: unknown option to `s'
</code>```

But when I run the sed command on its own:

```<code>(echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")
</code>```

It magically works. Could anyone explain what I'm doing wrong?

Editor's note: This question was originally mis-tagged bash, whereas the symptom described implies cmd.

答:
The error message in the question is due to windows cmd which splits the command with the | and adds closing parenthese ) to sed command.

cmd equivalent for "command substitution" is for /f followed by command between single quotes, pipe must be escaped with ^

```<code>for /f %x in ('echo "Modules/ASR/branches/1.9" ^| sed -e "s|Modules/||" ') do @echo "c:\Sources\"%~x
</code>```

Or when used in script the percent must be doubled

```<code>for /f %%x in ('echo "Modules/ASR/branches/1.9" ^| sed -e "s|Modules/||" ') do @echo "c:\Sources\"%%~x
</code>```

Otherwise expansion allows to replace pattern %var:pat=repl%

```<code>set mypath=Modules/ASR/branches/1.9
echo "c:\Sources\"%mypath:Modules/=%
</code>```

in bash equivalent

```<code>echo 'c:\Sources\'"$(echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")"
</code>```

also to avoid to launch a new process this can be done with variable expansion # to remove shortest prefix.

```<code>mypath="Modules/ASR/branches/1.9"
echo 'c:\Sources\'"${mypath//Modules\/}"
</code>```

Body:
I'm using Cmder on Windows and trying to execute the following statement:

echo "c:\Sources\" + (echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")

Whenever I issue that command I get the annoying error

sed: -e expression #1, char 13: unknown option to `s'

But when I run the sed command on its own:

(echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")

It magically works. Could anyone explain what I'm doing wrong?

Editor's note: This question was originally mis-tagged bash, whereas the symptom described implies cmd.

Body:
The error message in the question is due to windows cmd which splits the command with the | and adds closing parenthese ) to sed command.

cmd equivalent for "command substitution" is for /f followed by command between single quotes, pipe must be escaped with ^

for /f %x in ('echo "Modules/ASR/branches/1.9" ^| sed -e "s|Modules/||" ') do @echo "c:\Sources\"%~x

Or when used in script the percent must be doubled

for /f %%x in ('echo "Modules/ASR/branches/1.9" ^| sed -e "s|Modules/||" ') do @echo "c:\Sources\"%%~x

Otherwise expansion allows to replace pattern %var:pat=repl%

set mypath=Modules/ASR/branches/1.9
echo "c:\Sources\"%mypath:Modules/=%

in bash equivalent

echo 'c:\Sources\'"$(echo "Modules/ASR/branches/1.9" | sed -e "s|Modules/||")"

also to avoid to launch a new process this can be done with variable expansion # to remove shortest prefix.

mypath="Modules/ASR/branches/1.9"
echo 'c:\Sources\'"${mypath//Modules\/}"


问:
Text from csv is cached on reload
I have created a html page of a list of info that's read from a csv file. The webpage is for internal use in my workplace and I can live with a few possible unhandled compatibility issues.
I'm using Chrome to get the page to work and I might address the IE/Edge compatibility issues late.

My problem is that when I edit the data in the the dynamically created table and the new data is saved and the page is reloaded (using php), the browser shows the date from before the edit.

How can I force the browser to reload with the updated file?

I've tried all the <meta ***> solutions I've been able to find and, as you can see in the php file, I've tried the php header solution. The only thing I've found to work is checking the "Disable cache" in Chrome's developer tool and this solution is not optimal with non tech savvy users.

The html file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">
    <title>Some title</title>

    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #dddddd;
        }
    </style>

    <link rel="stylesheet" type="text/css" href="cssData.css">
</head>

<body onload='getData("")'>
    <div class='wrap'>
        <h1 id='createdDate' align='center'>Header</h1>
        <br>
        <div>
            <form action="phpFunc.php" id="some" name="someName" method="post" align='center'>
                <input type='button' id='edit' onclick='editData()' value='btn1' style='display:inline;' />
                <input type='button' id='add' onclick='addData()' value='btn2' style='display:none;' />
                <input type='button' id='save' onclick='saveData()' value='btn3' style='display:none;'/>

                <input type="text" id="tempText" class="someClass" value="Test" name="fileWrite" style='display:none;'/>
                <input type="submit" id='saveBtn' value="" class="submitClass" style='display:none;'/>

                <input type='button' id='cancel' onclick='cancelEdit()' value='btn4' style='display:none;'/>
            </form>
        </div>
        <table id='dataTable'></table>
        <br><br><br><br>
    </div>
    <div class='footer'>
        <i>Made by some guy</i>
    </div>
    <script src="functions.js"></script>
</body>
</code>```

The js function file:

```<code>var list = "", colNames = ["Kursus", "Image", "RAM", "SSD"];
var noCol = 4;

function getData(addon) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            visualFormating(this.responseText, addon);
        }else if (this.status == 404){
            visualFormating("","");
        }
    };
    xhttp.open("GET", "Data.csv", true);

    xhttp.send();
} else {
    alert("Functionen er ikke understøttet i denne browser.");
}
};

function visualFormating(input, addon){
if(input.length > 0 || addon.length > 0){
if(list.length < 1){
    input = input.replace(/(\")+/g,'')
    var array = input.split('\n');
    var text = "";
    var temp = array[0].split(';');

    for (var i = 0; i < array.length; i++){
        var temp = array[i].split(';');
        if(temp.length == 4){
        text += "<tr>";

        if(i != 0){
            for (var j = 0; j < temp.length; j++){
                text += "<td contenteditable='false'>" + temp[j];
                text += "</td>";
            }
            text += "<td class='checkboxes' style='display:none'><input type='checkbox' id='check"+i+"'>"
        }else{
            for (var j = 0; j < temp.length; j++){
                text += "<th onclick='sortTable("+j+")' style='cursor: pointer;'>" + temp[j];
                text += "</th>";
            }
            text += "<th id='delete' class='checkboxes' style='display:none'>Slet</th>";
        }

        text += "</tr>";}
    }
}else{
    text = list
}
}else{
    text = "<tr>";
    for (var i = 0; i < colNames.length; i++)
    {
        text += "<th onclick='sortTable("+i+")' style='cursor: pointer;'>" + colNames[i] + "</th>";
    }
    text += "<th id='delete' class='checkboxes' style='display:none'>Slet</th></tr>";
}

list = text + addon;
text = "<table>" + list + "</table>";
document.getElementById('dataTable').innerHTML = text;
};

function changeEditable(editable){
if(editable==true){
    var editable_elements = document.querySelectorAll("[contenteditable=false]");
    document.getElementById('edit').style.display = "none";
    document.getElementById('add').style.display = "inline";
    document.getElementById('save').style.display = "inline";
    document.getElementById('cancel').style.display = "inline";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "block";
    }
}else{
    var editable_elements = document.querySelectorAll("[contenteditable=true]");
    document.getElementById('edit').style.display = "inline";
    document.getElementById('add').style.display = "none";
    document.getElementById('save').style.display = "none";
    document.getElementById('cancel').style.display = "none";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "none";
    }
}

for(var i=0; i<editable_elements.length; i++){
    editable_elements[i].setAttribute("contenteditable", editable);
}
}

function saveData(){
changeEditable(false);
checkDelete();
writeData();
clearEdit();
getData("");
}

function checkDelete(){
var table = document.getElementById("dataTable");
var newList = "";

for (var i = table.rows.length - 1; i > 0; i--){
    if (document.getElementById("check"+i).checked) {
        table.deleteRow(i);
    }
}
}

function writeData(){
var rows = document.getElementById("dataTable").rows;
var text = "";

for (var r = 0; r < rows.length; r++){
    var tempText = "";
    for(var c = 0; c < noCol; c++){
        tempText += '"' + rows[r].cells[c].innerHTML + '"';
        if(c+2 != rows[r].cells.length) tempText += ";";
        else tempText += "\n";
    }
    //var tempText = '"' + rows[r].cells[0].innerHTML + '";"' + rows[r].cells[1].innerHTML + '";"' + rows[r].cells[2].innerHTML + '";"' + rows[r].cells[3].innerHTML + '"' + "\n";
    if (!checkEmpty(tempText))text += tempText;
}

document.getElementById('tempText').value = encodeURIComponent(text);
document.getElementById('saveBtn').click();
}

function addData() {
var text = "<tr>";

for (var i = 0; i < noCol; i++){
    text += "<td contenteditable='true'></td>"
}

text += "<td class='checkboxes' style='display:block'><input type='checkbox' id='check" + document.getElementById("dataTable").rows.length + "'></tr>";

updateList(text);
}

function updateList(input){
var rows = document.getElementById("dataTable").rows;
var text = "";
for (var i = 0; i < rows.length; i++){
    text += '<tr>' + rows[i].innerHTML + '</tr>';
}

list = text;

visualFormating("", input);
}

function editData(){
changeEditable(true);

}

function cancelEdit(){
clearEdit();
changeEditable(false);
getData("");
}

function clearEdit(){
list = "";
}

function checkEmpty(input){
input = input.replace(/"/g, '');
input = input.replace(/;/g, '');
input = input.replace(/\n/g, '');

if(input.length < 1) return true;
else return false;
}

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("dataTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
  //start by saying there should be no switching:
  shouldSwitch = false;
  /*Get the two elements you want to compare,
  one from current row and one from the next:*/
  x = rows[i].getElementsByTagName("TD")[n];
  y = rows[i + 1].getElementsByTagName("TD")[n];
  /*check if the two rows should switch place,
  based on the direction, asc or desc:*/
  if (dir == "asc") {
    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  /*If a switch has been marked, make the switch
  and mark that a switch has been done:*/
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
  //Each time a switch is done, increase this count by 1:
  switchcount ++;
} else {
  /*If no switching has been done AND the direction is "asc",
  set the direction to "desc" and run the while loop again.*/
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}
}
}
</code>```

The php file:

```<code><?php
$file = 'Data.csv';
$fileWrite = '';
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
    $fileWrite = urldecode($_POST['fileWrite']);
}
file_put_contents($file, $fileWrite);
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
header( 'Location: index.html' ) ;
?>
</code>```

The csv is formated as follows:

```<code>"column 1";"column 2";"column 3";"column 4"
"Data 1";"Data 2";"Data 3";"Data 4"
</code>```

If some info is missing please let me know. The whole 4 space to make code block is making a mess for me.

答: Just add a random number, like : "Data.csv?" + Math.random() to your file name. It will force the browser to download a fresh copy each time.

Title: Text from csv is cached on reload

Body:
I have created a html page of a list of info that's read from a csv file. The webpage is for internal use in my workplace and I can live with a few possible unhandled compatibility issues.
I'm using Chrome to get the page to work and I might address the IE/Edge compatibility issues late.

My problem is that when I edit the data in the the dynamically created table and the new data is saved and the page is reloaded (using php), the browser shows the date from before the edit.

How can I force the browser to reload with the updated file?

I've tried all the <meta ***> solutions I've been able to find and, as you can see in the php file, I've tried the php header solution. The only thing I've found to work is checking the "Disable cache" in Chrome's developer tool and this solution is not optimal with non tech savvy users.

The html file:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">
    <title>Some title</title>

    <link rel="stylesheet" type="text/css" href="cssData.css">

Header

            <form action="phpFunc.php" id="some" name="someName" method="post" align='center'>
                <input type='button' id='edit' onclick='editData()' value='btn1' style='display:inline;' />
                <input type='button' id='add' onclick='addData()' value='btn2' style='display:none;' />
                <input type='button' id='save' onclick='saveData()' value='btn3' style='display:none;'/>

                <input type="text" id="tempText" class="someClass" value="Test" name="fileWrite" style='display:none;'/>
                <input type="submit" id='saveBtn' value="" class="submitClass" style='display:none;'/>

                <input type='button' id='cancel' onclick='cancelEdit()' value='btn4' style='display:none;'/>
            </form>

        Made by some guy

The js function file:

var list = "", colNames = ["Kursus", "Image", "RAM", "SSD"];
var noCol = 4;

function getData(addon) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            visualFormating(this.responseText, addon);
        }else if (this.status == 404){
            visualFormating("","");
        }
    };
    xhttp.open("GET", "Data.csv", true);

    xhttp.send();
} else {
    alert("Functionen er ikke understøttet i denne browser.");
}
};

function visualFormating(input, addon){
if(input.length > 0 || addon.length > 0){
if(list.length < 1){
    input = input.replace(/(\")+/g,'')
    var array = input.split('\n');
    var text = "";
    var temp = array[0].split(';');

    for (var i = 0; i < array.length; i++){
        var temp = array[i].split(';');
        if(temp.length == 4){
        text += "
";

        if(i != 0){
            for (var j = 0; j < temp.length; j++){
                text += "" + temp[j];
                text += "	";
            }
            text += "<input type='checkbox' id='check"+i+"'>"
        }else{
            for (var j = 0; j < temp.length; j++){
                text += "" + temp[j];
                text += "	";
            }
            text += "Slet	";
        }

        text += "
";}
    }
}else{
    text = list
}
}else{
    text = "
";
    for (var i = 0; i < colNames.length; i++)
    {
        text += "" + colNames[i] + "	";
    }
    text += "Slet
";
}

list = text + addon;
text = "
" + list + "
";
document.getElementById('dataTable').innerHTML = text;
};

function changeEditable(editable){
if(editable==true){
    var editable_elements = document.querySelectorAll("[contenteditable=false]");
    document.getElementById('edit').style.display = "none";
    document.getElementById('add').style.display = "inline";
    document.getElementById('save').style.display = "inline";
    document.getElementById('cancel').style.display = "inline";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "block";
    }
}else{
    var editable_elements = document.querySelectorAll("[contenteditable=true]");
    document.getElementById('edit').style.display = "inline";
    document.getElementById('add').style.display = "none";
    document.getElementById('save').style.display = "none";
    document.getElementById('cancel').style.display = "none";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "none";
    }
}

for(var i=0; i<editable_elements.length; i++){
    editable_elements[i].setAttribute("contenteditable", editable);
}
}

function saveData(){
changeEditable(false);
checkDelete();
writeData();
clearEdit();
getData("");
}

function checkDelete(){
var table = document.getElementById("dataTable");
var newList = "";

for (var i = table.rows.length - 1; i > 0; i--){
    if (document.getElementById("check"+i).checked) {
        table.deleteRow(i);
    }
}
}

function writeData(){
var rows = document.getElementById("dataTable").rows;
var text = "";

for (var r = 0; r < rows.length; r++){
    var tempText = "";
    for(var c = 0; c < noCol; c++){
        tempText += '"' + rows[r].cells[c].innerHTML + '"';
        if(c+2 != rows[r].cells.length) tempText += ";";
        else tempText += "\n";
    }
    //var tempText = '"' + rows[r].cells[0].innerHTML + '";"' + rows[r].cells[1].innerHTML + '";"' + rows[r].cells[2].innerHTML + '";"' + rows[r].cells[3].innerHTML + '"' + "\n";
    if (!checkEmpty(tempText))text += tempText;
}

document.getElementById('tempText').value = encodeURIComponent(text);
document.getElementById('saveBtn').click();
}

function addData() {
var text = "
";

for (var i = 0; i < noCol; i++){
    text += "	"
}

text += "<input type='checkbox' id='check" + document.getElementById("dataTable").rows.length + "'>
";

updateList(text);
}

function updateList(input){
var rows = document.getElementById("dataTable").rows;
var text = "";
for (var i = 0; i < rows.length; i++){
    text += '
' + rows[i].innerHTML + '
';
}

list = text;

visualFormating("", input);
}

function editData(){
changeEditable(true);

}

function cancelEdit(){
clearEdit();
changeEditable(false);
getData("");
}

function clearEdit(){
list = "";
}

function checkEmpty(input){
input = input.replace(/"/g, '');
input = input.replace(/;/g, '');
input = input.replace(/\n/g, '');

if(input.length < 1) return true;
else return false;
}

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("dataTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
  //start by saying there should be no switching:
  shouldSwitch = false;
  /*Get the two elements you want to compare,
  one from current row and one from the next:*/
  x = rows[i].getElementsByTagName("TD")[n];
  y = rows[i + 1].getElementsByTagName("TD")[n];
  /*check if the two rows should switch place,
  based on the direction, asc or desc:*/
  if (dir == "asc") {
    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  /*If a switch has been marked, make the switch
  and mark that a switch has been done:*/
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
  //Each time a switch is done, increase this count by 1:
  switchcount ++;
} else {
  /*If no switching has been done AND the direction is "asc",
  set the direction to "desc" and run the while loop again.*/
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}
}
}

The php file:

<?php
$file = 'Data.csv';
$fileWrite = '';
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
    $fileWrite = urldecode($_POST['fileWrite']);
}
file_put_contents($file, $fileWrite);
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
header( 'Location: index.html' ) ;
?>

The csv is formated as follows:

"column 1";"column 2";"column 3";"column 4"
"Data 1";"Data 2";"Data 3";"Data 4"

If some info is missing please let me know. The whole 4 space to make code block is making a mess for me.


问:
File output manipulation - ideally in one line
Apologies in advance this is my first post, hope you can understand it etc.

Original File

```<code>cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625
</code>```

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

or

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

```<code>sed 's/Global//g'
tr -d '\n'
</code>```

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

```<code>S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef
</code>```

答:
try:

```<code>awk '/^PROC/{sub(/[[:space:]]+Global/,"");val=$0;getline;sub(/^[[:space:]]+/,"");printf("%s\t%s\n",val,$0)}'   Input_file
</code>```

Looking for a line which starts with string PROC, if this is the case then substitute space till string Global with NULL, storing current line's value into val. Then jumping into next line by using getline. Now substituting the initial space from line and then printing the val and current line's value with TAB in between them.

EDIT1: changing the code as per OP's request now.

```<code>awk '!/^[[:space:]]/{sub(/[[:space:]]+Global/,"");val=$0;getline;sub(/^[[:space:]]+/,"");printf("%s\t%s\n",val,$0)}'   Input_file
</code>```

Body:
Apologies in advance this is my first post, hope you can understand it etc.

Original File

cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

or

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

sed 's/Global//g'
tr -d '\n'

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef

Body:
try:

awk '/^PROC/{sub(/[[:space:]]+Global/,"");val=$0;getline;sub(/^[[:space:]]+/,"");printf("%s\t%s\n",val,$0)}'   Input_file

Looking for a line which starts with string PROC, if this is the case then substitute space till string Global with NULL, storing current line's value into val. Then jumping into next line by using getline. Now substituting the initial space from line and then printing the val and current line's value with TAB in between them.

EDIT1: changing the code as per OP's request now.

awk '!/^[[:space:]]/{sub(/[[:space:]]+Global/,"");val=$0;getline;sub(/^[[:space:]]+/,"");printf("%s\t%s\n",val,$0)}'   Input_file


答:
```<code>DateTime dateValue = new DateTime(2008, 6, 11);

Console.WriteLine((int) dateValue.DayOfWeek);
</code>```

<p>// The example displays the following output:
//       3 </p>

```<code>Console.WriteLine(dateValue.ToString("dddd"));
</code>```

<p>// The example displays the following output:
 //       Wed</p>

```<code>Console.WriteLine(dateValue.ToString("dddd"));
</code>```

<p>// The example displays the following output:
//       Wednesday </p>

Title: Get day of week from current date and specifying first day of week

Body:
DateTime dateValue = new DateTime(2008, 6, 11);

Console.WriteLine((int) dateValue.DayOfWeek);

// The example displays the following output:
//       3

Console.WriteLine(dateValue.ToString("dddd"));

// The example displays the following output:
 //       Wed

Console.WriteLine(dateValue.ToString("dddd"));

// The example displays the following output:
//       Wednesday


问:
C: Separate HEX String into Char Aarray with RegEx
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

```<code>const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};
</code>```

At the moment, I use regex in Notepad++, and works well.
This is the regex:

```<code>find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')
</code>```

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

答:
Your question is a bit unclear, but assuming you just want to fill a char array with binary data from a hex string at runtime, something like this will do it:

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

const char *buf = "FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3";

static unsigned char hexNibble(const char *str)
{
    unsigned char hex = *str;
    if (hex >= 'a' && hex <='f')
    {
        hex -= ('a' - 10);
    }
    else if (hex >= 'A' && hex <= 'F')
    {
        hex -= ('A' - 10);
    }
    else if (hex >= '0' && hex <= '9')
    {
        hex -= '0';
    }
    else
    {
        hex = 0;
    }
    return hex;
}

static size_t createCharArrayFromHexString(char *result[], const char *str)
{
    size_t len = strlen(str);
    if (!len) return 0;
    size_t bytes = len / 2;
    int mostSignificantNibble = len % 2;
    size_t size = bytes + mostSignificantNibble;
    *result = malloc(size);
    char *out = *result;
    const char *in = str;
    if (mostSignificantNibble)
    {
        *out++ = hexNibble(in++);
    }
    while (bytes)
    {
        *out = hexNibble(in++);
        *out <<= 4;
        *out++ |= hexNibble(in++);
        --bytes;
    }
    return size;
}

int main(void) {
    int value = 0;
    char *converted;

    size_t convertedSize = createCharArrayFromHexString(&converted, buf);

    for (int i = 0; i < convertedSize; ++i)
    {
        printf( "0x%02hhx\n", converted[i]);
    }

    free(converted);
}
</code>```

Inside the main loop of createCharArrayFromHexString(), you could as well use sscanf() for converting as is already in the comments to your question.

You can greatly simplify this code if you can guarantee there's always an even number of characters in your hex input. See the code running here

Body:
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};

At the moment, I use regex in Notepad++, and works well.
This is the regex:

find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

Body:
Your question is a bit unclear, but assuming you just want to fill a char array with binary data from a hex string at runtime, something like this will do it:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *buf = "FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3";

static unsigned char hexNibble(const char *str)
{
    unsigned char hex = *str;
    if (hex >= 'a' && hex <='f')
    {
        hex -= ('a' - 10);
    }
    else if (hex >= 'A' && hex <= 'F')
    {
        hex -= ('A' - 10);
    }
    else if (hex >= '0' && hex <= '9')
    {
        hex -= '0';
    }
    else
    {
        hex = 0;
    }
    return hex;
}

static size_t createCharArrayFromHexString(char *result[], const char *str)
{
    size_t len = strlen(str);
    if (!len) return 0;
    size_t bytes = len / 2;
    int mostSignificantNibble = len % 2;
    size_t size = bytes + mostSignificantNibble;
    *result = malloc(size);
    char *out = *result;
    const char *in = str;
    if (mostSignificantNibble)
    {
        *out++ = hexNibble(in++);
    }
    while (bytes)
    {
        *out = hexNibble(in++);
        *out <<= 4;
        *out++ |= hexNibble(in++);
        --bytes;
    }
    return size;
}

int main(void) {
    int value = 0;
    char *converted;

    size_t convertedSize = createCharArrayFromHexString(&converted, buf);

    for (int i = 0; i < convertedSize; ++i)
    {
        printf( "0x%02hhx\n", converted[i]);
    }

    free(converted);
}

Inside the main loop of createCharArrayFromHexString(), you could as well use sscanf() for converting as is already in the comments to your question.

You can greatly simplify this code if you can guarantee there's always an even number of characters in your hex input. See the code running here


问:
How to handle timezone difference for data in server especially for IOT platform
I am looking for solution, how to deal with the data which has specific time related data.

Project Architecture :
Backend is RESTful services build in Java.

Frontend is:
1. Angular JS (for web only)
2. Native Mobile App (Android, iPhone).

For eg. one device is in UK (i.e. UTC+1:00) time zone another device is
  in HKT (Hong Kong  i.e. UTC+8:00) timezone.

My server is in Germany (i.e. UTC +2:30) timezone.

What I should keep at server?

How to show current time at each device (web browser as well as mobile devices), and if I am serving web pages, which can be accessible from anywhere, which timezone value I should keep?

Current solution:
Currently I am keeping whenever data is arrived at server calculate the UTC epoch time and store it, send the time as it is via REST and then at client side (web browser or Android device ) I am converting it to local Timezone.

Is this approach correct?

答:
Yes, your approach seems fine and correct.

For your implementation: if you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport is org.threeten.bp), but the classes and methods names are the same.

To get the UTC time, you can use the Instant class. It's the best choice because it's always in UTC, and can be easily converted to and from another timezones:

```<code>// get current UTC time - Instant is always in UTC
Instant instant = Instant.now();

// you can use the string representation
System.out.println(instant.toString());// 2017-06-06T11:57:21.665Z
// or the timestamp (epoch millis - milliseconds from 1970-01-01T00:00:00Z)
System.out.println(instant.toEpochMilli());// 1496750241665

// convert to another timezone (always use valid IDs)
ZonedDateTime z = instant.atZone(ZoneId.of("America/Sao_Paulo"));
System.out.println(z);// 2017-06-06T08:57:21.665-03:00[America/Sao_Paulo]

// in another timezone
z = instant.atZone(ZoneId.of("Europe/Berlin"));
System.out.println(z);// 2017-06-06T13:57:21.665+02:00[Europe/Berlin]

// convert back to UTC Instant
System.out.println(z.toInstant()); // 2017-06-06T11:57:21.665Z
</code>```

The API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin). Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. You can use ZoneId.getAvailableZoneIds() to get a full list of all timezones names.

You can also use ZoneId.systemDefault() to get the system's default timezone. In this case, if the code runs on a server, it'll use the server's machine timezone. And if it runs in a device, it'll use whatever is configured in the device.

Body:
Yes, your approach seems fine and correct.

For your implementation: if you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport is org.threeten.bp), but the classes and methods names are the same.

To get the UTC time, you can use the Instant class. It's the best choice because it's always in UTC, and can be easily converted to and from another timezones:

// get current UTC time - Instant is always in UTC
Instant instant = Instant.now();

// you can use the string representation
System.out.println(instant.toString());// 2017-06-06T11:57:21.665Z
// or the timestamp (epoch millis - milliseconds from 1970-01-01T00:00:00Z)
System.out.println(instant.toEpochMilli());// 1496750241665

// convert to another timezone (always use valid IDs)
ZonedDateTime z = instant.atZone(ZoneId.of("America/Sao_Paulo"));
System.out.println(z);// 2017-06-06T08:57:21.665-03:00[America/Sao_Paulo]

// in another timezone
z = instant.atZone(ZoneId.of("Europe/Berlin"));
System.out.println(z);// 2017-06-06T13:57:21.665+02:00[Europe/Berlin]

// convert back to UTC Instant
System.out.println(z.toInstant()); // 2017-06-06T11:57:21.665Z

The API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin). Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. You can use ZoneId.getAvailableZoneIds() to get a full list of all timezones names.

You can also use ZoneId.systemDefault() to get the system's default timezone. In this case, if the code runs on a server, it'll use the server's machine timezone. And if it runs in a device, it'll use whatever is configured in the device.


问:
Align the form to the center in Bootstrap 4
I am trying to align the form to the center and keep it responsive. I have tried several ways but no success. I am trying to center all the text and the form. I am using Bootstrap v4. I am not sure if that helps.

HTML:

```<code><section id="cover">
     <div id="cover-caption">
         <div id="container">
             <div class="col-sm-10 col-sm offset-1">
                 <h1 class="display-3">Welcome to Bootstrap 4</h1>
                 <div class="info-form">
                 <form action="" class="form-inline">
                    <div class="form-group">
                        <label class="sr-only">Name</label>
                        <input type="text" class="form-control" placeholder="Jane Doe">
                    </div>
                    <div class="form-group">
                        <label class="sr-only">Email</label>
                        <input type="text" class="form-control" placeholder="jane.doe@example.com">
                    </div>
                    <button type="submit" class="btn btn-success ">okay, go!</button>
                </form>
                </div>
                <br>

                <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">↓</a>
             </div>
         </div>
     </div>
 </section>
</code>```

CSS:

```<code>html,
body{
 height: 100%;
}

#cover {
  background: #222 url('../img/stars.jpg') center center no-repeat;
  background-size: cover;
  color: white;
  height: 100%;
  text-align: center;
  display: flex;
  align-items: center;
</code>```

}

```<code>#cover-caption {
  width: 100%;
</code>```

}

答:
You need to use the various Bootstrap 4 centering methods...

Use text-center for inline elements.

Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

```<code><section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="jane.doe@example.com">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">↓</a>
                </div>
            </div>
        </div>
    </div>
</section>
</code>```

Body:
I am trying to align the form to the center and keep it responsive. I have tried several ways but no success. I am trying to center all the text and the form. I am using Bootstrap v4. I am not sure if that helps.

HTML:

Welcome to Bootstrap 4

                 <form action="" class="form-inline">

                        Name
                        <input type="text" class="form-control" placeholder="Jane Doe">

                        Email
                        <input type="text" class="form-control" placeholder="jane.doe@example.com">

                    <button type="submit" class="btn btn-success ">okay, go!</button>
                </form>

                ↓

CSS:

html,
body{
 height: 100%;
}

#cover {
  background: #222 url('../img/stars.jpg') center center no-repeat;
  background-size: cover;
  color: white;
  height: 100%;
  text-align: center;
  display: flex;
  align-items: center;

}

#cover-caption {
  width: 100%;

}

Body:
You need to use the various Bootstrap 4 centering methods...

Use text-center for inline elements.

Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="jane.doe@example.com">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">↓</a>
                </div>
            </div>
        </div>
    </div>
</section>


问:
Reactjs, typescript unable to set initial state inside component
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

```<code>export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (
        <section>
         <section>
             <h3>profile 1</h3>
             <div>baz</div>
         </section>
            <section>
                <h3>profile 2</h3>
                <div>shaz</div>
            </section>
        </section>
        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)
</code>```

Edit

So I managed to solve the issue with everyones help:

```<code>interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}
</code>```

答:
State is an Object.

Write it like this to define the data in state:

```<code>this.state = {
   data: [
       {name: 'baz'},
       {name: 'shaz'}
   ]
}
</code>```

Then access the state values by this.state.data.

Update:

Data is an array so you need to use map to print all the values, if you want to print specific value then access that by using the index of that item:

```<code>this.state.data[0].name   --->   baz

this.state.data[1].name   --->   shaz
</code>```

By using map:

```<code>this.state.data.map(el => {
   console.log('name', el.name);
})
</code>```

Body:
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (

profile 1

baz

profile 2

shaz

        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)

Edit

So I managed to solve the issue with everyones help:

interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (

profile 1

baz

profile 2

{this.state.name}

        )

    }
}

Body:
State is an Object.

Write it like this to define the data in state:

this.state = {
   data: [
       {name: 'baz'},
       {name: 'shaz'}
   ]
}

Then access the state values by this.state.data.

Update:

Data is an array so you need to use map to print all the values, if you want to print specific value then access that by using the index of that item:

this.state.data[0].name   --->   baz

this.state.data[1].name   --->   shaz

By using map:

this.state.data.map(el => {
   console.log('name', el.name);
})


问:
Displaying from multiple table based on the time and showing the source table
So, for example, I have 3 tables

Table 1: name

```<code>id | name | time
 1 | Bob  | 20.42
</code>```

Table 2: item

```<code>id | item   | time
 1 | Bottle | 18.42
 2 | Box    | 21.42
</code>```

Table 3: food

```<code>id | Food | time
1 | Steak | 19.42
</code>```

So I want to display them like this

```<code>From table item: 1 | Bottle
From table food: 1 | Steak
From table name: 1 | Bob
From table item: 2 | Box
</code>```

答:
Use UNION ALL:

```<code>select id, name
from (
    select * from name
    union all
    select * from item
    union all
    select * from food ) t
order by t.`time`
</code>```

Body:
So, for example, I have 3 tables

Table 1: name

id | name | time
 1 | Bob  | 20.42

Table 2: item

id | item   | time
 1 | Bottle | 18.42
 2 | Box    | 21.42

Table 3: food

id | Food | time
1 | Steak | 19.42

So I want to display them like this

From table item: 1 | Bottle
From table food: 1 | Steak
From table name: 1 | Bob
From table item: 2 | Box

Body:
Use UNION ALL:

select id, name
from (
    select * from name
    union all
    select * from item
    union all
    select * from food ) t
order by t.`time`


问:
How To Implement Javascript Polyline Collision Detection
I currently have a JavaScript platformer game. I have created a polygon-polygon collision detection with a response, using the SAT method portrayed on many other websites.

I have also created a function inside the Polygon constructor that will return either the sides exposed to the top of the polygon or the sides exposed to the bottom of the polygon, depending on which direction is chosen. The array that is returned contains many different Vectors, which will be explained more elaborately later.

The current code looks a bit like this:

```<code>Polygon.prototype.getSidesOn = function(dir) {
  if (dir === "top" || dir === "bottom") {
    var result = [], start = false, stop = false, elen =
this.calcPoints.length, e = 0, f = 0, point, next, prevX, prevY, directionX,   directionY;
    while (!stop) {
      if (e >= 5*elen) {return;}
      f = e%elen;
      prev = f-1 < 0 ? this.calcPoints[elen-1] : this.calcPoints[f-1];
      point = this.calcPoints[f];
      prevX = directionX;
      prevY = directionY;
      directionX = point.x > prev.x ? "right" : point.x < prev.x ? "left" : directionX;
      directionY = point.y < prev.y ? "up" : point.y > prev.y ? "down" : directionY;
      if (prevX !== directionX && prevX && prevY) {
        if (!start) {
          start = dir === "top" ? directionY === "up" : directionY === "down";
        } else {
          break;
        }
      }
      if (start) {
        if (point.x !== prev.x) {
          if (!result.length) {
            result.push(new Vector(prev.x,prev.y),new
Vector(point.x,point.y));
          } else {
            result.push(new Vector(point.x,point.y));
          }
        } else {
          break;
        }
      }
      e++;
    }
    return result;
  } else {
    return;
  }
}
</code>```

I understand that it is a bit messy, but that is not a worry as I will optimise it later.

Basically, it works on ONLY convex polygons (I mean the word "convex" as in a triangle or a shape that does not go back into itself). Anyway, it works because of the fact that all convex polygons only have two points where the adjacent sides are facing the opposite X direction.

Anyway, the array that is outputted looks a bit like this:

```<code>//[Vector,Vector,Vector,Vector...]
</code>```

that is not what it actually looks like, but basically, it outputs an array of Vectors for each point detected.

What I need to implement is a way to detect collision between two of these polylines. Unlike the polygon-polygon collision detection system, there does not need to be a response vector, and instead, the code should output either a "true" or "false" bool.

The only way that I can currently think of doing this is as follows:

```<code>function PolylinePolyline(line1,line2) {
  var i, ilen = line1.length, j, jlen = line2.length;
  for (i = 0; i < ilen; i++) {
    for (j = 0; j < jlen; j++) {
      var point1 = line1[i];
      var point2 = i+1 < ilen ? line1[i+1] : line1[0];
      var point3 = line2[j];
      var point4 = j+1 < jlen ? line2[j+1] : line2[0];
      var line01 = new line(point1,point2);
      var line02 = new line(point3,point4);
      if (LineLine(line01,line02) {
        return true;
      }
    }
  }
  return false;
}
</code>```

And although this works, it is very expensive to use if the lines are, let's say, 5 points long, and I have to detect collision between 4 of them. I would prefer an alternative that returns true if they are colliding and false if not. I will not explain why I need this, as it is a bit abstract but an example of a polyline would be this:

Note that the polylines are convex-shaped

答:
You can speed up your collision search by defining (pseudo random) infinite length lines that go between two polygons such that the line splits up the polygons into 3 sets: above, below and colliding. Because they are dvidied by the line, you know that all above do not collide with all below. Repeat this a few times until you have a low number of undecided polygon pairs, then apply your old algorithm to the remaining pairs.

You can find (pseudo random) infinite length lines by calculating the normal at the middle of the line connecting the centers of two polygons in your set of polygons.

Body:
I currently have a JavaScript platformer game. I have created a polygon-polygon collision detection with a response, using the SAT method portrayed on many other websites.

I have also created a function inside the Polygon constructor that will return either the sides exposed to the top of the polygon or the sides exposed to the bottom of the polygon, depending on which direction is chosen. The array that is returned contains many different Vectors, which will be explained more elaborately later.

The current code looks a bit like this:

Polygon.prototype.getSidesOn = function(dir) {
  if (dir === "top" || dir === "bottom") {
    var result = [], start = false, stop = false, elen =
this.calcPoints.length, e = 0, f = 0, point, next, prevX, prevY, directionX,   directionY;
    while (!stop) {
      if (e >= 5*elen) {return;}
      f = e%elen;
      prev = f-1 < 0 ? this.calcPoints[elen-1] : this.calcPoints[f-1];
      point = this.calcPoints[f];
      prevX = directionX;
      prevY = directionY;
      directionX = point.x > prev.x ? "right" : point.x < prev.x ? "left" : directionX;
      directionY = point.y < prev.y ? "up" : point.y > prev.y ? "down" : directionY;
      if (prevX !== directionX && prevX && prevY) {
        if (!start) {
          start = dir === "top" ? directionY === "up" : directionY === "down";
        } else {
          break;
        }
      }
      if (start) {
        if (point.x !== prev.x) {
          if (!result.length) {
            result.push(new Vector(prev.x,prev.y),new
Vector(point.x,point.y));
          } else {
            result.push(new Vector(point.x,point.y));
          }
        } else {
          break;
        }
      }
      e++;
    }
    return result;
  } else {
    return;
  }
}

I understand that it is a bit messy, but that is not a worry as I will optimise it later.

Basically, it works on ONLY convex polygons (I mean the word "convex" as in a triangle or a shape that does not go back into itself). Anyway, it works because of the fact that all convex polygons only have two points where the adjacent sides are facing the opposite X direction.

Anyway, the array that is outputted looks a bit like this:

//[Vector,Vector,Vector,Vector...]

that is not what it actually looks like, but basically, it outputs an array of Vectors for each point detected.

What I need to implement is a way to detect collision between two of these polylines. Unlike the polygon-polygon collision detection system, there does not need to be a response vector, and instead, the code should output either a "true" or "false" bool.

The only way that I can currently think of doing this is as follows:

function PolylinePolyline(line1,line2) {
  var i, ilen = line1.length, j, jlen = line2.length;
  for (i = 0; i < ilen; i++) {
    for (j = 0; j < jlen; j++) {
      var point1 = line1[i];
      var point2 = i+1 < ilen ? line1[i+1] : line1[0];
      var point3 = line2[j];
      var point4 = j+1 < jlen ? line2[j+1] : line2[0];
      var line01 = new line(point1,point2);
      var line02 = new line(point3,point4);
      if (LineLine(line01,line02) {
        return true;
      }
    }
  }
  return false;
}

And although this works, it is very expensive to use if the lines are, let's say, 5 points long, and I have to detect collision between 4 of them. I would prefer an alternative that returns true if they are colliding and false if not. I will not explain why I need this, as it is a bit abstract but an example of a polyline would be this:

Note that the polylines are convex-shaped


问:
How to get value attirbute value from php 2d session variable
I am having an php session array like

```<code>["cart"]["123"] = "Biscuit"
["cart"]["124"] = "Jam"
</code>```

If I want to access the 2nd element I will access array_values($_SESSION["cart"])[$i]
where $i runs in for loop. If I want to get the values "123" and "124", how can i achieve it in a for loop with only "cart" and $i..?

答:
This is an associative array easiest and best way is foreach because have to deal with key-value pairs rather than indexes(numbers).

```<code>foreach($arr['cart'] as $key => $val){
  echo "$key<br/>";
}
</code>```

I used a variable to hold values($arr)

But you can try for loop also:

```<code>$keys = array_keys($arr['cart']);
for ($keyindex = 0; $keyindex < count($keys); $keyindex++) {
    $key = $keys[$keyindex];
    echo $key."<br>";

}
</code>```

Body:
I am having an php session array like

["cart"]["123"] = "Biscuit"
["cart"]["124"] = "Jam"

If I want to access the 2nd element I will access array_values($_SESSION["cart"])[$i]
where $i runs in for loop. If I want to get the values "123" and "124", how can i achieve it in a for loop with only "cart" and $i..?

Body:
This is an associative array easiest and best way is foreach because have to deal with key-value pairs rather than indexes(numbers).

foreach($arr['cart'] as $key => $val){
  echo "$key<br/>";
}

I used a variable to hold values($arr)

But you can try for loop also:

$keys = array_keys($arr['cart']);
for ($keyindex = 0; $keyindex < count($keys); $keyindex++) {
    $key = $keys[$keyindex];
    echo $key."<br>";

}