问:
How can I add multiple tables via LEFT JOIN and count the rows of each table?
I am counting the results of a table I LEFT JOINED:

```<code>SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id
</code>```

http://sqlfiddle.com/#!9/3e9d4b/4

But now I want to add another table via LEFT JOIN and count it also:

```<code>SELECT p.*,COUNT(po.name) AS posts,
    COUNT(ta.name) AS tasks
    FROM projects p
    left join posts po on p.name = po.name
    left join tasks ta on p.name = ta.name
    group by p.id
</code>```

http://sqlfiddle.com/#!9/ee068/2

But now the counting is wrong. For cat I have only 2 posts and 3 tasks. Where is the number 6 coming from?

答:
You can still use joins, but instead of a single top level aggregation, you can aggregate each of the two tables in separate subqueries:

```<code>SELECT
    p.name,
    COALESCE(t1.posts_cnt, 0) AS posts_cnt,
    COALESCE(t2.tasks_cnt, 0) AS tasks_cnt
FROM projects p
LEFT JOIN
(
    SELECT name, COUNT(*) AS posts_cnt
    FROM posts
    GROUP BY name
) t1
    ON p.name = t1.name
LEFT JOIN
(
    SELECT name, COUNT(*) AS tasks_cnt
    FROM tasks
    GROUP BY name
) t2
    ON p.name = t2.name
</code>```

Your current queries have problems, because you are aggregating by id but selecting other columns.  From what I see, you want to be aggregating in all three tables using the name column.

This approach should outperform an approach using correlated subqueries.

Body:
I am counting the results of a table I LEFT JOINED:

SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id

http://sqlfiddle.com/#!9/3e9d4b/4

But now I want to add another table via LEFT JOIN and count it also:

SELECT p.*,COUNT(po.name) AS posts,
    COUNT(ta.name) AS tasks
    FROM projects p
    left join posts po on p.name = po.name
    left join tasks ta on p.name = ta.name
    group by p.id

http://sqlfiddle.com/#!9/ee068/2

But now the counting is wrong. For cat I have only 2 posts and 3 tasks. Where is the number 6 coming from?

Body:
You can still use joins, but instead of a single top level aggregation, you can aggregate each of the two tables in separate subqueries:

SELECT
    p.name,
    COALESCE(t1.posts_cnt, 0) AS posts_cnt,
    COALESCE(t2.tasks_cnt, 0) AS tasks_cnt
FROM projects p
LEFT JOIN
(
    SELECT name, COUNT(*) AS posts_cnt
    FROM posts
    GROUP BY name
) t1
    ON p.name = t1.name
LEFT JOIN
(
    SELECT name, COUNT(*) AS tasks_cnt
    FROM tasks
    GROUP BY name
) t2
    ON p.name = t2.name

Your current queries have problems, because you are aggregating by id but selecting other columns.  From what I see, you want to be aggregating in all three tables using the name column.

This approach should outperform an approach using correlated subqueries.


来源: stackexchange

问:
Getting the return of a store Insert
Ive created a store, which I can manipulate.

```<code>var storeJ = new Ext.data.JsonStore({
    root: 'data',
    idProperty: primaryKey,
    id:'storeJ',
    fields: [primaryKey,'name', 'code', 'email'],
    autoSave:true,
    storeId: 'storeJ',
    proxy: proxyJ,
    writer: writer,
});
storeJ.load();
</code>```

When I try to add to this store, via a button, I return a Pk ( via php )
This happens after

    storeJ.insert(0, r);

```<code>//Tbar Item
handler: function(){
  var r = new storeJ.recordType({   });
  grid.stopEditing();
  storeJ.insert(0, r);
  grid.startEditing(0, 1);
}
</code>```

I assume I need some kinda listener to get there, but how on earth do I create it?

答:
You already have the record before the insert.

Will something like the following work:

```<code>var r = new storeJ.recordType({   });
r.data[primaryKey] = pk;
grid.stopEditing();
storeJ.insert(0, r);
grid.startEditing(0, 1);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Getting the return of a store Insert

Body:
Ive created a store, which I can manipulate.

var storeJ = new Ext.data.JsonStore({
    root: 'data',
    idProperty: primaryKey,
    id:'storeJ',
    fields: [primaryKey,'name', 'code', 'email'],
    autoSave:true,
    storeId: 'storeJ',
    proxy: proxyJ,
    writer: writer,
});
storeJ.load();

When I try to add to this store, via a button, I return a Pk ( via php )
This happens after

    storeJ.insert(0, r);

//Tbar Item
handler: function(){
  var r = new storeJ.recordType({   });
  grid.stopEditing();
  storeJ.insert(0, r);
  grid.startEditing(0, 1);
}

I assume I need some kinda listener to get there, but how on earth do I create it?

Body:
You already have the record before the insert.

Will something like the following work:

var r = new storeJ.recordType({   });
r.data[primaryKey] = pk;
grid.stopEditing();
storeJ.insert(0, r);
grid.startEditing(0, 1);


问:
Replacing string with Regex with start and end tags with Java replace function
I have a mathematical formulas string like this.

```<code>(##type## * 2) + 5 + ##component## + ##param##
</code>```

After replacing, I want to get like this.

```<code>((value.type) * 2) + 5 + (value.component) + (value.param)
</code>```

I will always add the "value." string to the begining of the parameters and add both side (). How can i do this?

答:
```<code>String test = "(##type## * 2) + 5 + ##component## + ##param##";
System.out.println(test.replaceAll("##(.*?)##", "(value.$1)"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a mathematical formulas string like this.

(##type## * 2) + 5 + ##component## + ##param##

After replacing, I want to get like this.

((value.type) * 2) + 5 + (value.component) + (value.param)

I will always add the "value." string to the begining of the parameters and add both side (). How can i do this?


问:
Close android keyboard on the last field of a form
Is there a way to close the android keyboard when I'm on the last input of a form, already filled it, and click on the keyboard 'enter' button? It's a web app built with angularjs. Thanks</p>

答:
After the 'enter' button you could focus on an element (an  for example) and this should hide the soft keyboard.
Details to catch the enter button here: angularjs move focus to next control on enter

Body:
After the 'enter' button you could focus on an element (an <a> for example) and this should hide the soft keyboard.
Details to catch the enter button here: angularjs move focus to next control on enter


问:
Java method called with reflection only. Annotate?
I have a bunch of classes named Process0, Process1, Process2 etc. inherited from a base class Process. Every child class includes the same static method. Future implementations may add more "ProcessNN".

I have to iterate all classes and call the same method from every class for specific data.
It happened this static method is never called directly, only with reflection.

How can I mark/annotate this method in every class to remove warnings over "never used method" and preserve it from automatic code optimization?

Thanks.

答: You can add the @SuppressWarnings("unused") annotation to suppress compiler (and most IDE) warnings.


问:
Adding controls (trackbars, multiline textboxes and labels) to a form under different DPIs - C#
My application loads information from a file which then creates x amount of controls on y amounts of tabpages in a form.

My problem is that when the user has a different DPI to the standard Windows 96, the controls added overlap each other. The initial controls on the form are fine.

How can I set the controls to be modified to the 96 DPI instead of whatever the users machine is running at?

If this is very difficult, is there a way to see what the users DPI is? I can then throw a warning saying that you should use 96DPI etc etc.

Thank you for any help or advise you can give me!

答: I assume you use Windows.Forms. You can use property AutoScaleMode to control how each GUI control is zoomed. There are more options you can choose, so go and try what is best for you or you can also read this article in MSDN to get more information on principles of zooming of controls in Windows.Forms.


问:
Eclipse keep asking about SVN credentials
I have tried to move SVN project to Git.
I have created a remote REPO and pushed my project there.
Whenever I open Eclipse Europa I keep getting a message about SVN credentials and I can't get rid of it; after the Cancel button is pressed, the same window appear again.

How to get rig of the nasty window?

I have deleted hidden .svn folders and tried steps suggested in this article:
http://www.thinkplexx.com/learn/howto/ide/eclipse/fix-eclipse-svn-always-asking-for-login-and-password-clear-keyring-or-cache

答: Create a new workspace (e. g. by using the command line argument -data) and import your project(s) from the old into the new workspace.


问:
intent_filter: run apk build in UNITY from url
I have a problem running the app via url.
I added to manifest intent-filter, but it does not work.
I would like to have the application launch after the url, of course it is on the device.

This is the code activity in my android manifest:

<activity android:label="@string/app_name" android:name="com.unity3d.player.UnityPlayerActivity" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="testurl" android:host="app.open"/>
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
```

Is there anyone able to help me?

答: It works. It was necessary to create an html with a URL.</p>

Body:
I have a problem running the app via url.
I added to manifest intent-filter, but it does not work.
I would like to have the application launch after the url, of course it is on the device.

This is the code activity in my android manifest:

<activity android:label="@string/app_name" android:name="com.unity3d.player.UnityPlayerActivity" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="testurl" android:host="app.open"/>
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>

Is there anyone able to help me?


问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
Typically a Linux program returns 0 on success or non-zero on failure.   There are some exceptions (grep for example, which has values to represent whether it found a match).    The reason for this is that the bash prompt defines true as 0, and false as 1, so it makes scripting simple:

```<code>somecmd && action "if succesful"
</code>```

But that's the program itself.   For code inside of a program, there is often a mixture of conventions.   A common one is to return 0 (or positive) on success, or negative on failure.   The reason behind this is that all instruction sets (that I'm aware of), have a branch-if-zero, or branch-if-less-than-zero instructions, which means its only one instruction to do the comparison (as opposed to having to do a compare and then branch if the comparison matched).

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

Body:
Typically a Linux program returns 0 on success or non-zero on failure.   There are some exceptions (grep for example, which has values to represent whether it found a match).    The reason for this is that the bash prompt defines true as 0, and false as 1, so it makes scripting simple:

somecmd && action "if succesful"

But that's the program itself.   For code inside of a program, there is often a mixture of conventions.   A common one is to return 0 (or positive) on success, or negative on failure.   The reason behind this is that all instruction sets (that I'm aware of), have a branch-if-zero, or branch-if-less-than-zero instructions, which means its only one instruction to do the comparison (as opposed to having to do a compare and then branch if the comparison matched).


问:
What does '@' at beginning of a variable mean?

Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

```<code>try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}
</code>```

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?

答: Resharper outputs them sometimes if the name of the variable is close to a class name or a namespace i believe, it is just giving it a unique non clashing name</p>

Body:
Possible Duplicate:

  What does the @ symbol before a variable name mean in C#?

I've seen this a couple of times in code that has been passed onto me:

try {
   //Do some stuff
}
catch(Exception @exception)
{
   //Do catch stuff
}

Can anyone please explain the purpose of the '@' at the beginning of the Exception variable?


问:
Advantages/disadvantages of init method
What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?

```<code>public class A {
  private int x;

  public A(int x){
    this.x = x;
  }

  public void init(int x){
   this.x = x;
  }
}
</code>```

Here we can use either constructor or init method.

答:
You are wrong. They do not have the same purpose.

A constructor is always required when you want to create a new object using the new() operator.

A init method is something that might make sense in certain contexts, for example servlet stuff (see here for further reading regarding this aspect).

And please note: in your example, one could your init method more as a setter - as it is simply setting the corresponding field.

Coming from there:

first of all, you think about the constructors that you want to put into you class (by asking: which information is required to create a new instance of the class)

if there is special need, then consider adding setters for specific fields - or as layed out above, it might be required to provide an init() method (in case where object creation and initializiation can not happen at the same point of time)

Title: Advantages/disadvantages of init method

Body:
What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?

public class A {
  private int x;

  public A(int x){
    this.x = x;
  }

  public void init(int x){
   this.x = x;
  }
}

Here we can use either constructor or init method.


问:
How to send information from SQL table by using phpmailer?
I have a SQL table that shows the expiry date of the items, and I want to send the status of the expiration date on a daily basis through email, where I want the user to know the expiration date update for the listed items.

I tried to use this example in phpmailer, by using localhost and it works, but I do not know how to link that with my case.

For example, is it possible to do like this $body= include ('sql.php'); or is there other way to do that?, where I am only interested in sending the Expiry Date and Expiration Message from this table, and is it possible to send the entire table?

Here is the SQL code

```<code><?php

 $con=mysqli_connect('localhost','','','arduino');

 if(mysqli_connect_errno($con))
 {
    echo 'Failed to connect:'.mysqli_connect_error();
}
else
    echo 'Connected Successfully!! </br>';
$url=$_SERVER['REQUEST_URI'];
$sql = "SELECT
    ID,
    Item_Name,
    Expiry_Date,
    CASE
        WHEN `Expiry_Date` < CURDATE() THEN CONCAT(`Item_Name`,' has EXPIRED already')
        WHEN `Expiry_Date` = CURDATE() THEN CONCAT(`Item_Name`,' will expire today')
        WHEN `Expiry_Date` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' will expire tomorrow')
        WHEN `Expiry_Date` > DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' has not expire yet')
        ELSE 'Error processing expiration date.'
   END AS `Expiration_Message`
FROM
    test;";

    $result = mysqli_query($con,$sql);

    while($row = mysqli_fetch_array($result)){
        echo ($row['Expiration_Message']);
        echo '<br>';
    }

    print_r($row);

    mysqli_close($con);

?>
</code>```

And here is the code that I took it from phpmailer example

```<code><?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    //$mail->SMTPDebug = 1;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'Smtp.live.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'XXXXX@hotmail.com';                 // SMTP username
    $mail->Password = 'XXXXX';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('XXXXX@hotmail.com', 'Smart Fridge');
    $mail->addAddress('XXXXX@gmail.com', 'Joe');     // Add a recipient
    $body= '<p><td><strong>Hello</strong></td> this is my first email!!!!</p>';

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Expiry Date';
    $mail->Body    = $body;
    $mail->AltBody = strip_tags($body);

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}
</code>```

答:
You need to store your result into a variable, not echo it.

```<code>$mailBody = '';

while($row = mysqli_fetch_array($result)){
    $mailBody .= $row['Expiration_Message'] . "<br>\n";
}
</code>```

and later

```<code>$mail->Body    = $mailBody;
</code>```

.= is an operator to concatenate your strings. It is equal to:

```<code>$mailBody = $mailBody . 'something new string to concat';
</code>```

Body:
I have a SQL table that shows the expiry date of the items, and I want to send the status of the expiration date on a daily basis through email, where I want the user to know the expiration date update for the listed items.

I tried to use this example in phpmailer, by using localhost and it works, but I do not know how to link that with my case.

For example, is it possible to do like this $body= include ('sql.php'); or is there other way to do that?, where I am only interested in sending the Expiry Date and Expiration Message from this table, and is it possible to send the entire table?

Here is the SQL code

<?php

 $con=mysqli_connect('localhost','','','arduino');

 if(mysqli_connect_errno($con))
 {
    echo 'Failed to connect:'.mysqli_connect_error();
}
else
    echo 'Connected Successfully!!
';
$url=$_SERVER['REQUEST_URI'];
$sql = "SELECT
    ID,
    Item_Name,
    Expiry_Date,
    CASE
        WHEN `Expiry_Date` < CURDATE() THEN CONCAT(`Item_Name`,' has EXPIRED already')
        WHEN `Expiry_Date` = CURDATE() THEN CONCAT(`Item_Name`,' will expire today')
        WHEN `Expiry_Date` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' will expire tomorrow')
        WHEN `Expiry_Date` > DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' has not expire yet')
        ELSE 'Error processing expiration date.'
   END AS `Expiration_Message`
FROM
    test;";

    $result = mysqli_query($con,$sql);

    while($row = mysqli_fetch_array($result)){
        echo ($row['Expiration_Message']);
        echo '
';
    }

    print_r($row);

    mysqli_close($con);

?>

And here is the code that I took it from phpmailer example

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    //$mail->SMTPDebug = 1;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'Smtp.live.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'XXXXX@hotmail.com';                 // SMTP username
    $mail->Password = 'XXXXX';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('XXXXX@hotmail.com', 'Smart Fridge');
    $mail->addAddress('XXXXX@gmail.com', 'Joe');     // Add a recipient
    $body= '
Hello	 this is my first email!!!!
';

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Expiry Date';
    $mail->Body    = $body;
    $mail->AltBody = strip_tags($body);

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
}

Body:
You need to store your result into a variable, not echo it.

$mailBody = '';

while($row = mysqli_fetch_array($result)){
    $mailBody .= $row['Expiration_Message'] . "<br>\n";
}

and later

$mail->Body    = $mailBody;

.= is an operator to concatenate your strings. It is equal to:

$mailBody = $mailBody . 'something new string to concat';


问:
Track remote branch from local branch
By using:

```<code>git checkout --track origin/branch1
</code>```

does it matter to which local branch am I already checked out? For example is it different to run the above when I am on local master or to another local branch? If yes what is the difference? Does branch1 become branch of the current local branch?

答: No, your local branch1 will be exactly like the remote one, no matter where you started.

Title: Track remote branch from local branch

Body:
By using:

git checkout --track origin/branch1

does it matter to which local branch am I already checked out? For example is it different to run the above when I am on local master or to another local branch? If yes what is the difference? Does branch1 become branch of the current local branch?


问:
Using css border property in eclipse rcp application
I am currently working on an eclipse rcp application that we want to customize look-and-feel wise via CSS.

Sadly the documentation is not that great, so I'd like to try to get help here.

I would like to configure the border of several Widgets via CSS. For example Composite or ScrolledComposite.

The CSS Theme is working generally, this question is only about the border property.

Can I use the border property at all to configure the border of an Widget or is there only the SWT.BORDER property that needs to be set in the creation process of a widget?

答:
There is no support for borders in the SWT CSS. The SWT.BORDER style on the control constructor is the only thing available.

You can write your own CSS property handlers using the org.eclipse.e4.ui.css.core.propertyHandler extension point, but adding a border would be difficult as the SWT controls don't support it.

All the existing CSS properties are defined using the org.eclipse.e4.ui.css.core.propertyHandler extension point, mostly in the org.eclipse.e4.ui.css.swt plugin.


问:
RxJava. Sequential execution
In my Android App I have a presenter which handles user interactions, contains kind of request manager and if needed sends user input over request manager to request manager.

Request manager itself contains server API and handles server request using this RxJava.

I have a code, which sends a request to server everytime a user enters a message and show the response from server:

```<code>private Observable<List<Answer>> sendRequest(String request) {
    MyRequest request = new MyRequest();
    request.setInput(request);
    return Observable.fromCallable(() -> serverApi.process(request))
            .doOnNext(myResponse -> {
                // store some data
            })
            .map(MyResponse::getAnswers)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());
}
</code>```

However now I need to have kind of queue. The user may send a new message before the server has responded. Each message from the queue should be processed sequentially. I.e. the second message will be sent after we've got a response to the first message and so on.

In case an error occurs no further requests should be handled.

I also need to display the answers within a RecyclerView.

I have no idea how to change the code above to achieve the handling described above

I see kind of problem. On one hand, this queue can be anytime updated by the user, on the other hand anytime server sent a response the message should be removed from the queue.

Maybe there is a rxjava operator or special way I just missed.

I saw a similar answer here, however, the "queue" there is constant.
Making N sequential api calls using RxJava and Retrofit

I'll be very thankful for any solution or link

答:
For this kind of behaviour I'm using Flowable backpressure implementation.
Create outer stream that is parent for your api request stream, flatMap the api request with maxConcurrency = 1 and implement some sort of buffer strategy, so your Flowable doesn't throw exception.

```<code>Flowable.create(emitter -> {/* user input stream*/}, BackpressureStrategy.BUFFER)
                .onBackpressureBuffer(127, // buffer size
                        () -> {/* overflow action*/},
                        BackpressureOverflowStrategy.DROP_LATEST) // action when buffer exceeds 127
                .flatMap(request -> sendRequest(request), 1) // very important parameter
                .subscribe(results -> {
                    // work with results
                }, error -> {
                    // work with errors
                });
</code>```

It will buffer user input up to given threshold, and then drop it(if you don't do this it will throw exception, but it is highly unlikely that user will exceed such buffer), it will execute sequentially 1 by 1 like a queue. Don't try to implement this behaviour yourself if there are operators for thing kind of behaviour in libary itself.

Oh I forgot to mention, your sendRequest() method must return Flowable or you can convert it to Flowable.

Hope this helps!

Title: RxJava. Sequential execution

Body:
In my Android App I have a presenter which handles user interactions, contains kind of request manager and if needed sends user input over request manager to request manager.

Request manager itself contains server API and handles server request using this RxJava.

I have a code, which sends a request to server everytime a user enters a message and show the response from server:

private Observable<List<Answer>> sendRequest(String request) {
    MyRequest request = new MyRequest();
    request.setInput(request);
    return Observable.fromCallable(() -> serverApi.process(request))
            .doOnNext(myResponse -> {
                // store some data
            })
            .map(MyResponse::getAnswers)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread());
}

However now I need to have kind of queue. The user may send a new message before the server has responded. Each message from the queue should be processed sequentially. I.e. the second message will be sent after we've got a response to the first message and so on.

In case an error occurs no further requests should be handled.

I also need to display the answers within a RecyclerView.

I have no idea how to change the code above to achieve the handling described above

I see kind of problem. On one hand, this queue can be anytime updated by the user, on the other hand anytime server sent a response the message should be removed from the queue.

Maybe there is a rxjava operator or special way I just missed.

I saw a similar answer here, however, the "queue" there is constant.
Making N sequential api calls using RxJava and Retrofit

I'll be very thankful for any solution or link

Body:
For this kind of behaviour I'm using Flowable backpressure implementation.
Create outer stream that is parent for your api request stream, flatMap the api request with maxConcurrency = 1 and implement some sort of buffer strategy, so your Flowable doesn't throw exception.

Flowable.create(emitter -> {/* user input stream*/}, BackpressureStrategy.BUFFER)
                .onBackpressureBuffer(127, // buffer size
                        () -> {/* overflow action*/},
                        BackpressureOverflowStrategy.DROP_LATEST) // action when buffer exceeds 127
                .flatMap(request -> sendRequest(request), 1) // very important parameter
                .subscribe(results -> {
                    // work with results
                }, error -> {
                    // work with errors
                });

It will buffer user input up to given threshold, and then drop it(if you don't do this it will throw exception, but it is highly unlikely that user will exceed such buffer), it will execute sequentially 1 by 1 like a queue. Don't try to implement this behaviour yourself if there are operators for thing kind of behaviour in libary itself.

Oh I forgot to mention, your sendRequest() method must return Flowable or you can convert it to Flowable.

Hope this helps!


问:
Unable to create node_modules folder at host and mount host folder to container
My dockerfile will run npm install, however after docker-compose build the folder node_modules in my host folder remains empty even after seeing building. How can i get the folder up and reflected in the host too?

This is docker-compose.yml:

This is my docker-compose

```<code>version: "2"

volumes:
  mongostorage:

services:
  app:
    build: ./app
    ports:
      - "3000"
    links:
      - mongo
      - redis
    command: node ./bin/www
  nginx:
    build: ./nginx
    ports:
      - "80:80"
    links:
      - app:app
  mongo:
    image: mongo:latest
    environment:
      - MONGO_DATA_DIR=/data/db
    volumes:
      - mongostorage:/data/db
    ports:
      - "27017:27017"
  redis:
    image: redis
    volumes:
      - ./data/redis/db:/data/db
    ports:
      - "6379:6379"
</code>```

This is dockerfile in app

```<code>FROM node:6.3

RUN mkdir -p /var/www/app

WORKDIR /var/www/app

VOLUME /var/www/app

COPY . /var/www/app

COPY package.json /var/www/app

RUN npm install
</code>```

package.json

```<code>{
  "name": "app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "body-parser": "^1.13.3",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "helmet": "^3.0.0",
    "jade": "~1.11.0",
    "redis": "^2.6.2",
    "serve-favicon": "~2.3.0"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1",
    "gulp-complexity": "^0.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-cssnano": "^2.1.2",
    "gulp-less": "^3.3.0",
    "gulp-uglify": "^1.5.4",
    "gulp-watch": "^4.3.11",
    "strip-debug": "^1.1.1",
    "util": "^0.10.3"
  }
}
</code>```

docker logs for the app container returns after docker-compose up error:

```<code>module.js:442
    throw err;
    ^

Error: Cannot find module 'dotenv'
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/nodeapp/app.js:3:1)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
</code>```

答:
starting fresh..

The following is, I believe, what you are asking for, but I'm not sure it's what you want.

What is the actual use case you are trying to address?

If it is to be able to develop your app, modifying files on your local system and have them reflected in the docker container this is not the way to do it..

I have used the npm module serve as an easy way to keep the container running.

I have used a named volume to make things easier. The volume data is defined in docker-compose and mounted on /var/www/app.

fyi, you could also try moving the VOLUME instruction in your original Dockerfile to the bottom as at https://docs.docker.com/engine/reference/builder/#volume:

```<code>Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.
</code>```

But this still only defines the volume mount point in the container, you still need to mount it on the host at run time.

App files:

```<code>$ tree
.
├── app
│   ├── Dockerfile
│   └── package.json
└── docker-compose.yml

1 directory, 3 files

$ cat app/Dockerfile
FROM node:6.3
RUN mkdir -p /var/www/app
WORKDIR /var/www/app
COPY . /var/www/app
RUN npm install

$ cat app/package.json
{
  "name": "app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "serve"
  },
  "dependencies": {
    "serve": "*"
  }
}

$ cat docker-compose.yml
version: "2"

services:
  app:
    build: ./app
    ports:
      - "3000"
    command: npm start
    volumes:
      - data:/var/www/app
volumes:
  data:
</code>```

Build the app:

```<code>$ docker-compose build app
Building app
Step 1/5 : FROM node:6.3
---> 0d9089853221
Step 2/5 : RUN mkdir -p /var/www/app
---> Using cache
---> 18cc43628367
Step 3/5 : WORKDIR /var/www/app
---> Using cache
---> b8fa2b1a2624
Step 4/5 : COPY . /var/www/app
---> de38a6c3f784
Step 5/5 : RUN npm install
---> Running in 5a035f687de1
npm info it worked if it ends with ok
npm info using npm@3.10.3
npm info using node@v6.3.1
npm info attempt registry request try #1 at 1:19:21 PM
npm http request GET https://registry.npmjs.org/serve
...
npm info ok
---> 76b99c707ac1
Removing intermediate container 5a035f687de1
Successfully built 76b99c707ac1
Successfully tagged 47173020_app:latest
</code>```

Bring up the app

```<code>$ docker-compose up -d app
Recreating 47173020_app_1 ...
Recreating 47173020_app_1 ... done
</code>```

Check the app logs

```<code>$ docker-compose logs app
Attaching to 47173020_app_1
app_1  | npm info it worked if it ends with ok
app_1  | npm info using npm@3.10.3
app_1  | npm info using node@v6.3.1
app_1  | npm info lifecycle app@0.0.0~prestart: app@0.0.0
app_1  | npm info lifecycle app@0.0.0~start: app@0.0.0
app_1  |
app_1  | > app@0.0.0 start /var/www/app
app_1  | > serve
app_1  |
app_1  | serve: Running on port 5000
</code>```

Now the volume you are looking for on the host is on the docker host running as a vm on your local machine and can only be accessed from a running container.

I have taken the following from Inspecting Docker Volumes on a Mac/Windows the Easy Way which you can refer to for more detail.

List the docker volumes

```<code>$ docker volume ls
local               47173020_data
</code>```

Inspect the volume to get it's mount point

```<code>$ docker volume inspect 47173020_data
[
    {
        "CreatedAt": "2017-11-13T13:15:59Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/47173020_data/_data",
        "Name": "47173020_data",
        "Options": {},
        "Scope": "local"
    }
]
</code>```

Start up a simple container, mount "/docker" on the host root, and list the files in the volume which are the ones copied and created by the Dockerfile

```<code>$ docker run --rm -it -v /:/docker alpine:edge ls -l /docker/var/lib/docker/volumes/47173020_data/_data
total 12
-rw-r--r--    1 root     root           119 Nov 13 12:30 Dockerfile
drwxr-xr-x  153 root     root          4096 Nov 13 13:14 node_modules
-rw-r--r--    1 root     root           144 Nov 13 13:03 package.json
</code>```

Body:
My dockerfile will run npm install, however after docker-compose build the folder node_modules in my host folder remains empty even after seeing building. How can i get the folder up and reflected in the host too?

This is docker-compose.yml:

This is my docker-compose

version: "2"

volumes:
  mongostorage:

services:
  app:
    build: ./app
    ports:
      - "3000"
    links:
      - mongo
      - redis
    command: node ./bin/www
  nginx:
    build: ./nginx
    ports:
      - "80:80"
    links:
      - app:app
  mongo:
    image: mongo:latest
    environment:
      - MONGO_DATA_DIR=/data/db
    volumes:
      - mongostorage:/data/db
    ports:
      - "27017:27017"
  redis:
    image: redis
    volumes:
      - ./data/redis/db:/data/db
    ports:
      - "6379:6379"

This is dockerfile in app

FROM node:6.3

RUN mkdir -p /var/www/app

WORKDIR /var/www/app

VOLUME /var/www/app

COPY . /var/www/app

COPY package.json /var/www/app

RUN npm install

package.json

{
  "name": "app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "body-parser": "^1.13.3",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "helmet": "^3.0.0",
    "jade": "~1.11.0",
    "redis": "^2.6.2",
    "serve-favicon": "~2.3.0"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1",
    "gulp-complexity": "^0.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-cssnano": "^2.1.2",
    "gulp-less": "^3.3.0",
    "gulp-uglify": "^1.5.4",
    "gulp-watch": "^4.3.11",
    "strip-debug": "^1.1.1",
    "util": "^0.10.3"
  }
}

docker logs for the app container returns after docker-compose up error:

module.js:442
    throw err;
    ^

Error: Cannot find module 'dotenv'
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/nodeapp/app.js:3:1)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)

Body:
starting fresh..

The following is, I believe, what you are asking for, but I'm not sure it's what you want.

What is the actual use case you are trying to address?

If it is to be able to develop your app, modifying files on your local system and have them reflected in the docker container this is not the way to do it..

I have used the npm module serve as an easy way to keep the container running.

I have used a named volume to make things easier. The volume data is defined in docker-compose and mounted on /var/www/app.

fyi, you could also try moving the VOLUME instruction in your original Dockerfile to the bottom as at https://docs.docker.com/engine/reference/builder/#volume:

Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.

But this still only defines the volume mount point in the container, you still need to mount it on the host at run time.

App files:

$ tree
.
├── app
│   ├── Dockerfile
│   └── package.json
└── docker-compose.yml

1 directory, 3 files

$ cat app/Dockerfile
FROM node:6.3
RUN mkdir -p /var/www/app
WORKDIR /var/www/app
COPY . /var/www/app
RUN npm install

$ cat app/package.json
{
  "name": "app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "serve"
  },
  "dependencies": {
    "serve": "*"
  }
}

$ cat docker-compose.yml
version: "2"

services:
  app:
    build: ./app
    ports:
      - "3000"
    command: npm start
    volumes:
      - data:/var/www/app
volumes:
  data:

Build the app:

$ docker-compose build app
Building app
Step 1/5 : FROM node:6.3
---> 0d9089853221
Step 2/5 : RUN mkdir -p /var/www/app
---> Using cache
---> 18cc43628367
Step 3/5 : WORKDIR /var/www/app
---> Using cache
---> b8fa2b1a2624
Step 4/5 : COPY . /var/www/app
---> de38a6c3f784
Step 5/5 : RUN npm install
---> Running in 5a035f687de1
npm info it worked if it ends with ok
npm info using npm@3.10.3
npm info using node@v6.3.1
npm info attempt registry request try #1 at 1:19:21 PM
npm http request GET https://registry.npmjs.org/serve
...
npm info ok
---> 76b99c707ac1
Removing intermediate container 5a035f687de1
Successfully built 76b99c707ac1
Successfully tagged 47173020_app:latest

Bring up the app

$ docker-compose up -d app
Recreating 47173020_app_1 ...
Recreating 47173020_app_1 ... done

Check the app logs

$ docker-compose logs app
Attaching to 47173020_app_1
app_1  | npm info it worked if it ends with ok
app_1  | npm info using npm@3.10.3
app_1  | npm info using node@v6.3.1
app_1  | npm info lifecycle app@0.0.0~prestart: app@0.0.0
app_1  | npm info lifecycle app@0.0.0~start: app@0.0.0
app_1  |
app_1  | > app@0.0.0 start /var/www/app
app_1  | > serve
app_1  |
app_1  | serve: Running on port 5000

Now the volume you are looking for on the host is on the docker host running as a vm on your local machine and can only be accessed from a running container.

I have taken the following from Inspecting Docker Volumes on a Mac/Windows the Easy Way which you can refer to for more detail.

List the docker volumes

$ docker volume ls
local               47173020_data

Inspect the volume to get it's mount point

$ docker volume inspect 47173020_data
[
    {
        "CreatedAt": "2017-11-13T13:15:59Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/47173020_data/_data",
        "Name": "47173020_data",
        "Options": {},
        "Scope": "local"
    }
]

Start up a simple container, mount "/docker" on the host root, and list the files in the volume which are the ones copied and created by the Dockerfile

$ docker run --rm -it -v /:/docker alpine:edge ls -l /docker/var/lib/docker/volumes/47173020_data/_data
total 12
-rw-r--r--    1 root     root           119 Nov 13 12:30 Dockerfile
drwxr-xr-x  153 root     root          4096 Nov 13 13:14 node_modules
-rw-r--r--    1 root     root           144 Nov 13 13:03 package.json


问:
Typing Casting in Python Question
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

```<code>for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}
</code>```

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

答:
Figured this out, Python deal with classes a little more intelligently

In Actionscript

```<code>for ( var f in itemArray ) {
   // call function in f
   FooObject(f).doSomething()
}
</code>```

In Python

```<code>for FooObject in itemArray:
    # call function
    FooObject.foo()
</code>```

Title: Typing Casting in Python Question

Body:
Im a AS3 developer, currently learning Python

In AS3 Id quite often do this:

for ( var foo in fooArray ) {
   trace(FooObject(foo).name);
}

Typing casting the objects in the array, so that I get code hinting in my IDE

How would I do this in Python?

Body:
Figured this out, Python deal with classes a little more intelligently

In Actionscript

for ( var f in itemArray ) {
   // call function in f
   FooObject(f).doSomething()
}

In Python

for FooObject in itemArray:
    # call function
    FooObject.foo()


问:
How to combine post table and image table using sql left join and union
How do i combine 3 tables user table, post table and image table to display post with image and post without image
using sql inner join, left join and union.

Table Users

```<code>userid | uname |  pagename
-------|-------|-----
801    | peter |  a1
2      | john  |
</code>```

Table Post

```<code>postid | postuserid | message
-------|------------|--------------
10     |  801       | This is post without image
101    |  801       | This is post with 2 images
102    |  801       | This is post with 1 image
</code>```

Table Images

```<code>img | imgpostid | url
----|-----------|------------
1   | 101       | image1.png
2   | 101       | image2.png
3   | 102       | image01.png
</code>```

My SQL Query

```<code>SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801
</code>```

Expected result

```<code>This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
</code>```

The result i get

```<code>This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]
</code>```

答:
You are looking for string aggregation, namely LISTAGG:

```<code>select p.*, i.images
from posts p
left join
(
  select imgpostid, listagg(url, ',') within group (order by url) as images
  from images
  group by imgpostid
) i on i.imgpostid = p.postid;
</code>```

Body:
How do i combine 3 tables user table, post table and image table to display post with image and post without image
using sql inner join, left join and union.

Table Users

userid | uname |  pagename
-------|-------|-----
801    | peter |  a1
2      | john  |

Table Post

postid | postuserid | message
-------|------------|--------------
10     |  801       | This is post without image
101    |  801       | This is post with 2 images
102    |  801       | This is post with 1 image

Table Images

img | imgpostid | url
----|-----------|------------
1   | 101       | image1.png
2   | 101       | image2.png
3   | 102       | image01.png

My SQL Query

SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801

Expected result

This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

The result i get

This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

Body:
You are looking for string aggregation, namely LISTAGG:

select p.*, i.images
from posts p
left join
(
  select imgpostid, listagg(url, ',') within group (order by url) as images
  from images
  group by imgpostid
) i on i.imgpostid = p.postid;


问:
Whats the point of letting the user commit before pulling?
If a user commits local changes, and tries to push the changes to a repository that has new changes, the push will fail saying that there are unpulled changes.

But if you try to pull the changes, it will fail because there are uncommited (to the repository) changes in my local repository.

What is the point of letting users commit changes if they will not be able to push them if he doesn't pull first?

答:
Committing changes is something you do locally i.e. in your own local working copy as opposed to any remote branch. Git makes you commit before pulling so that your local, "unregistered" changes are not overwritten by whatever you are pulling from the remote (note that "pulling" means "fetch" + "merge", or download changes and merge them with your local changes). If anything it's wrong or there is any merge conflict, you will be able to solve it thanks to your commit. That's why you can and should commit first, then pull (fetch + merge), and then push.

There are many reasons why several devs shouldn't be pushing to the same branch, but that's a different story I guess.


问:
Creating a Box Matrix in Python
I am relatively new to python and I am struggling to work this out. Its pretty simple but I am horrible at coding.

Write a function box_matrix(rows, cols) which creates a new matrix (a 2D NumPy array) with the given number of rows and columns, such that all elements are 0, except for the rows and columns at the "edges" of the matrix, which should be 1, (a "hollow" or "box" matrix").

答:
Start with a matrix of 0's, as indexing in python starts at 0 your final rows and columns are rows - 1 and cols - 1. The : in the indexing means all rows or all columns. Use these two indexing facts to fill in the "box" positions with 1.</p>

```<code>import numpy as np

def box_matrix(rows,cols):
    mat = np.zeros( (rows,cols ))
    mat[:,0] = 1
    mat[0,:] = 1
    mat[rows-1,:] = 1
    mat[:,cols-1] = 1
    return mat

bm = box_matrix(4,4)

print bm
</code>```

Title: Creating a Box Matrix in Python

Body:
Start with a matrix of 0's, as indexing in python starts at 0 your final rows and columns are rows - 1 and cols - 1. The : in the indexing means all rows or all columns. Use these two indexing facts to fill in the "box" positions with 1.

import numpy as np

def box_matrix(rows,cols):
    mat = np.zeros( (rows,cols ))
    mat[:,0] = 1
    mat[0,:] = 1
    mat[rows-1,:] = 1
    mat[:,cols-1] = 1
    return mat

bm = box_matrix(4,4)

print bm


问:
Fastlane: cannot use p12 file generated by "match" command
I am configuring Fastlane and their match command to generate my Certificates and provisionings. All files are stored in a private github repo as recommended in the fastlane docs.

All worked properly, certificates and provisionings were generated and stored in my private repo, including the p12 file for the certificates.
But when I try to download this p12 file (to run my app in Xcode) it seems to be encripted.

The match command encripted the p12 before uploading it to github, so the question is:

--> How can I download and decrypt the p12 file generated by match command in my private repo??

答:
If you want to manually decrypt a file (https://docs.fastlane.tools/actions/match/#manual-decrypt)</p>

```<code>openssl aes-256-cbc -k "<password>" -in "<fileYouWantToDecryptPath>" -out "<decryptedFilePath>" -a -d
</code>```

Body:
If you want to manually decrypt a file (https://docs.fastlane.tools/actions/match/#manual-decrypt)

openssl aes-256-cbc -k "<password>" -in "<fileYouWantToDecryptPath>" -out "<decryptedFilePath>" -a -d


问:
ASP.NET Root Url Doesn't Resolve to Default.aspx
I have an asp.net web site that won't seem to resolve to Default.aspx when initially loading. When I debug on my local machine it loads Default no problem. Unless I try to navigate to "localhost:#####/". Then it gives a 404 error. When I deploy it to a staging server, give it a virtual path "mywebapp", and load it from "mydomain.com/mywebapp" it gives a 404 as well. I have set Default.aspx to the top of the list for Default Document in IIS. If I navigate to "mydomain.com/mywebapp/default" the site loads just fine. Any suggestions? I would paste code but it is a large website and I quite honestly am not sure what I'm looking for anymore.

EDIT:
In my site I am also using DataTables for display and edit of data. In the ajax calls I was previously able to call the controller by using urls such as:

```<code>api/MyController/idvalue
</code>```

but since uncovering this I had to go back and preface the urls to get them to work:

```<code>mywebapp/api/MyController/idvalue
</code>```

Controller:

```<code>public class MyController : ApiController
{
    [Route("api/MyContoller/{idvalue}")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult MyControllerMethod(intidvalue)
    {
    }
}
</code>```

WebApiConfig:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

RouteConfig:

```<code> public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.MapRoute(
        //        name: "Default",
        //        url: "{controller}/{action}/{id}",
        //        defaults: new { action = "Index", id = UrlParameter.Optional }
        //    );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

答:
Found the solution. In my RouteConfig.cs if I comment out the line:

```<code>controller = "Home",
</code>```

it works just fine.

```<code>public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.MapRoute(
        //        name: "Default",
        //        url: "{controller}/{action}/{id}",
        //        defaults: new { action = "Index", id = UrlParameter.Optional }
        //    );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                //controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}
</code>```

However, I'm not completely sure why this is. So if anyone is able to explain it to me that would be great!

Body:
I have an asp.net web site that won't seem to resolve to Default.aspx when initially loading. When I debug on my local machine it loads Default no problem. Unless I try to navigate to "localhost:#####/". Then it gives a 404 error. When I deploy it to a staging server, give it a virtual path "mywebapp", and load it from "mydomain.com/mywebapp" it gives a 404 as well. I have set Default.aspx to the top of the list for Default Document in IIS. If I navigate to "mydomain.com/mywebapp/default" the site loads just fine. Any suggestions? I would paste code but it is a large website and I quite honestly am not sure what I'm looking for anymore.

EDIT:
In my site I am also using DataTables for display and edit of data. In the ajax calls I was previously able to call the controller by using urls such as:

api/MyController/idvalue

but since uncovering this I had to go back and preface the urls to get them to work:

mywebapp/api/MyController/idvalue

Controller:

public class MyController : ApiController
{
    [Route("api/MyContoller/{idvalue}")]
    [HttpGet]
    [HttpPost]
    public IHttpActionResult MyControllerMethod(intidvalue)
    {
    }
}

WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig:

 public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.MapRoute(
        //        name: "Default",
        //        url: "{controller}/{action}/{id}",
        //        defaults: new { action = "Index", id = UrlParameter.Optional }
        //    );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Body:
Found the solution. In my RouteConfig.cs if I comment out the line:

controller = "Home",

it works just fine.

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.MapRoute(
        //        name: "Default",
        //        url: "{controller}/{action}/{id}",
        //        defaults: new { action = "Index", id = UrlParameter.Optional }
        //    );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                //controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

However, I'm not completely sure why this is. So if anyone is able to explain it to me that would be great!


问:
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

答:
Algorithmically it is correct to check possible factors up to the square root of your target.

If N is a number that may or may not be prime, if there are no factors (not including 1) up to sqrt(N) then N must be prime. sqrt(N) itself may well be its only prime factor (eg 9 which is 3*3).

If we are going to test to see if 17 is prime, we know that sqrt(17) is just above 4. 2, 3 and 4 do not divide into 17 so it must be prime as 5 is greater.

This must be the case because 17/5 will be less than 5 and would have to be a factor too, but we know there are no factors less than 5.

Programmatically of course the code is not optimal, as you would not use doubles and square-roots but something like (i*i <= N)

Title: while (i<=sqrt(static_cast<double>(n))

Body:
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

while (i<=sqrt(static_cast<double>(n))

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.


问:
form submit message duplicated
I am submitting my form with ajax and jquery ,, but the problem is that the error message is duplicated on every time form submits . What could be the problem ?

js file

```<code>$(document).ready(function(e){
    $("#checkit").click(function(){
 var ID = $("#certcode").val();

      $.ajax({
    type: "POST",
    url: "/icac/cert-check-ajax.php",
    data: 'z='+ ID,
    success: function(data) {
          $("#datadisp").append(data);

         $('#certcode').val('');
         return false;
    }

        });
});
});
</code>```

php

```<code><?php
 include('/includes/db-connect.php');

if (!empty($_POST["z"]) ) {
    $z = $_POST["z"];
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = '$z'");

if( mysqli_num_rows($result) == 1) {

           echo '<div id="datadisp" class="alert alert-success" role="alert">Certificate Found</div';

}

    else {     echo '<div id="datadisp" class="alert alert-warning" role="alert">Invalid Security Code</div>';}
}
?>
</code>```

答:
I solved it by
  $("#datadisp").empty();
          $("#datadisp").html(data);</p>

Title: form submit message duplicated

Body:
I am submitting my form with ajax and jquery ,, but the problem is that the error message is duplicated on every time form submits . What could be the problem ?

js file

$(document).ready(function(e){
    $("#checkit").click(function(){
 var ID = $("#certcode").val();

      $.ajax({
    type: "POST",
    url: "/icac/cert-check-ajax.php",
    data: 'z='+ ID,
    success: function(data) {
          $("#datadisp").append(data);

         $('#certcode').val('');
         return false;
    }

        });
});
});

php

<?php
 include('/includes/db-connect.php');

if (!empty($_POST["z"]) ) {
    $z = $_POST["z"];
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = '$z'");

if( mysqli_num_rows($result) == 1) {

           echo '
Certificate Found


问:
Lucene search using Kibana does return my results
Using Kibana, I have created the following index:

```<code>put newsindex
{
  "settings" : {
    "number_of_shards":3,
    "number_of_replicas":2
  },
  "mappings" : {
    "news": {
      "properties": {
        "NewsID": {
          "type": "integer"
        },
        "NewsType": {
          "type": "text"
        },
        "BodyText": {
          "type": "text"
        },
        "Caption": {
          "type": "text"
        },
        "HeadLine": {
          "type": "text"
        },
        "Approved": {
          "type": "text"
        },
        "Author": {
          "type": "text"
        },
        "Contact": {
          "type": "text"
        },
        "DateCreated": {
          "type": "date",
          "format": "date_time"
        },
        "DateSubmitted": {
          "type": "date",
          "format": "date_time"
        },
        "LastModifiedDate": {
          "type": "date",
          "format": "date_time"
        }
      }
    }
  }
}
</code>```

I have populated the index with Logstash. If I just perform a match_all query, all my records are returned as you'd expect. However, when I try to perform a targeted query such as:

```<code>get newsindex/_search
{
    "query":{"match": {"headline": "construct abnomolies"}
            }
}
</code>```

I can see headline as a property of _source, but my query is ignored i.e. I still receive everything, regardless of whats in the headline. How do I need to change my index to make headline searchable. I'm using Elasticsearch 5.6.3

答: I needed to change the name property on my index to be lowercase. I noticed in the output windows the the properties under _source where lowercase. In Kibana the predictive text was offering my notation and lowercase. I've dropped my index and re-populated and it now works.</p>

Body:
Using Kibana, I have created the following index:

put newsindex
{
  "settings" : {
    "number_of_shards":3,
    "number_of_replicas":2
  },
  "mappings" : {
    "news": {
      "properties": {
        "NewsID": {
          "type": "integer"
        },
        "NewsType": {
          "type": "text"
        },
        "BodyText": {
          "type": "text"
        },
        "Caption": {
          "type": "text"
        },
        "HeadLine": {
          "type": "text"
        },
        "Approved": {
          "type": "text"
        },
        "Author": {
          "type": "text"
        },
        "Contact": {
          "type": "text"
        },
        "DateCreated": {
          "type": "date",
          "format": "date_time"
        },
        "DateSubmitted": {
          "type": "date",
          "format": "date_time"
        },
        "LastModifiedDate": {
          "type": "date",
          "format": "date_time"
        }
      }
    }
  }
}

I have populated the index with Logstash. If I just perform a match_all query, all my records are returned as you'd expect. However, when I try to perform a targeted query such as:

get newsindex/_search
{
    "query":{"match": {"headline": "construct abnomolies"}
            }
}

I can see headline as a property of _source, but my query is ignored i.e. I still receive everything, regardless of whats in the headline. How do I need to change my index to make headline searchable. I'm using Elasticsearch 5.6.3


问:
How to hide the soft navigation bar(virtual buttons) of android device for whole application?
I want to hide the soft navigational bar i.e. virtual buttons of android device for whole app. I have used below code snippet

```<code>getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
</code>```

to hide it but when i slide gridview it will become visible .

答:
```<code>View decorView = getWindow().getDecorView();
</code>```

<p>// Hide both the navigation bar and the status bar.</p>

```<code>int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
</code>```

Body:
I want to hide the soft navigational bar i.e. virtual buttons of android device for whole app. I have used below code snippet

getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

to hide it but when i slide gridview it will become visible .

Body:
View decorView = getWindow().getDecorView();

// Hide both the navigation bar and the status bar.

int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);


问:
MKMapitem's Placemark.name is nil when creating MKMapItem from MKPlacemark
```<code>MKPlacemark *placemark1 = [[MKPlacemark alloc] initWithPlacemark:mapItem1.placemark];

MKMapItem *item = [[MKMapItem alloc] initWithPlacemark:placemark1];

NSLog(@"placemark1.name is - %@", placemark1.name)
</code>```

placemark1.name is - Starbucks

```<code>NSLog(@"mapItem1's placemark.name is - %@", mapItem1.placemark.name)
</code>```

mapItem1's placemark.name is - Starbucks

```<code>NSLog(@"item's placemark.name is - %@", item.placemark.name)
</code>```

item's placemark.name is - nil

mapItem1 has the proper value. mapItem1.placemark.name is @"Startbucks".

When I implement like the above, item.placemark.name is nil.
But placemark1.name is @"Sartbucks".

When I made MKMapItem by another MKPlacemark, it also place mark.name in this MKMapItem is nil.

I don't know why these result has returned.

I think the same value of original placemark has to be returned.

答:
I notice if you assign the name of MapItem, the placemark would show the name.</p>

```<code>extension MKPlacemark {
    var toMapItem: MKMapItem {
        let item = MKMapItem(placemark: self)
        item.name = name
        return item
    }
}
</code>```

Body:
MKPlacemark *placemark1 = [[MKPlacemark alloc] initWithPlacemark:mapItem1.placemark];

MKMapItem *item = [[MKMapItem alloc] initWithPlacemark:placemark1];

NSLog(@"placemark1.name is - %@", placemark1.name)

placemark1.name is - Starbucks

NSLog(@"mapItem1's placemark.name is - %@", mapItem1.placemark.name)

mapItem1's placemark.name is - Starbucks

NSLog(@"item's placemark.name is - %@", item.placemark.name)

item's placemark.name is - nil

mapItem1 has the proper value. mapItem1.placemark.name is @"Startbucks".

When I implement like the above, item.placemark.name is nil.
But placemark1.name is @"Sartbucks".

When I made MKMapItem by another MKPlacemark, it also place mark.name in this MKMapItem is nil.

I don't know why these result has returned.

I think the same value of original placemark has to be returned.

Body:
I notice if you assign the name of MapItem, the placemark would show the name.

extension MKPlacemark {
    var toMapItem: MKMapItem {
        let item = MKMapItem(placemark: self)
        item.name = name
        return item
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to redirect to last link after login from google in php?
I am trying to redirect the user to the last link after login through Gmail or Facebook.

Here are the four things I tried without success.

1) Using $_SERVER['HTTP_REFERER'] But it redirects me back to Gmail instead of the last link on my site.

2) Using $_SESSION - I try to store last url in session before login but after login I don't get its value as session is empty.

3) Using cookies - I also try using cookies but it is also not working

4) I try to send the last url as $_GET parameter in redirect url but doing that stops google login as that url does not match the url stored in google apps.

Is there any other way to achieve this?

答:
I can't see why using cookies wouldn't work. Before redirecting the user to the Authorization Server, store the current URL in a cookie. When the AS redirects the user back to the redirect_uri, that page does another redirect to the URL stored in the cookie.

But I like the version where you include the "last page URL" in the request better (the 4th element on your list). Since Google apparently doesn't allow wildcards in their OAuth configuration, you can use the state parameter instead. From RFC 6749 - The OAuth 2.0 Authorization Framework:

```<code>state
     RECOMMENDED.  An opaque value used by the client to maintain
     state between the request and callback.  The authorization
     server includes this value when redirecting the user-agent back
     to the client.  The parameter SHOULD be used for preventing
     cross-site request forgery as described in Section 10.12.
</code>```

When you build your redirect URL, you just set the state parameter like so:

```<code>https://accounts.google.com/o/oauth2/v2/auth
    ?client_id=MY_CLIENT_ID
    &redirect_uri=http://example.com/oauth-redirect_uri
    &scope=REQUESTED_SCOPES
    &state=http://example.com/last-page-the-user-loaded
</code>```

Depending on your OAuth flow, the Authorization server will redirect the user to an URL that looks somewhat like this upon successful authorization:

```<code>http://example.com/oauth-redirect_uri
    ?code=CODE
    &state=http://example.com/last-page-the-user-loaded
</code>```

Your server can then process the state parameter and redirect the user accordingly.

Body:
I can't see why using cookies wouldn't work. Before redirecting the user to the Authorization Server, store the current URL in a cookie. When the AS redirects the user back to the redirect_uri, that page does another redirect to the URL stored in the cookie.

But I like the version where you include the "last page URL" in the request better (the 4th element on your list). Since Google apparently doesn't allow wildcards in their OAuth configuration, you can use the state parameter instead. From RFC 6749 - The OAuth 2.0 Authorization Framework:

state
     RECOMMENDED.  An opaque value used by the client to maintain
     state between the request and callback.  The authorization
     server includes this value when redirecting the user-agent back
     to the client.  The parameter SHOULD be used for preventing
     cross-site request forgery as described in Section 10.12.

When you build your redirect URL, you just set the state parameter like so:

https://accounts.google.com/o/oauth2/v2/auth
    ?client_id=MY_CLIENT_ID
    &redirect_uri=http://example.com/oauth-redirect_uri
    &scope=REQUESTED_SCOPES
    &state=http://example.com/last-page-the-user-loaded

Depending on your OAuth flow, the Authorization server will redirect the user to an URL that looks somewhat like this upon successful authorization:

http://example.com/oauth-redirect_uri
    ?code=CODE
    &state=http://example.com/last-page-the-user-loaded

Your server can then process the state parameter and redirect the user accordingly.


问:
WCF Endpoints determine which Auth method called
From inside a WCF Service can I determine the authentication method which called the service?

For example;

```<code>if (Forms Authentication) {
  //do something
}

if (WindowsAuthentication) {
  //do something else
}
</code>```

答:
You can inspect the ServiceSecurityContext on the OperationContext inside your WCF service class, and from that, you can determine how the user was authenticated (if at all).

```<code>ServiceSecurityContext security =
      OperationContext.Current.ServiceSecurityContext;
</code>```

Now you might have one of these on the security context:

PrimaryIdentity. Contains the identity claim from the claim set, as a traditional IIdentity reference.

WindowsIdentity. Contains the identity claim from the claim set if it is a WindowsIdentity.

If you have other authentication mechanisms (like certificates, or federated authentication), your PrimaryIdentity will contain a suitable identity for that mechanism.

See the Fundamentals of WCF Security (link to page 3) for a great discussion of this topic.

Body:
From inside a WCF Service can I determine the authentication method which called the service?

For example;

if (Forms Authentication) {
  //do something
}

if (WindowsAuthentication) {
  //do something else
}

Body:
You can inspect the ServiceSecurityContext on the OperationContext inside your WCF service class, and from that, you can determine how the user was authenticated (if at all).

ServiceSecurityContext security =
      OperationContext.Current.ServiceSecurityContext;

Now you might have one of these on the security context:

PrimaryIdentity. Contains the identity claim from the claim set, as a traditional IIdentity reference.

WindowsIdentity. Contains the identity claim from the claim set if it is a WindowsIdentity.

If you have other authentication mechanisms (like certificates, or federated authentication), your PrimaryIdentity will contain a suitable identity for that mechanism.

See the Fundamentals of WCF Security (link to page 3) for a great discussion of this topic.


问:
React - JSX conditional tags
I have a Todo component. My ToDoContainer downloads all the todos using fetch. The response looks like the following:

```<code>[
    { id: 0, checked: 1, text: "bla bla" },
    { id: 1, checked: 0, text: "bla bla 2" }
]
</code>```

After successfully getting my todos, I'm passing them down from TodoContainer to Todo component which renders them.

Unfortunately I can't make it work:

```<code><li>
    <input type="checkbox" />
    { this.props.text }
</li>
</code>```

How do I pass the info about the checkbox being checked or not?

I've tried:

```<code><li>
    <input type="checkbox" {this.props.checked ? 'not', 'working') />
    { this.props.text }
</li>
</code>```

But it looks like you can't use {} within tags in JSX?

The official guide isn't helpful either, because doing something like:

```<code>render() {
    let todoInput = null;
    if (this.props.checked) {
        todoInput = '<input type="checkbox" checked />';
    }
    else {
        todoInput = '<input type="checkbox"/>';
    }

    return (
        <li>
            { todoInput } { this.props.text }
        </li>
    );
}
</code>```

Won't work as it just renders the HTML (not the input itself) and I do not want to create new component just for that or to dangerously set HTML.

Any hints? :(

答:
You can use :

```<code><input type="checkbox" checked={this.props.checked} />
</code>```

OR

Remove single quotes

From :

```<code>todoInput = '<input type="checkbox" checked />';
</code>```

Like this :

```<code>todoInput = <input type="checkbox" checked />;
</code>```

OR

Conditional tags :

```<code>this.props.checked ? <CompA /> : <CompB />;
</code>```

Title: React - JSX conditional tags

Body:
I have a Todo component. My ToDoContainer downloads all the todos using fetch. The response looks like the following:

[
    { id: 0, checked: 1, text: "bla bla" },
    { id: 1, checked: 0, text: "bla bla 2" }
]

After successfully getting my todos, I'm passing them down from TodoContainer to Todo component which renders them.

Unfortunately I can't make it work:

    <input type="checkbox" />
    { this.props.text }

How do I pass the info about the checkbox being checked or not?

I've tried:

    <input type="checkbox" {this.props.checked ? 'not', 'working') />
    { this.props.text }

But it looks like you can't use {} within tags in JSX?

The official guide isn't helpful either, because doing something like:

render() {
    let todoInput = null;
    if (this.props.checked) {
        todoInput = '<input type="checkbox" checked />';
    }
    else {
        todoInput = '<input type="checkbox"/>';
    }

    return (

            { todoInput } { this.props.text }

    );
}

Won't work as it just renders the HTML (not the input itself) and I do not want to create new component just for that or to dangerously set HTML.

Any hints? :(

Body:
You can use :

<input type="checkbox" checked={this.props.checked} />

OR

Remove single quotes

From :

todoInput = '<input type="checkbox" checked />';

Like this :

todoInput = <input type="checkbox" checked />;

OR

Conditional tags :

this.props.checked ? <CompA /> : <CompB />;


问:
css: how to "center" a big image inside limited width and height without changing dimensions
before anything: No I don't mean centering an image inside a div

WHAT I WANT TO DO IS SIMILAR TO THE DESKTOP 'CENTER' OPTION HENCE THE TITLE PLEASE DON'T BE CONFUSED I JUST DON'T KNOW THE SUITABLE TERM OF WHAT I WANT

I am making a certian css template for my use, but I have this question that I couldn't figure out ..

basically, there is an image before each post, so the width is known. I set it to 100% of a container called "post". post has a width of 75% of the browser

```<code><div class="post">
  <h1>post title</h1>
  <img class="post-img" src="myImg.png" />
  <!--other elements-->
</div>
</code>```

css:

```<code>.post {
  width: 75%;
.post-img {
  max-width: 100%;
}
</code>```

Now to the problem ..
although the width now is fixed regardless of the image, the height is pretty much automatic

I want to set the height to a certain value, like max-height: 500px; for example .. so when a picture is big:

make width = 100% of the post div

is the height > 500px? no then make it auto. yes then crop the extra part

an image

as you can see, the black stroke is the limited width and height

the width was checked first so no extra parts to the left and right

the height is more than 500px, so it will be cropped and the viewed image would be the one inside the black frame

答:
Like i said overflow:hidden; is the one you need

.container{
width: 700px;
}

.post {
width: 75%;
overflow:hidden;
border:2px solid #f63;
}

.post img{
max-width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="post">
  <h1>post title</h1>
  <img class="post-img" src="http://www.petsworld.in/blog/wp-content/uploads/2014/09/adorable-cat.jpg" />
  <!--other elements-->
</div>
</div></code>```

Body:
before anything: No I don't mean centering an image inside a div

WHAT I WANT TO DO IS SIMILAR TO THE DESKTOP 'CENTER' OPTION HENCE THE TITLE PLEASE DON'T BE CONFUSED I JUST DON'T KNOW THE SUITABLE TERM OF WHAT I WANT

I am making a certian css template for my use, but I have this question that I couldn't figure out ..

basically, there is an image before each post, so the width is known. I set it to 100% of a container called "post". post has a width of 75% of the browser

post title

css:

.post {
  width: 75%;
.post-img {
  max-width: 100%;
}

Now to the problem ..
although the width now is fixed regardless of the image, the height is pretty much automatic

I want to set the height to a certain value, like max-height: 500px; for example .. so when a picture is big:

make width = 100% of the post div

is the height > 500px? no then make it auto. yes then crop the extra part

an image

as you can see, the black stroke is the limited width and height

the width was checked first so no extra parts to the left and right

the height is more than 500px, so it will be cropped and the viewed image would be the one inside the black frame

Body:
Like i said overflow:hidden; is the one you need

.container{
width: 700px;
}

.post {
width: 75%;
overflow:hidden;
border:2px solid #f63;
}

.post img{
max-width: 100%;
}

<div class="container">
<div class="post">
  <h1>post title</h1>
  <img class="post-img" src="http://www.petsworld.in/blog/wp-content/uploads/2014/09/adorable-cat.jpg" />
  <!--other elements-->
</div>
</div>


问:
Redirect WooCommerce Shop
I am using WooCommerce on my webshop. I bought a new domain where I made a 301 redirect from my old page to the new page.

https://old-domain.dk/ redirect to https://new-domain.dk/

I forgot one thing.. I have to redirect the WooCommerce shop aswell.

https://old-domain.dk/shop has to redirect to https://new-domain.dk/shop

But I have around 1000 products in my shop. So I do not want to just redirect to the main page of my new site. Fx:

https://old-domain.dk/shop/furnitures should redirect to https://new-domain.dk/shop/furnitures.

Is there anyway that I can redirect all my products in the shop at once to the new site, or do I have to do that one by one?

Update
I can see my question has been marked as the question already has been answered in other question. I am well aware of how to make a 402 redirect. But on a wordpress website you have to domains on your shop. https://old-domain.dk and https://old-domain.dk/shop/. The normal domain is redirecting, but the /shop domain I do not know how to redirect in .Htaccess.

I tried to set the redirect in .Htaccess - public_html- But this is not working.

Best Regards.

答:
I guess this .htaccess config will do that

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^old-domain.dk [NC,OR]
RewriteCond %{HTTP_HOST} ^www.old-domain.dk [NC]
RewriteRule ^(.*)$ http://new-domain.dk/$1 [L,R=301,NC]
</code>```

I think a minimal config like this will also work.

```<code>RewriteEngine On
RewriteRule ^(.*)$ http://new-domain.dk/$1 [R=301]
</code>```

Cheers.

Title: Redirect WooCommerce Shop

Body:
I guess this .htaccess config will do that

RewriteEngine on
RewriteCond %{HTTP_HOST} ^old-domain.dk [NC,OR]
RewriteCond %{HTTP_HOST} ^www.old-domain.dk [NC]
RewriteRule ^(.*)$ http://new-domain.dk/$1 [L,R=301,NC]

I think a minimal config like this will also work.

RewriteEngine On
RewriteRule ^(.*)$ http://new-domain.dk/$1 [R=301]

Cheers.


答:
First you aggregate the images:

```<code>SELECT
    imgpostid,
    LISTAGG(url, ', ') WITHIN GROUP (ORDER BY url) "imgs"
FROM Images
GROUP BY imgpostid
</code>```

Then add the users

SQL DEMO

```<code>WITH i as (
  SELECT "imgpostid",
          LISTAGG("url", ', ') WITHIN GROUP (ORDER BY "url") "imgs"
  FROM Images
  GROUP BY "imgpostid"
)
SELECT p."message", i."imgs" as images
FROM post p
LEFT JOIN users u
   ON p."postuserid" = u."userid"
LEFT JOIN i
   ON p."postid" = i."imgpostid"
;
</code>```

Title: How to combine post table and image table using sql left join and union

Body:
How do i combine 3 tables user table, post table and image table to display post with image and post without image
using sql inner join, left join and union.

Table Users

userid | uname |  pagename
-------|-------|-----
801    | peter |  a1
2      | john  |

Table Post

postid | postuserid | message
-------|------------|--------------
10     |  801       | This is post without image
101    |  801       | This is post with 2 images
102    |  801       | This is post with 1 image

Table Images

img | imgpostid | url
----|-----------|------------
1   | 101       | image1.png
2   | 101       | image2.png
3   | 102       | image01.png

My SQL Query

SELECT * FROM Post pt
INNER JOIN Users us
ON pt.postuserid = us.userid
LEFT JOIN Images im
ON pt.postid = im.imgpostid
WHERE us.pagename = 'a1'
AND us.userid = 801

Expected result

This is post without image
This is post with 2 images [IMAGE1.PNG],[IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

The result i get

This is post without image
This is post with 2 images [IMAGE2.PNG]
This is post with 2 images [IMAGE2.PNG]
This is post with 1 image [IMAGE01.PNG]

Body:
First you aggregate the images:

SELECT
    imgpostid,
    LISTAGG(url, ', ') WITHIN GROUP (ORDER BY url) "imgs"
FROM Images
GROUP BY imgpostid

Then add the users

SQL DEMO

WITH i as (
  SELECT "imgpostid",
          LISTAGG("url", ', ') WITHIN GROUP (ORDER BY "url") "imgs"
  FROM Images
  GROUP BY "imgpostid"
)
SELECT p."message", i."imgs" as images
FROM post p
LEFT JOIN users u
   ON p."postuserid" = u."userid"
LEFT JOIN i
   ON p."postid" = i."imgpostid"
;


问:
Collapse multiple lines when reading flat file in python
I want to parse a flat file that looks like this in python;

```<code>  Element ID     Element Type     Result       Jacobian Sign

============== ================= ========= =====================
      1            Parabolic      Warning          1.000000
                  Hexahedron
      2            Parabolic      Warning          1.000000
                  Hexahedron
      3            Parabolic      Warning          1.000000
                  Hexahedron
      4            Parabolic      Warning          1.000000
</code>```

I tried using the mechanism used in this answer as follows;

```<code>import pandas as pd

def parse_file(file):
    col_spec = [(0, 15), (16, 33), (34, 43), (44, 65)]
    return pd.read_fwf(file, colspecs=col_spec)
</code>```

But it reads one record for the top row and one row which is empty apart from the word 'Hexahedron' as the element type.

```<code>>>> data = parse_file("example.txt")
>>> data.head()
       Element ID      Element Type    Result         Jacobian Sign
0             NaN               NaN       NaN                   NaN
1  ==============  ================  ========  ====================
2               1         Parabolic   Warning              1.000000
3             NaN        Hexahedron       NaN                   NaN <= Extra record
4               2         Parabolic   Warning              1.000000
</code>```

As you can see from lines, the first two rows are captured as 2 records (records 2 and 3). I want the parser to capture the first two rows as one record, so that the phrase 'Parabolic Hexahedron' is captured as the element type. How can I do this?

答:
some post-processing should do the trick. Here is some code using the shift operator. Also notice that opening the file is not required, just pass the filename to pd.read_fwf.

```<code>import pandas as pd

col_spec = [(0, 15), (15, 32), (32, 42), (43, 65)]
df = pd.read_fwf("example.txt", colspecs=col_spec, comment="=")

# combine rows
df["combined"] = (df['Element Type'] + df['Element Type'].shift(-1)).where(df['Element ID'].notnull(), df['Element Type'] )
# remove extra rows
df = df[df['Element ID'].notnull()]
</code>```

this should give a DataFrame that looks like this:

```<code>  Element ID Element Type   Result Jacobian Sign             combined
2          1    Parabolic  Warning      1.000000  ParabolicHexahedron
4          2    Parabolic  Warning      1.000000  ParabolicHexahedron
6          3    Parabolic  Warning      1.000000  ParabolicHexahedron
8          4    Parabolic  Warning      1.000000  ParabolicHexahedron
</code>```

Body:
I want to parse a flat file that looks like this in python;

  Element ID     Element Type     Result       Jacobian Sign

============== ================= ========= =====================
      1            Parabolic      Warning          1.000000
                  Hexahedron
      2            Parabolic      Warning          1.000000
                  Hexahedron
      3            Parabolic      Warning          1.000000
                  Hexahedron
      4            Parabolic      Warning          1.000000

I tried using the mechanism used in this answer as follows;

import pandas as pd

def parse_file(file):
    col_spec = [(0, 15), (16, 33), (34, 43), (44, 65)]
    return pd.read_fwf(file, colspecs=col_spec)

But it reads one record for the top row and one row which is empty apart from the word 'Hexahedron' as the element type.

>>> data = parse_file("example.txt")
>>> data.head()
       Element ID      Element Type    Result         Jacobian Sign
0             NaN               NaN       NaN                   NaN
1  ==============  ================  ========  ====================
2               1         Parabolic   Warning              1.000000
3             NaN        Hexahedron       NaN                   NaN <= Extra record
4               2         Parabolic   Warning              1.000000

As you can see from lines, the first two rows are captured as 2 records (records 2 and 3). I want the parser to capture the first two rows as one record, so that the phrase 'Parabolic Hexahedron' is captured as the element type. How can I do this?

Body:
some post-processing should do the trick. Here is some code using the shift operator. Also notice that opening the file is not required, just pass the filename to pd.read_fwf.

import pandas as pd

col_spec = [(0, 15), (15, 32), (32, 42), (43, 65)]
df = pd.read_fwf("example.txt", colspecs=col_spec, comment="=")

# combine rows
df["combined"] = (df['Element Type'] + df['Element Type'].shift(-1)).where(df['Element ID'].notnull(), df['Element Type'] )
# remove extra rows
df = df[df['Element ID'].notnull()]

this should give a DataFrame that looks like this:

  Element ID Element Type   Result Jacobian Sign             combined
2          1    Parabolic  Warning      1.000000  ParabolicHexahedron
4          2    Parabolic  Warning      1.000000  ParabolicHexahedron
6          3    Parabolic  Warning      1.000000  ParabolicHexahedron
8          4    Parabolic  Warning      1.000000  ParabolicHexahedron