问:
Javascript - A function that accepts parameter and return a string which contains "x"
```<code>function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);
</code>```

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.

答:
You could declare a new Array and use Array.prototype.join, similar to the below:

function change(o)
{
  return new Array(o+1).join('x')
}

console.log(change(5));
console.log(change(9));```
</div>
</div>
</p>

<p>Or if you don't have to support Internet Explorer you could use <strong>String.prototype.repeat()</strong>, similar to the below:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function change(o)
{
  return 'x'.repeat(o);
}

console.log(change(5));
console.log(change(9));</code>```

Body:
function change(o)
{
  var str = "";
  for (var p = 0; p<=o ;p++)
  {
    temp = p;
    str = str + temp;
    if (p == o){
    }
    else{
      str = str + ",";
    }
  }
console.log(str);
}
change(5);

(consolelog will be changed into return, it's just to view the output)

Basically, I am a beginner who recently started and I wanted to make a simple function that returns a value of the function. For example; if change(5) was inputted, it would return a string value of 5 x's, so xxxxx. If it was change(7), it would return me xxxxxxx, so any idea how to do this? Because my code only gives value from 0 to my inputted value.

Body:
You could declare a new Array and use Array.prototype.join, similar to the below:

function change(o)
{
  return new Array(o+1).join('x')
}

console.log(change(5));
console.log(change(9));

Or if you don't have to support Internet Explorer you could use String.prototype.repeat(), similar to the below:

function change(o)
{
  return 'x'.repeat(o);
}

console.log(change(5));
console.log(change(9));


来源: stackexchange

问:
Mercurial: How to jump back to previous hash? Equivalent of `cd -`
In mercurial, is there a quick way to jump back to the previous hash without typing that hash?

For example if I am at hash abc123 and then do hg update def456, is there a quick generic mercurial command to jump back to abc123 without having to remember I was at abc123?

I'm looking for something analogous to bash's cd - which takes you to the last directory you cd'd out of without having to type out that directory explicitly.

If there isn't one, is it easy to write a little extension where I can type something like hg update - and it will do this? It would be very useful as I jump around a lot.

Thanks!

答:
Mercurial has - at least by default - no provisions to memorize the history of the checked-out revisions.

I also wouldn't count on a completely brain dead way to exist.

I'd first try to hack this feature by means of a hook to hg update where I check the parameter for the special case of '-' and replace it by a stored value. And if update is called without that special value, I'd try to store it in that very file I retrieve it from. But I cannot guarantee that such approach will work.

ContentLicense: CC BY-SA 3.0


问:
Getting fortnight from timestamp in Postgres
I'm doing some cohort analysis and want to see for a group of customers in November, how many transact weekly, fortnightly, and monthly; and for how long

I have this for the week and month (weekly example):

```<code>WITH weekly_users AS (
SELECT user_fk
     , DATE_TRUNC('week',created_at) AS week
     , (DATE_PART('year', created_at) - 2016) * 52 + DATE_PART('week', created_at) - 45 AS weeks_between
  FROM transactions
    WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
      GROUP BY user_fk, week, weeks_between
),

t2 AS (
  SELECT weekly_users.*
     , COUNT(*) OVER (PARTITION BY user_fk
                          ORDER BY week ROWS BETWEEN UNBOUNDED PRECEDING
                                                  AND 1 PRECEDING) AS prev_rec_cnt
  FROM weekly_users
)
SELECT week
     , COUNT(*)
  FROM t2
 WHERE weeks_between = prev_rec_cnt
 GROUP BY week
 ORDER BY week;
</code>```

But weekly is too little of an interval, and monthly too much. So I want fortnight. Has anyone done this before? From Googling it seems like a challenge

Thanks in advance

答:
Just worked it out, this is how you'd do it:

```<code>WITH fortnightly_users AS (
    SELECT user_fk
         , EXTRACT(YEAR FROM created_at) * 100 + CEIL(EXTRACT(WEEK FROM created_at)/2) AS fortnight
         , (EXTRACT(YEAR FROM created_at) - 2016) * 26 + CEIL(EXTRACT(WEEK FROM created_at)/2) - 23 AS fortnights_between
      FROM transactions
        WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
          GROUP BY user_fk, fortnight, fortnights_between
    ),

    t2 AS (
      SELECT fortnightly_users.*
         , COUNT(*) OVER (PARTITION BY user_fk
                              ORDER BY fortnight ROWS BETWEEN UNBOUNDED PRECEDING
                                                      AND 1 PRECEDING) AS prev_rec_cnt
      FROM fortnightly_users
    )
    SELECT fortnight
         , COUNT(*)
      FROM t2
     WHERE fortnights_between = prev_rec_cnt
     GROUP BY fortnight
     ORDER BY fortnight;
</code>```

So you get the week number, then divide by 2. Rounding up to avoid fractional numbers for fortnights

Body:
I'm doing some cohort analysis and want to see for a group of customers in November, how many transact weekly, fortnightly, and monthly; and for how long

I have this for the week and month (weekly example):

WITH weekly_users AS (
SELECT user_fk
     , DATE_TRUNC('week',created_at) AS week
     , (DATE_PART('year', created_at) - 2016) * 52 + DATE_PART('week', created_at) - 45 AS weeks_between
  FROM transactions
    WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
      GROUP BY user_fk, week, weeks_between
),

t2 AS (
  SELECT weekly_users.*
     , COUNT(*) OVER (PARTITION BY user_fk
                          ORDER BY week ROWS BETWEEN UNBOUNDED PRECEDING
                                                  AND 1 PRECEDING) AS prev_rec_cnt
  FROM weekly_users
)
SELECT week
     , COUNT(*)
  FROM t2
 WHERE weeks_between = prev_rec_cnt
 GROUP BY week
 ORDER BY week;

But weekly is too little of an interval, and monthly too much. So I want fortnight. Has anyone done this before? From Googling it seems like a challenge

Thanks in advance

Body:
Just worked it out, this is how you'd do it:

WITH fortnightly_users AS (
    SELECT user_fk
         , EXTRACT(YEAR FROM created_at) * 100 + CEIL(EXTRACT(WEEK FROM created_at)/2) AS fortnight
         , (EXTRACT(YEAR FROM created_at) - 2016) * 26 + CEIL(EXTRACT(WEEK FROM created_at)/2) - 23 AS fortnights_between
      FROM transactions
        WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
          GROUP BY user_fk, fortnight, fortnights_between
    ),

    t2 AS (
      SELECT fortnightly_users.*
         , COUNT(*) OVER (PARTITION BY user_fk
                              ORDER BY fortnight ROWS BETWEEN UNBOUNDED PRECEDING
                                                      AND 1 PRECEDING) AS prev_rec_cnt
      FROM fortnightly_users
    )
    SELECT fortnight
         , COUNT(*)
      FROM t2
     WHERE fortnights_between = prev_rec_cnt
     GROUP BY fortnight
     ORDER BY fortnight;

So you get the week number, then divide by 2. Rounding up to avoid fractional numbers for fortnights


答:
You can do like this

function change(o)
{
  if(o>0){
    console.log(Array(parseInt(o)+1).join("x"));
  }else{
    console.log("Blank");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" onkeyup="change(this.value)"></code>```

Title: Javascript - A function that accepts parameter and return a string which contains "x"

Body:
You can do like this

function change(o)
{
  if(o>0){
    console.log(Array(parseInt(o)+1).join("x"));
  }else{
    console.log("Blank");
  }
}

<input type="number" onkeyup="change(this.value)">


问:
Open camera inside fragment
Is it possible to use camera in fragment like view, so that it wouldn't open another app and go away from my special app?

I want something like SurfaceView with camera?

答:
Native implementation is way better.

XML

```<code><com.google.android.cameraview.CameraView
android:id="@+id/camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:keepScreenOn="true"
android:adjustViewBounds="true"
app:autoFocus="true"
app:aspectRatio="4:3"
app:facing="back"
app:flash="auto"/>
</code>```

Inside Activity/Fragment

Start camera

```<code>  mCameraView.start();
</code>```

Stop camera

```<code>  mCameraView.stop();
</code>```

Open source: Google

Requires API Level 9. The library uses Camera 1 API on API Level 9-20 and Camera2 on 21 and above.

Title: Open camera inside fragment

Body:
Native implementation is way better.

XML

<com.google.android.cameraview.CameraView
android:id="@+id/camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:keepScreenOn="true"
android:adjustViewBounds="true"
app:autoFocus="true"
app:aspectRatio="4:3"
app:facing="back"
app:flash="auto"/>

Inside Activity/Fragment

Start camera

  mCameraView.start();

Stop camera

  mCameraView.stop();

Open source: Google

Requires API Level 9. The library uses Camera 1 API on API Level 9-20 and Camera2 on 21 and above.

ContentLicense: CC BY-SA 4.0


问:
Error and confusion when creating datatype and monad
Consider the next piece of code:

```<code>data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

data Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)

instance Monad Board where
    return x = x
    f >>= x = x
</code>```

I'd like that Board will be a monad. But the problem is that i get the following error -

```<code>[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:17:14: error:
    Illegal binding of built-in syntax: (,,,,,,,,)
</code>```

What needs to be changed so that Board can be defined later on as a monad

答:
Every data constructor must have an unambiguous name, such as you gave with EmptyTile, X, O, Player1 and Player2. With Board, there is no such name; Haskell desugars this as

```<code>data Board = (,,,,,,,,) Tile Tile Tile Tile Tile Tile Tile Tile Tile
</code>```

so here, (,,,,,,,,) would be the “constructor name”, but that's not actually legal in Haskell, thus the error.

Just choose a custom name, like boring

```<code>data Board = Board Tile Tile Tile Tile Tile Tile Tile Tile Tile
</code>```

Now, this cannot possibly be a monad: a monad is foremostly a functor, i.e. something that's parameterised on some type and covariant in that parameter. You can make it a monad though, by replacing those hard-coded Tile fields with something polymorphic:

```<code>data Board t = Board t t t t t t t t t
    deriving (Functor)
</code>```

But the Applicative and Monad instances will look a bit more involved than what you proposed.

You might consider an approach like this: instead of hand-rolling the Board data structure, you define an indexing type:

```<code>data BoardIndex = Edge0 | Middle | Edge1
type Board t = (BoardIndex, BoardIndex) -> t
</code>```

Then this will be a monad without any further definitions, namely the function monad, which has the semantics you probably want here. It tends to be a bit inefficient since results aren't actually stored but always recomputed on the spot, but for something like Tic Tac Toe that will hardly matter. (You can easily make it more efficient later, by introducing memoisation.)

Body:
Consider the next piece of code:

data Tile   = EmptyTile | X | O
data Player = Player1 | Player2

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

data Board = (Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile, Tile)

emptyBoard :: Board
emptyBoard = (EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile,EmptyTile)

instance Monad Board where
    return x = x
    f >>= x = x

I'd like that Board will be a monad. But the problem is that i get the following error -

[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:17:14: error:
    Illegal binding of built-in syntax: (,,,,,,,,)

What needs to be changed so that Board can be defined later on as a monad

Body:
Every data constructor must have an unambiguous name, such as you gave with EmptyTile, X, O, Player1 and Player2. With Board, there is no such name; Haskell desugars this as

data Board = (,,,,,,,,) Tile Tile Tile Tile Tile Tile Tile Tile Tile

so here, (,,,,,,,,) would be the “constructor name”, but that's not actually legal in Haskell, thus the error.

Just choose a custom name, like boring

data Board = Board Tile Tile Tile Tile Tile Tile Tile Tile Tile

Now, this cannot possibly be a monad: a monad is foremostly a functor, i.e. something that's parameterised on some type and covariant in that parameter. You can make it a monad though, by replacing those hard-coded Tile fields with something polymorphic:

data Board t = Board t t t t t t t t t
    deriving (Functor)

But the Applicative and Monad instances will look a bit more involved than what you proposed.

You might consider an approach like this: instead of hand-rolling the Board data structure, you define an indexing type:

data BoardIndex = Edge0 | Middle | Edge1
type Board t = (BoardIndex, BoardIndex) -> t

Then this will be a monad without any further definitions, namely the function monad, which has the semantics you probably want here. It tends to be a bit inefficient since results aren't actually stored but always recomputed on the spot, but for something like Tic Tac Toe that will hardly matter. (You can easily make it more efficient later, by introducing memoisation.)


问:
Which construction is faster?
Which construction is faster:

```<code>$a = $b * $c ? $b * $c : 0;
</code>```

or

```<code>$i = $b * $c;
$a = $i ? $i : 0;
</code>```

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

答:
If you have PHP 5.3, this is faster:

```<code>$a = $b * $c ?: 0;
</code>```

This is the same as $a = $b * $c ? $b * $c : 0;, but the $a*$b calcultation is done only once. Also, it doesn't do additional assignments as in your second solution.

Using Martin v. Löwis's benchmark script I get the following times:

```<code>$a = $b * $c ?: 0;               1.07s
$a = $b * $c ? $b * $c : 0;      1.16s
$i = $b * $c; $a = $i ? $i : 0;  1.39s
</code>```

Now these are micro-optimizations, so there is probably many ways of optimizing your code before doing this :)

If it is not the case, you may also want to compare generated PHP OP codes:

1 $a = $b * $c ? $b * $c : 0; :

```<code>number of ops:  8
compiled vars:  !0 = $a, !1 = $b, !2 = $c
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  JMPZ                                                     ~0, ->5
         2  MUL                                              ~1      !1($b), !2($c)
         3  QM_ASSIGN                                        ~2      ~1
         4  JMP                                                      ->6
         5  QM_ASSIGN                                        ~2      0
         6  ASSIGN                                                   !0($a), ~2
         7  RETURN                                                   null
</code>```

2 $i = $b * $c; $a = $i ? $i : 0;

```<code>number of ops:  8
compiled vars:  !0 = $i, !1 = $b, !2 = $c, !3 = $a
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  ASSIGN                                                   !0($i), ~0
         2  JMPZ                                                     !0($i), ->5
         3  QM_ASSIGN                                        ~2      !0($i)
         4  JMP                                                      ->6
         5  QM_ASSIGN                                        ~2      0
         6  ASSIGN                                                   !3($a), ~2
         7  RETURN                                                   null
</code>```

3 $a = $b * $c ?: 0; :

```<code>number of ops:  5
compiled vars:  !0 = $a, !1 = $b, !2 = $c
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  ZEND_JMP_SET                                     ~1      ~0
         2  QM_ASSIGN                                        ~1      0
         3  ASSIGN                                                   !0($a), ~1
         4  RETURN                                                   null
</code>```

These OP code listings was generated by the VLD extension.

ContentLicense: CC BY-SA 2.5

Title: Which construction is faster?

Body:
Which construction is faster:

$a = $b * $c ? $b * $c : 0;

or

$i = $b * $c;
$a = $i ? $i : 0;

All variables are local ones.

Does speed differs for mulitplication, addition, substraction and division?

Update:

Here's some clarification:

This is a theoretical question about writing speed-optimized code from scratch. Not about "searching bottlenecks".

I can measure code speed by myself. But it's was not a question about homework of using microtime(). It was a question about how PHP-interpreter works (what I tried to figure out by digging google myself but was unseccusfull).

Moreover - I did measuring with myself and was a little confused. Different starting values of $a, $b and $c (combinations of zeros, negative, positive, integer and floats) produce different results between constructions. So I was confused.

BoltClock provide me usefull info but user576875 made my day by posting a link to opcode decoder! His answer contains also direct answer to my question. Thanks!

Body:
If you have PHP 5.3, this is faster:

$a = $b * $c ?: 0;

This is the same as $a = $b * $c ? $b * $c : 0;, but the $a*$b calcultation is done only once. Also, it doesn't do additional assignments as in your second solution.

Using Martin v. Löwis's benchmark script I get the following times:

$a = $b * $c ?: 0;               1.07s
$a = $b * $c ? $b * $c : 0;      1.16s
$i = $b * $c; $a = $i ? $i : 0;  1.39s

Now these are micro-optimizations, so there is probably many ways of optimizing your code before doing this :)

If it is not the case, you may also want to compare generated PHP OP codes:

1 $a = $b * $c ? $b * $c : 0; :

number of ops:  8
compiled vars:  !0 = $a, !1 = $b, !2 = $c
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  JMPZ                                                     ~0, ->5
         2  MUL                                              ~1      !1($b), !2($c)
         3  QM_ASSIGN                                        ~2      ~1
         4  JMP                                                      ->6
         5  QM_ASSIGN                                        ~2      0
         6  ASSIGN                                                   !0($a), ~2
         7  RETURN                                                   null

2 $i = $b * $c; $a = $i ? $i : 0;

number of ops:  8
compiled vars:  !0 = $i, !1 = $b, !2 = $c, !3 = $a
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  ASSIGN                                                   !0($i), ~0
         2  JMPZ                                                     !0($i), ->5
         3  QM_ASSIGN                                        ~2      !0($i)
         4  JMP                                                      ->6
         5  QM_ASSIGN                                        ~2      0
         6  ASSIGN                                                   !3($a), ~2
         7  RETURN                                                   null

3 $a = $b * $c ?: 0; :

number of ops:  5
compiled vars:  !0 = $a, !1 = $b, !2 = $c
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   1     0  MUL                                              ~0      !1($b), !2($c)
         1  ZEND_JMP_SET                                     ~1      ~0
         2  QM_ASSIGN                                        ~1      0
         3  ASSIGN                                                   !0($a), ~1
         4  RETURN                                                   null

These OP code listings was generated by the VLD extension.


问:
AIX: change executable of a running program
I have a master process which forks & execs child processes with defined executable files.
Master and child processes are running infinite loops. Master restarts them if they stop.

Now I want to update the executable files of child processes. Something like:

1. copy new executable files

2. kill child processes (when they're idle)

3. master process restarts them with new executables

But simple cp "new_exec" "old_exec" returns error:

"Cannot open or remove a file containing a running program."

Question(s):

Can I use "cp -f new_file old_file"?

Would that affect old running processes (Is everything loaded into memory on process start)?

I am on AIX.

答:
Can I use "cp -f new_file old_file"?
  Would that affect old running processes (Is everything loaded into memory on process start)?

'No' and 'yes'. But, if you had asked how to solve this, I would say either:

```<code>rm /oldpath/exec
cp /newpath/exec /oldpath/exec
</code>```

or rather:

```<code>cp /newpath/exec /oldpath/exec_replace
mv /oldpath/exec_replace /oldpath/exec
</code>```

Body:
Can I use "cp -f new_file old_file"?
  Would that affect old running processes (Is everything loaded into memory on process start)?

'No' and 'yes'. But, if you had asked how to solve this, I would say either:

rm /oldpath/exec
cp /newpath/exec /oldpath/exec

or rather:

cp /newpath/exec /oldpath/exec_replace
mv /oldpath/exec_replace /oldpath/exec


问:
Adobe Animate CC file not playing when uploaded to server
I have some basic animate CC files that work when tested locally using a browser or preview in Dreamweaver; but when uploaded to my server does not play.
The files are all adapted from the same "template" which was the first animation I created which does work when uploaded. The output files are HTML5 canvas.

Not sure why the other files will not play. Any help would be greatly appreciated!

This is the URL to the working files and then below the problem one:
http://www.robertfitzroyacademy.com/rfa-w.html (portal URL- I am testing reception and year 1)
http://www.robertfitzroyacademy.com/rfaworld-reception.html (working animation)
http://www.robertfitzroyacademy.com/rfaworld-year1.html (problem animation)

I also have a dropbox with the files in: https://www.dropbox.com/s/6gq5v6m696jgtzx/HTML5%20animation%20issue.zip?dl=0

Many thanks in advance for any help you can give.
Hanniel

答:
I worked out the answer, I hadn't uploaded all the linked image files. Even though I had no new images as such, each time I generated a new fla file from the original it created a new image file linked to the new file.

Once I uploaded all the associated files the animation started playing.


问:
This operation is not supported in the environment…be http or https and web storage must be enabled
i am developing a hybrid mobile app in ionic framework using firebase and angularjs. When I try to login with twitter using signInWithPopup('twitter') in browser its works and it gives me a right userdata from twitter but in my android device i'm getting an error like below

code : auth/operation-not-supported-in-this-environment.  message :
  "This operation is not supported in the environment this application
  is running on. "location.protocol" must be http or https and web
  storage must be enabled."

i don't know how to solve this issue..

Thanks in advance

答:
signINWithPopup will work only in the browser it will not work in the ionic. Fire-base solved this problem in the fire-base version of 3.9.0 and please follow the below link and i got my app working fine with Facebook and google and twitter.

https://firebase.google.com/docs/auth/web/cordova


问:
Cannot connect to Postgres server running through brew services
I've been looking for a solution for this and could not find a working solution.

I've installed postgres using brew (brew install postgres)  in my MacBook and I am currently running it using brew services (brew services list  displays postgres as a running service). However, when I try to run psql I get following error.

psql: could not connect to server: No such file or directory  Is the
  server running locally and accepting  connections on Unix domain
  socket "/tmp/.s.PGSQL.5432"?

Anyone has already solved similar problem?

答:
I would combine the two answers from Wilson and Grasshopper here.

You can check the plist file for the postgres service using brew services list to find the location of the file and just opening it up in you favourite editor.

You should see the value of StandardErrorPath listed as:

```<code><key>StandardErrorPath</key>
<string>/usr/local/var/log/postgres.log</string>
</code>```

And then you should tail the end of the log file using tail -n 100 /usr/local/var/log/postgres.log

In my case the error was the following:

2017-12-06 11:51:16.078 GMT [85476] FATAL:  lock file "postmaster.pid" already exists
  2017-12-06 11:51:16.078 GMT [85476] HINT:  Is another postmaster (PID 601) running in data directory "/usr/local/var/postgres"?

This was because I had to hard shutdown my Mac and postgres didn't get a chance to cleanup the PID file. Just remove the PID file rm /usr/local/var/postgres/postmaster.pid and start postgres brew services start postgresql

A word of warning: do not delete this PID file unless you are sure that postgres is not running. You can do this by running brew services stop postgresql and then waiting for the result of brew services list to show posgres is in the stopped state.

Body:
I would combine the two answers from Wilson and Grasshopper here.

You can check the plist file for the postgres service using brew services list to find the location of the file and just opening it up in you favourite editor.

You should see the value of StandardErrorPath listed as:

<key>StandardErrorPath</key>
<string>/usr/local/var/log/postgres.log</string>

And then you should tail the end of the log file using tail -n 100 /usr/local/var/log/postgres.log

In my case the error was the following:

2017-12-06 11:51:16.078 GMT [85476] FATAL:  lock file "postmaster.pid" already exists
  2017-12-06 11:51:16.078 GMT [85476] HINT:  Is another postmaster (PID 601) running in data directory "/usr/local/var/postgres"?

This was because I had to hard shutdown my Mac and postgres didn't get a chance to cleanup the PID file. Just remove the PID file rm /usr/local/var/postgres/postmaster.pid and start postgres brew services start postgresql

A word of warning: do not delete this PID file unless you are sure that postgres is not running. You can do this by running brew services stop postgresql and then waiting for the result of brew services list to show posgres is in the stopped state.


问:
Filter results in ShinyApp
i have a shiny app Item Correlation which get the correlation between several products.
and i want to get only the values which's more than zero without removing the sorted results.
and  this's my server code:</p>

```<code>server <- function(input,output){
  data<- reactive({
    input$Item
  })
  output$Itemcorr <- renderTable({
    DF %>% filter(FirstItem == data())  %>% arrange(desc(X.Correlation))
  })

  output$plot <- renderPlot({
    barplot(subset(DF$X.Correlation, DF$FirstItem == data()),main="X.Correlation Distribution",
            xlab="SecondItems",ylab="Percent",xlim=c(1,60),ylim = c(0,100), col=c("darkblue","red"),names.arg =subset(DF$SecondItem, DF$FirstItem == data())
    )
  })
</code>```

答:
We can do a couple of things here,

1) create the second condition also in the same filter

2) In the reactive call we do the data subsetting

```<code>server <- function(input,output){

 data<- reactive({
    DF %>%
       filter(FirstItem == input$Item, X.Correlation > 0) %>%
       arrange(desc(X.Correlation))
    })

 output$Itemcorr <- renderTable({
    data()
  })

 output$plot <- renderPlot({
    barplot(data()$X.Correlation),main="X.Correlation Distribution",
            xlab="SecondItems",ylab="Percent",xlim=c(1,60),ylim = c(0,100),
    col=c("darkblue","red"),names.arg =data()$SecondItem)
    )
  })
</code>```

Title: Filter results in ShinyApp

Body:
i have a shiny app Item Correlation which get the correlation between several products.
and i want to get only the values which's more than zero without removing the sorted results.
and  this's my server code:

server <- function(input,output){
  data<- reactive({
    input$Item
  })
  output$Itemcorr <- renderTable({
    DF %>% filter(FirstItem == data())  %>% arrange(desc(X.Correlation))
  })

  output$plot <- renderPlot({
    barplot(subset(DF$X.Correlation, DF$FirstItem == data()),main="X.Correlation Distribution",
            xlab="SecondItems",ylab="Percent",xlim=c(1,60),ylim = c(0,100), col=c("darkblue","red"),names.arg =subset(DF$SecondItem, DF$FirstItem == data())
    )
  })

Body:
We can do a couple of things here,

1) create the second condition also in the same filter

2) In the reactive call we do the data subsetting

server <- function(input,output){

 data<- reactive({
    DF %>%
       filter(FirstItem == input$Item, X.Correlation > 0) %>%
       arrange(desc(X.Correlation))
    })

 output$Itemcorr <- renderTable({
    data()
  })

 output$plot <- renderPlot({
    barplot(data()$X.Correlation),main="X.Correlation Distribution",
            xlab="SecondItems",ylab="Percent",xlim=c(1,60),ylim = c(0,100),
    col=c("darkblue","red"),names.arg =data()$SecondItem)
    )
  })


问:
CSS flex layout and overflow: auto child
I'm trying to create a layout:

```<code><div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="">
       <div style="overflow: auto">
           <div style="min-width: 1000px"></div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div>
</code>```

As you can see, I need a three column layout with first and third column in fixed size. The second column should occupy rest of the space.

The problem is that inside the second column I need to display a large data table with optional scrollbar.

Is there any way how to accomplish this using flexbox?

The problem with my code is, that overflow: auto never works if I'm not specifying width of second child and whole layout ends up with width of 1800px. On the other side I cannot specify it because the second child is supposed to occupy rest of the space.

Thanks!

答:
In this case, with the existing markup untouched, the main reason is min-width, which for flex items defaults to auto and prevent them (here the second) from being smaller than its content.

Adding min-width: 0; to its style
 will fix that.

Stack snippet

...

 scrollabe

...

```
</div>
</div>
</p>

<hr>

<p>IE, being somewhat buggy, also need <code>display: flex</code> added to the <code>second</code>'s style, and one doesn't need an IE css hack here, since this works on the other browsers too.</p>

<p>Stack snippet</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="display: flex; min-width: 0;">
       <div style="overflow: auto;">
           <div style="min-width: 1000px; background: red;"> scrollabe</div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div></code>```

So finally, when the content in the second is smaller and should in such cases fill the remaining space, it will also need flex-grow: 1.

Stack snippet

...

 scrollabe

...

```

Body:
I'm trying to create a layout:

...

...

As you can see, I need a three column layout with first and third column in fixed size. The second column should occupy rest of the space.

The problem is that inside the second column I need to display a large data table with optional scrollbar.

Is there any way how to accomplish this using flexbox?

The problem with my code is, that overflow: auto never works if I'm not specifying width of second child and whole layout ends up with width of 1800px. On the other side I cannot specify it because the second child is supposed to occupy rest of the space.

Thanks!

Body:
In this case, with the existing markup untouched, the main reason is min-width, which for flex items defaults to auto and prevent them (here the second) from being smaller than its content.

Adding min-width: 0; to its style <div id="second" style="min-width: 0;"> will fix that.

Stack snippet

<div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="min-width: 0;">
       <div style="overflow: auto;">
           <div style="min-width: 1000px; background: red;"> scrollabe</div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div>

IE, being somewhat buggy, also need display: flex added to the second's style, and one doesn't need an IE css hack here, since this works on the other browsers too.

Stack snippet

<div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="display: flex; min-width: 0;">
       <div style="overflow: auto;">
           <div style="min-width: 1000px; background: red;"> scrollabe</div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div>

So finally, when the content in the second is smaller and should in such cases fill the remaining space, it will also need flex-grow: 1.

Stack snippet

<div style="display: flex; flex-direction: row;">

    <div id="first" style="flex: 1 1 200px;">...</div>

    <div id="second" style="flex-grow: 1; display: flex; min-width: 0;">
       <div style="overflow: auto;">
           <div style="min-width: 1000px; background: red;"> scrollabe</div>
       </div>
    </div>

    <div id="third" style="flex: 1 1 600px;">...</div>

</div>


问:
How to skip JAR deploy in maven and deploy the assembly only
My project packages to a Spring Boot fat-jar.

I configured 2 extra build plugins:

Generate an executable using Launch4j Plugin (it get the resulting fat-jar and embed it on a executable file)

Assembly the resulting executable in a ZIP

Now I want to deploy only the assembly resulting zip to my maven repository.

This is my build section:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.akathist.maven.plugins.launch4j</groupId>
            <artifactId>launch4j-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>l4j-clui</id>
                    <phase>package</phase>
                    <goals>
                        <goal>launch4j</goal>
                    </goals>
                    <configuration>
                        <headerType>console</headerType>
                        <outfile>target/${project.build.finalName}.exe</outfile>
                        <jar>target/${project.build.finalName}.jar</jar>
                        <manifest>launch4j/besser-updater.manifest</manifest>
                        <classPath>
                            <mainClass>org.springframework.boot.loader.JarLauncher</mainClass>
                        </classPath>
                        <jre>
                            <minVersion>1.8.0_131</minVersion>
                            <jdkPreference>preferJre</jdkPreference>
                            <runtimeBits>32/64</runtimeBits>
                        </jre>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <descriptors>
                            <descriptor>launch4j/assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

How can I configure the deploy phase to ignore the jar artifact and deploy only the zip assembly file?

答:
Are you using the assembly to deploy or are you talking about simply avoiding the install of the dependencies in your remote repo?

If you are talking about the assembly plugin you can easily exclude jars with it

https://maven.apache.org/plugins/maven-assembly-plugin/examples/single/including-and-excluding-artifacts.html

You can avoid to deploy the single artifact like this:

```<code><build>
  <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-deploy-plugin</artifactId>
     <version>2.4</version>
     <configuration>
       <skip>true</skip>
     </configuration>
  </plugin>
...
</build>
</code>```

Then you can specify the specific file to deploy just including into the deploy plugin configuration.

reference: http://prystash.blogspot.ie/2009/06/maven-excluding-module-from-deploy.html

Hope it helps..

Body:
My project packages to a Spring Boot fat-jar.

I configured 2 extra build plugins:

Generate an executable using Launch4j Plugin (it get the resulting fat-jar and embed it on a executable file)

Assembly the resulting executable in a ZIP

Now I want to deploy only the assembly resulting zip to my maven repository.

This is my build section:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
        <plugin>
            <groupId>com.akathist.maven.plugins.launch4j</groupId>
            <artifactId>launch4j-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>l4j-clui</id>
                    <phase>package</phase>
                    <goals>
                        <goal>launch4j</goal>
                    </goals>
                    <configuration>
                        <headerType>console</headerType>
                        <outfile>target/${project.build.finalName}.exe</outfile>
                        <jar>target/${project.build.finalName}.jar</jar>
                        <manifest>launch4j/besser-updater.manifest</manifest>
                        <classPath>
                            <mainClass>org.springframework.boot.loader.JarLauncher</mainClass>
                        </classPath>
                        <jre>
                            <minVersion>1.8.0_131</minVersion>
                            <jdkPreference>preferJre</jdkPreference>
                            <runtimeBits>32/64</runtimeBits>
                        </jre>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <descriptors>
                            <descriptor>launch4j/assembly.xml</descriptor>
                        </descriptors>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How can I configure the deploy phase to ignore the jar artifact and deploy only the zip assembly file?

Body:
Are you using the assembly to deploy or are you talking about simply avoiding the install of the dependencies in your remote repo?

If you are talking about the assembly plugin you can easily exclude jars with it

https://maven.apache.org/plugins/maven-assembly-plugin/examples/single/including-and-excluding-artifacts.html

You can avoid to deploy the single artifact like this:

<build>
  <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-deploy-plugin</artifactId>
     <version>2.4</version>
     <configuration>
       <skip>true</skip>
     </configuration>
  </plugin>
...
</build>

Then you can specify the specific file to deploy just including into the deploy plugin configuration.

reference: http://prystash.blogspot.ie/2009/06/maven-excluding-module-from-deploy.html

Hope it helps..


问:
Tracing instantiation in a base class
Currently I trace number of instances of a base class this way:

```<code>private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}
</code>```

Then I have child classes with constructor like this:

```<code>public ChildClass(): base()
{
    // Empty Constructor
}
</code>```

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?

答:
Is getting exception means I really tried to create more than one instance of the ChildClass according to above code ?

It means there is  more than 1 baseclass(-derived) instance.

Is there any way to do it it the BaseClass ?

Do what in the baseclass? This part of the Questions is unclear. You're already doing it in the baseclass.

But your setup won't be very usefull as it will only allow 1 instance of the baseclass and hence of only 1 of the derived classes.

I'll  assume you want each derived class to be a Singleton. To implement that in the base class you'll need for instance a static HashSet where you can use the Typename (this.GetType().Name) as key.

Title: Tracing instantiation in a base class

Body:
Currently I trace number of instances of a base class this way:

private static int _instanceCount = 0;

protected BaseClass()
{
    Interlocked.Increment(ref _instanceCount);

    if (_instanceCount > 1)
        throw new Exception("multiple instances detected.");
}

Then I have child classes with constructor like this:

public ChildClass(): base()
{
    // Empty Constructor
}

and I get exceptions of course. I can move the code from BaseClass constructor to ChildClass constructor but it's a kind of redundancy (all children with the same code).

Is there any way to do it in the BaseClass?

Is getting exception means I really tried to create more than one instance of the ChildClass according to above code?


问:
onPositionChanged handler of gmaps marker scope issue
I try to update the current position of a draggable marker of the react-google-maps wrapper and pass these values back to the parent.

My problem is, that in onMarkerPositionChange this is either the FindLocationMarker class or the marker itself, depending on how the function is invoked.

onPositionChanged={() => this.onMarkerPositionChange()} was my other option.

I need both, the marker for the position and the class for the function in props.

In the provided example, this is the marker.
evt is undefined, I know.

How can i provide both, the class scope and the marker, to the function?

```<code>class FindLocationMarker extends Component {

  onMarkerPositionChange = (evt) => {
    console.log(evt);
    let lat = this.position.lat();
    let lng = this.position.lng();

    this.props.handleMarkerPositionChange(lat, lng);
  }

  render() {
    return (
      <div>
        <Marker
          position={this.props.position}
          draggable
          onPositionChanged={this.onMarkerPositionChange}
        />
      </div>
      )
  }
}

export default FindLocationMarker;
</code>```

答:
After a long discussion below I decided to update my answer for future issues with https://github.com/tomchentw/react-google-maps Marker.jsx component.

If you want to get the position of the marker onPositionChange you need to:

Store the marker in your refs

Listen to the onPositionChange event and then access the position of the marker in your refs.

Example:

```<code>onPositionChanged() {
    const position = this.marker.getPosition();

    // do something with position
}

render() {
    return <Marker
        onPositionChanged={ ::this.onPositionChanged }
        ref={input => this.marker = input}
    />
}
</code>```

Body:
I try to update the current position of a draggable marker of the react-google-maps wrapper and pass these values back to the parent.

My problem is, that in onMarkerPositionChange this is either the FindLocationMarker class or the marker itself, depending on how the function is invoked.

onPositionChanged={() => this.onMarkerPositionChange()} was my other option.

I need both, the marker for the position and the class for the function in props.

In the provided example, this is the marker.
evt is undefined, I know.

How can i provide both, the class scope and the marker, to the function?

class FindLocationMarker extends Component {

  onMarkerPositionChange = (evt) => {
    console.log(evt);
    let lat = this.position.lat();
    let lng = this.position.lng();

    this.props.handleMarkerPositionChange(lat, lng);
  }

  render() {
    return (

        <Marker
          position={this.props.position}
          draggable
          onPositionChanged={this.onMarkerPositionChange}
        />

      )
  }
}

export default FindLocationMarker;

Body:
After a long discussion below I decided to update my answer for future issues with https://github.com/tomchentw/react-google-maps Marker.jsx component.

If you want to get the position of the marker onPositionChange you need to:

Store the marker in your refs

Listen to the onPositionChange event and then access the position of the marker in your refs.

Example:

onPositionChanged() {
    const position = this.marker.getPosition();

    // do something with position
}

render() {
    return <Marker
        onPositionChanged={ ::this.onPositionChanged }
        ref={input => this.marker = input}
    />
}


问:
:disable_with for submit button, Rails 3, JQuery
I'm trying to get :disable_with to work on my button. I'm using JQuery though, and the form is not a javascript implements form, so I'm wondering if theres a better way to make this work?</p>

答: Unfortunately, :disable_with will not work without Javascript. This is needed to modify the DOM.


问:
sort string by number inside
I would like to know how can I sort a string by the number inside.

As example I have:

```<code>hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)
</code>```

I want to sort them by the number even if it changes.

答:
Just a little complement to Andy's answer.

If you want to sort set which also contain strings without any number:

```<code>sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))
</code>```

, which would put those strings without any number at the very beginning.

Title: sort string by number inside

Body:
I would like to know how can I sort a string by the number inside.

As example I have:

hello = " hola %d" % (number_from_database)
bye = "adios %d" % (number_from_database_again)

I want to sort them by the number even if it changes.

Body:
Just a little complement to Andy's answer.

If you want to sort set which also contain strings without any number:

sorted(l, key=lambda x: int('0'+re.sub('\D', '', x)))

, which would put those strings without any number at the very beginning.


问:
pthread mutex with a global variable: correct usage?
I understand the purpose of mutex in pthreads, but I often here that it is considered a bad practice to use mutex with a global variable as a shared resource (for example, like in the answer to this question: Mutex lock threads).

So, the questions:

Is it really that bad to put the shared resource as a global variable?

If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?

What is the better way to share the variables between the processes?

答:
In general:

Global Variable are Evil:

Global Variables Are Bad on C2 Wiki

Chapter 19: Global Variables Are Evil from Better Embedded System Software

Yes, you have to create a variable in the main thread and pass the reference to other threads that have to use it, which is true even if you have only one shared variable.


问:
Import issue while mocking REST in py.test
I've tried to write some unit tests for a REST Client in Python. I have trouble with mocking the response from the server.
Specifically, I want a GET query return a pre-prepared JSON string without connecting to the server. As I learned the way to do that in Python is to use unittest.mock or pytest-mock. My project structure is as such:

```<code>workspace/__init__.py
workspace/module/__init__.py
workspace/module/connector.py
workspace/tests/__init__.py
workspace/tests/test_connector.py
</code>```

I put the test code in test_connector.py. I've tried to use unittest.mock.patch in this way:

```<code>@patch()
test_get_container_list(mocker):
    (....)
</code>```

as well as pytest-mock:

```<code>mocker.patch('module.connector.Connector.get_container_list.requests.sessions.get')
mocker.return_value.ok = True
mocker.return_value.json.return_value = container_list
</code>```

I've been stumped however by this error:

```<code>ImportError: No module named 'module.connector.Connector'; 'module.connector' is not a package
</code>```

I've also tried to modify what I'm putting in path, but all I got was:

```<code>ImportError: No module named 'Connector'
ImportError: No module named 'connector.Connector'; 'connector' is not a package
</code>```

I launched tests with this command:

pytest tests/

from the module directory. My imports look like this:

```<code>import configparser
import pytest
from module.connector import Connector
</code>```

Environment: Ubuntu 16.04, Python 3.5.2, pytest-3.2.5, py-1.5.2, pluggy-0.4.0; plugins: mock-1.6.3, cov-2.5.1

All remaining tests work without problems, just this one with mocking does not.

My question: how do I make mocked tests work correctly? (import errors appear wheather I use pytest-mock or unittest.mock).

答:
I went another route and instead of using pytest-mock I used request-mock. The approach here is to perform the HTTP requests normally with requests and mock the response of a particular URL.

```<code>import requests
import requests_mock

def test_requests():
    with requests_mock.Mocker() as mock:
        session = requests.Session()
        url = 'https://google.com/'

        mock.register_uri('GET', url, text='{"answer": "My return text"}')  # mocking the http response within this context
        resp = session.get('https://google.com/')
        assert resp.json()['answer'] == 'My return text'
</code>```

Check for more info here and probably you'll want to check regarding request matching here.

Hope this gives you some inspiration for an alternative approach.

Body:
I've tried to write some unit tests for a REST Client in Python. I have trouble with mocking the response from the server.
Specifically, I want a GET query return a pre-prepared JSON string without connecting to the server. As I learned the way to do that in Python is to use unittest.mock or pytest-mock. My project structure is as such:

workspace/__init__.py
workspace/module/__init__.py
workspace/module/connector.py
workspace/tests/__init__.py
workspace/tests/test_connector.py

I put the test code in test_connector.py. I've tried to use unittest.mock.patch in this way:

@patch()
test_get_container_list(mocker):
    (....)

as well as pytest-mock:

mocker.patch('module.connector.Connector.get_container_list.requests.sessions.get')
mocker.return_value.ok = True
mocker.return_value.json.return_value = container_list

I've been stumped however by this error:

ImportError: No module named 'module.connector.Connector'; 'module.connector' is not a package

I've also tried to modify what I'm putting in path, but all I got was:

ImportError: No module named 'Connector'
ImportError: No module named 'connector.Connector'; 'connector' is not a package

I launched tests with this command:

pytest tests/

from the module directory. My imports look like this:

import configparser
import pytest
from module.connector import Connector

Environment: Ubuntu 16.04, Python 3.5.2, pytest-3.2.5, py-1.5.2, pluggy-0.4.0; plugins: mock-1.6.3, cov-2.5.1

All remaining tests work without problems, just this one with mocking does not.

My question: how do I make mocked tests work correctly? (import errors appear wheather I use pytest-mock or unittest.mock).

Body:
I went another route and instead of using pytest-mock I used request-mock. The approach here is to perform the HTTP requests normally with requests and mock the response of a particular URL.

import requests
import requests_mock

def test_requests():
    with requests_mock.Mocker() as mock:
        session = requests.Session()
        url = 'https://google.com/'

        mock.register_uri('GET', url, text='{"answer": "My return text"}')  # mocking the http response within this context
        resp = session.get('https://google.com/')
        assert resp.json()['answer'] == 'My return text'

Check for more info here and probably you'll want to check regarding request matching here.

Hope this gives you some inspiration for an alternative approach.


问:
TypeScript - getOwnPropertyNames() - Constructor Properties vs. Getter/Setter
I am quite new to TypeScript and there is a point I do not quite understand.

Imagine the following classes:

```<code>export class PropertyInConstructor {

  constructor(public foo: boolean) {

  }
}
</code>```

```<code>export class PropertyWithGetSet {

  private _foo: boolean = false;

  get foo(): boolean {
    return this._foo;
  }

  set foo(theFoo: boolean) {
    this._foo = theFoo;
  }
}
</code>```

From my understanding these two approaches both provide me a property that I can access using new PropertyInConstructor().foo or new PropertyWithGetSet().foo.

I now want to get the existing properties of such a class (without instance!) and to try it out:

```<code>console.log(Object.getOwnPropertyNames(PropertyInConstructor.prototype));
console.log(Object.getOwnPropertyNames(PropertyWithGetSet.prototype));
</code>```

["constructor"]

  ["constructor", "foo"]

Why is it that the call where the properties are specified inside the constructor does not add the "foo" property?

Is there something missing or some other way to get those properties?

答:
Short answer: most properties are added to the instance dynamically at runtime. Properties with getters and setters need to be added to the prototype with Object.defineProperty.

Added at Runtime

With your first example:

```<code>export class PropertyInConstructor {
  constructor(public foo: boolean) {
  }
}
</code>```

The property is only added to the instance when the constructor runs. Here is the transpiled JavaScript:

```<code>var PropertyInConstructor = /** @class */ (function () {
    function PropertyInConstructor(foo) {
        this.foo = foo;
    }
    return PropertyInConstructor;
}());
</code>```

Effectively, the property foo does not exist on the class until the constructor runs.

This isn't just for constructor properties, it is for all properties that are not defined against the prototype, for example:

```<code>class PropertyInConstructor {
    public foo: boolean;
    constructor() {
        this.foo = true;
  }
}
</code>```

Define Property

When you use get and set, things are different, because the property is added to the prototype:

```<code>var PropertyWithGetSet = /** @class */ (function () {
    function PropertyWithGetSet() {
        this._foo = false;
    }
    Object.defineProperty(PropertyWithGetSet.prototype, "foo", {
        get: function () {
            return this._foo;
        },
        set: function (theFoo) {
            this._foo = theFoo;
        },
        enumerable: true,
        configurable: true
    });
    return PropertyWithGetSet;
}());
</code>```

Body:
I am quite new to TypeScript and there is a point I do not quite understand.

Imagine the following classes:

export class PropertyInConstructor {

  constructor(public foo: boolean) {

  }
}

export class PropertyWithGetSet {

  private _foo: boolean = false;

  get foo(): boolean {
    return this._foo;
  }

  set foo(theFoo: boolean) {
    this._foo = theFoo;
  }
}

From my understanding these two approaches both provide me a property that I can access using new PropertyInConstructor().foo or new PropertyWithGetSet().foo.

I now want to get the existing properties of such a class (without instance!) and to try it out:

console.log(Object.getOwnPropertyNames(PropertyInConstructor.prototype));
console.log(Object.getOwnPropertyNames(PropertyWithGetSet.prototype));

["constructor"]

  ["constructor", "foo"]

Why is it that the call where the properties are specified inside the constructor does not add the "foo" property?

Is there something missing or some other way to get those properties?

Body:
Short answer: most properties are added to the instance dynamically at runtime. Properties with getters and setters need to be added to the prototype with Object.defineProperty.

Added at Runtime

With your first example:

export class PropertyInConstructor {
  constructor(public foo: boolean) {
  }
}

The property is only added to the instance when the constructor runs. Here is the transpiled JavaScript:

var PropertyInConstructor = /** @class */ (function () {
    function PropertyInConstructor(foo) {
        this.foo = foo;
    }
    return PropertyInConstructor;
}());

Effectively, the property foo does not exist on the class until the constructor runs.

This isn't just for constructor properties, it is for all properties that are not defined against the prototype, for example:

class PropertyInConstructor {
    public foo: boolean;
    constructor() {
        this.foo = true;
  }
}

Define Property

When you use get and set, things are different, because the property is added to the prototype:

var PropertyWithGetSet = /** @class */ (function () {
    function PropertyWithGetSet() {
        this._foo = false;
    }
    Object.defineProperty(PropertyWithGetSet.prototype, "foo", {
        get: function () {
            return this._foo;
        },
        set: function (theFoo) {
            this._foo = theFoo;
        },
        enumerable: true,
        configurable: true
    });
    return PropertyWithGetSet;
}());


问:
Is there a complete react-native Component API
At the top of my new react native app some boilerplate code is created

```<code>export default class App extends Component < {} > {
    render() {
        ...
    }
}
</code>```

Within the Learn the Basics webpage of the React Native Documentation there is a section on Component. Within this section it mentions

A component can be pretty simple - the only thing that's required is a
  render function...

I can't see in the API list an entry for Component. I presume this Component has the same idea as Object in Java as the base class for everything.
Java's Object class provides some methods such as toString().

I would like to know :

Is my presumption correct?

Is there a weblink to documentation somewhere that details the full
api for Component?

What else provided by react native, that isn't my own custom code, can be put inside my App
class?

答:
You can read about React Components here. React-Native utilizes React architecture.

Component is a module of your app that has a particular functionality. On the left sidebar here you can see a section called "Components" These are the default React-Native components. You can create other components, needed in your app by using those components. Examples of how the components could look or be created are components of Expo SDK and React-Native-Elements component library.

Through this link you can view all of React-Native and Expo components on your device using Expo app: https://expo.io/@community/native-component-list

Your custom components / components of other libraries that you would like to render (put them in return statement, wrapped with parenthesis, like return (<Text>Hello World</Text>);.

Plus anything that is related to rendering your screen could also be put inside the render method, but outside the return statement. For example, state / props destructuring, conditional rendering (if something is true - show this view, else show this view) and so forth.

Body:
At the top of my new react native app some boilerplate code is created

export default class App extends Component < {} > {
    render() {
        ...
    }
}

Within the Learn the Basics webpage of the React Native Documentation there is a section on Component. Within this section it mentions

A component can be pretty simple - the only thing that's required is a
  render function...

I can't see in the API list an entry for Component. I presume this Component has the same idea as Object in Java as the base class for everything.
Java's Object class provides some methods such as toString().

I would like to know :

Is my presumption correct?

Is there a weblink to documentation somewhere that details the full
api for Component?

What else provided by react native, that isn't my own custom code, can be put inside my App
class?


问:
Parent child relation in C# classes
I have the following case:

```<code>public class ParentObject
{
public int id {get;set;}
public string parent_object_name {get;set;}
public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
public int id {get;set;}
public string child_object_name {get;set;}
}

ParentObject parent_object = new ParentObject()
{
  id = 1,
  parent_object_name = "test name",
  child_objects = new List<ChildObject>(){ new ChildObject(){ id = 1, child_object_name = "test name"};
}
</code>```

I am aware that it is perfectly valid to reference parent_object.child_objects, but I am not sure how can I code my classes to have a reference such as child_objects.First().parent_object ie. similar to navigational properties in Entity Framework.

答:
Try this:</p>

```<code>public class ChildObject
{
    public int id { get; set; }
    public string child_object_name { get; set; }
    public ParentObject parent_object { get; set; }
}
</code>```

Title: Parent child relation in C# classes

Body:
I have the following case:

public class ParentObject
{
public int id {get;set;}
public string parent_object_name {get;set;}
public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
public int id {get;set;}
public string child_object_name {get;set;}
}

ParentObject parent_object = new ParentObject()
{
  id = 1,
  parent_object_name = "test name",
  child_objects = new List<ChildObject>(){ new ChildObject(){ id = 1, child_object_name = "test name"};
}

I am aware that it is perfectly valid to reference parent_object.child_objects, but I am not sure how can I code my classes to have a reference such as child_objects.First().parent_object ie. similar to navigational properties in Entity Framework.

Body:
Try this:

public class ChildObject
{
    public int id { get; set; }
    public string child_object_name { get; set; }
    public ParentObject parent_object { get; set; }
}


问:
String in String , by searching each occurrence of specific text and filter to other cells
```<code>Summary : Using vba-excel Looping through a single cell of text , finding
and taking  out  each nth occurrence of <li> to </li > into each individual
cell
</code>```

Before

Single excel cell (e.g A1 ) contains

```<code><li>
  <ahref="xxxx">
  <imgsrc=""yyy">
  </a>
</li>

<li>
  <ahref="xxxx">
  <imgsrc=""yyy">
  </a>
</li>
</code>```

Result ( after ) :

cell A2

```<code><ahref="xxxx">
<imgsrc=""yyy">
</code>```

cell A3

```<code><ahref="xxxx">
<imgsrc=""yyy">
</code>```

much appreciated ; D

what i have done so far

```<code>'myrow is already pre-define previous , basically row number fetch during
 loopping

Dim newi As String
Dim texti as string
</code>```

i = MyRow
    texi = cell (i , 1)

```<code>'not sure if this is correct , trying to find each
For Each item In Texti
Cells(i, 13) = item("<a href=")
Cells(i, 14) = item("<img src=")
newi = Cells(i, 13).Value + "  " + Cells(i, 14).Value
Next
</code>```

Thanks again in advance for helping me , was stuck with this ~ !

答:
Try this:

```<code>Sub StringExtract()

Dim iLength As Integer, iLoopCounter As Integer, iInnerLoopCounter As Integer
Dim sRemString As String
Dim iLastRow As Integer

iLength = Len(Range("A1"))

For iLoopCounter = 1 To iLength

    If (Mid(Range("A1"), iLoopCounter, 4) = "<li>") Then

        For iInnerLoopCounter = iInnerLoopCounter + 4 To iLength

            If (Mid(Range("A1"), iInnerLoopCounter, 5) = "</li>") Then

                sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)

                iLastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

                Cells(iLastRow, "A").Value = sRemString

                Exit For

            End If

        Next iInnerLoopCounter

    End If

Next iLoopCounter
End Sub
</code>```

might not be the fastest way, but in this case it should work. I cant figure out, why the  should be excluded as well. If you need to, increase the integer from -6 to your needs in this line:

```<code>sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)
</code>```

Body:
Summary : Using vba-excel Looping through a single cell of text , finding
and taking  out  each nth occurrence of
 to
 into each individual
cell

Before

Single excel cell (e.g A1 ) contains

  <ahref="xxxx">
  <imgsrc=""yyy">

  <ahref="xxxx">
  <imgsrc=""yyy">

Result ( after ) :

cell A2

<ahref="xxxx">
<imgsrc=""yyy">

cell A3

<ahref="xxxx">
<imgsrc=""yyy">

much appreciated ; D

what i have done so far

'myrow is already pre-define previous , basically row number fetch during
 loopping

Dim newi As String
Dim texti as string

i = MyRow
    texi = cell (i , 1)

'not sure if this is correct , trying to find each
For Each item In Texti
Cells(i, 13) = item("<a href=")
Cells(i, 14) = item("<img src=")
newi = Cells(i, 13).Value + "  " + Cells(i, 14).Value
Next

Thanks again in advance for helping me , was stuck with this ~ !

Body:
Try this:

Sub StringExtract()

Dim iLength As Integer, iLoopCounter As Integer, iInnerLoopCounter As Integer
Dim sRemString As String
Dim iLastRow As Integer

iLength = Len(Range("A1"))

For iLoopCounter = 1 To iLength

    If (Mid(Range("A1"), iLoopCounter, 4) = "<li>") Then

        For iInnerLoopCounter = iInnerLoopCounter + 4 To iLength

            If (Mid(Range("A1"), iInnerLoopCounter, 5) = "</li>") Then

                sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)

                iLastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1

                Cells(iLastRow, "A").Value = sRemString

                Exit For

            End If

        Next iInnerLoopCounter

    End If

Next iLoopCounter
End Sub

might not be the fastest way, but in this case it should work. I cant figure out, why the </a> should be excluded as well. If you need to, increase the integer from -6 to your needs in this line:

sRemString = Mid(Range("A1"), iLoopCounter + 5, iInnerLoopCounter - iLoopCounter - 6)


问:
Python. Change list
I am trying to create a program that will figure out a number that the user thinks of.

```<code>nums=list(range(1,11))

def remove_odd(l):
    return [n for n in l if n % 2 == 0]

y=str(input('Is it an even number?'))
if y=='yes':
    (remove_odd(nums))

print(nums)
</code>```

I get this output:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

But I want to get:

```<code>[2, 4, 6, 8, 10]
</code>```

What am I doing wrong?

答:
```<code>nums=list(range(1,11))
def remove_odd(l):
    return [n for n in l if n % 2 == 0]
y=str(input('Is it an even number?'))
if y=='yes':
    nums = remove_odd(nums)
print(nums)
</code>```

You need to use a new variable to receive the return value of the function

Title: Python. Change list

Body:
I am trying to create a program that will figure out a number that the user thinks of.

nums=list(range(1,11))

def remove_odd(l):
    return [n for n in l if n % 2 == 0]

y=str(input('Is it an even number?'))
if y=='yes':
    (remove_odd(nums))

print(nums)

I get this output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But I want to get:

[2, 4, 6, 8, 10]

What am I doing wrong?

Body:
nums=list(range(1,11))
def remove_odd(l):
    return [n for n in l if n % 2 == 0]
y=str(input('Is it an even number?'))
if y=='yes':
    nums = remove_odd(nums)
print(nums)

You need to use a new variable to receive the return value of the function


答:
One way would be to define a constructor that accepts the parent as parameter.</p>

```<code>public class ChildObject
{
  public ChildObject(ParentObject aParent)
  {
    parent = aParent
  }

  public ParentObject parent { get; private set; }
  public int id {get;set;}
  public string child_object_name {get;set;}
}
</code>```

Title: Parent child relation in C# classes

Body:
One way would be to define a constructor that accepts the parent as parameter.

public class ChildObject
{
  public ChildObject(ParentObject aParent)
  {
    parent = aParent
  }

  public ParentObject parent { get; private set; }
  public int id {get;set;}
  public string child_object_name {get;set;}
}


问:
NEHotspotConfigurationManager not creating/joining hotspot
I am trying to create/add a Hotspot configuration in iOS 11 installed device.

My code is as follows

```<code>let hotspotConfig = NEHotspotConfiguration(ssid: "testNetwork")
hotspotConfig.joinOnce = true
NEHotspotConfigurationManager.shared.apply(hotspotConfig) { (configurationError) in
    if configurationError != nil {
      print("error")
      print(configurationError!.localizedDescription)
    } else {
      print("success")
    }
}
</code>```

When i try to run the code. Device prompts for permissions as the following:-

```<code>"AppName" wants to join Wi-Fi Network "testNetwork"
</code>```

But on tapping "Join", I am getting the following response

```<code>Unable to join the network "testNetwork"
</code>```

However, on debug console "success" is getting printed.

Please tell me what am i doing wrong.

答:
Enable Hotspot on App Id configure services

After Enable Hotspot Configuration

Body:
I am trying to create/add a Hotspot configuration in iOS 11 installed device.

My code is as follows

let hotspotConfig = NEHotspotConfiguration(ssid: "testNetwork")
hotspotConfig.joinOnce = true
NEHotspotConfigurationManager.shared.apply(hotspotConfig) { (configurationError) in
    if configurationError != nil {
      print("error")
      print(configurationError!.localizedDescription)
    } else {
      print("success")
    }
}

When i try to run the code. Device prompts for permissions as the following:-

"AppName" wants to join Wi-Fi Network "testNetwork"

But on tapping "Join", I am getting the following response

Unable to join the network "testNetwork"

However, on debug console "success" is getting printed.

Please tell me what am i doing wrong.


问:
Use of getter-setter within class
Should one use under any circumstances getters-setters of a class within the class?</p>

答:
Yes, getters and setters are useful. Because PHP doesn't support type hinting for simple types like int or string, you cannot force a value to be of the right type.

By using a setter, you always have the possibility to check the value that is set. When a value set to an int property isn't an int, you can choose to typecast it, or raise an error, instead of just accepting the wrong value.

That will make debugging and maintaining your application a lot easier. So it's a good idea to use getters and setters, even if they do not contain much logic other than these checks.

Title: Use of getter-setter within class


问:
CSharp skip file through loop if it contains some string
Good morning,
I am looping through many text files in a folder to get the text written inside of them.
The name of the file is automatically written by another progam in a standard like date_filename.id, so I cannot be able to filter the files basing on the file name...

I noticed that they have a file identification on the first line like ORDERR or Something else so I was thinking if there's some method to skip the file if the first line contains some string.The loop looks like this at the moment:

```<code> DirectoryInfo FilesPath = new DirectoryInfo(path);
 var Files = FilesPath.GetFiles();
 foreach (var file in Files)
        {
            List<string> lines = new List<string>();
            using (StreamReader sr = file.OpenText())
            {

                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("ORDERR"))
                    {
                        "Do something"
                    }
                    else
                    {
                        break;
                    }
                }

            }
</code>```

But when the loop reach the second line, obviusly, it will skip the rest.
What can I do?

Thank you in advance for any kind of help

(I cannot be able to find something through stackoverflow)

答:
What you need is a flag to set and break out of the readloop</p>

```<code>DirectoryInfo FilesPath = new DirectoryInfo(path);
var Files = FilesPath.GetFiles();
foreach (var file in Files)
{
    bool hasError = false;
    List<string> lines = new List<string>();
    using (StreamReader sr = file.OpenText())
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            if (s.Contains("ORDERR"))
            {
                hasError = true;
                break;
             } else {
                lines.Add(s)
             }
        }
    }

    if (!hasError)
    {
        // do something with lines as we were ok with it
    }
}
</code>```

Body:
Good morning,
I am looping through many text files in a folder to get the text written inside of them.
The name of the file is automatically written by another progam in a standard like date_filename.id, so I cannot be able to filter the files basing on the file name...

I noticed that they have a file identification on the first line like ORDERR or Something else so I was thinking if there's some method to skip the file if the first line contains some string.The loop looks like this at the moment:

 DirectoryInfo FilesPath = new DirectoryInfo(path);
 var Files = FilesPath.GetFiles();
 foreach (var file in Files)
        {
            List<string> lines = new List<string>();
            using (StreamReader sr = file.OpenText())
            {

                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("ORDERR"))
                    {
                        "Do something"
                    }
                    else
                    {
                        break;
                    }
                }

            }

But when the loop reach the second line, obviusly, it will skip the rest.
What can I do?

Thank you in advance for any kind of help

(I cannot be able to find something through stackoverflow)

Body:
What you need is a flag to set and break out of the readloop

DirectoryInfo FilesPath = new DirectoryInfo(path);
var Files = FilesPath.GetFiles();
foreach (var file in Files)
{
    bool hasError = false;
    List<string> lines = new List<string>();
    using (StreamReader sr = file.OpenText())
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            if (s.Contains("ORDERR"))
            {
                hasError = true;
                break;
             } else {
                lines.Add(s)
             }
        }
    }

    if (!hasError)
    {
        // do something with lines as we were ok with it
    }
}


问:
Apache redirect to different port for docker container ( Redmine )
Hello I am working a project to run Drupal web page and Redmine on the same server. Drupal is main web and using 80 and 443. Redmine is on docker and using 3000 port.

Using httpd proxy setting, I was able to get the Redmine page.

```<code>ProxyPreserveHost On
ProxyPass /redmine http://127.0.0.1:3000/
ProxyPassReverse /redmine http://127.0.0.1:3000/
ProxyPass /stylesheets http://127.0.0.1:3000/stylesheets/
ProxyPassReverse /stylesheets http://127.0.0.1:3000/stylesheets/
ProxyPass /javascripts http://127.0.0.1:3000/javascripts/
ProxyPassReverse /javascripts http://127.0.0.1:3000/javascripts/
ProxyPass /images http://127.0.0.1:3000/images
ProxyPassReverse /images http://127.0.0.1:3000/images
</code>```

However, when I click buttons on the redmine page such as project, login, register. It's redirected to main domain.

I would like to get www.example.com/redmine/login

but it's redirected to www.example.com/login

How can I resolve this issue?

答:
To configure Redmine's URI, you can do it from Redmine itself, navigate to

admin | settings

and enter desired configuration to
Host name and path field

And click save.

Additionally, depending upon how Redmine is deployed, deployment specific configuration can be applied, as described on Redmine wiki: http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_in_a_sub-URI

Body:
Hello I am working a project to run Drupal web page and Redmine on the same server. Drupal is main web and using 80 and 443. Redmine is on docker and using 3000 port.

Using httpd proxy setting, I was able to get the Redmine page.

ProxyPreserveHost On
ProxyPass /redmine http://127.0.0.1:3000/
ProxyPassReverse /redmine http://127.0.0.1:3000/
ProxyPass /stylesheets http://127.0.0.1:3000/stylesheets/
ProxyPassReverse /stylesheets http://127.0.0.1:3000/stylesheets/
ProxyPass /javascripts http://127.0.0.1:3000/javascripts/
ProxyPassReverse /javascripts http://127.0.0.1:3000/javascripts/
ProxyPass /images http://127.0.0.1:3000/images
ProxyPassReverse /images http://127.0.0.1:3000/images

However, when I click buttons on the redmine page such as project, login, register. It's redirected to main domain.

I would like to get www.example.com/redmine/login

but it's redirected to www.example.com/login

How can I resolve this issue?


问:
@Scheduled Tasks keep JVM hanging when standalone program wants to exit, JVM needs to be killed
i opened this bug in the spring bug tracker. would be cool if some clever people here can already help me

https://jira.springsource.org/browse/SPR-9341

答:
This is the solution using Java config

```<code>@Bean
public TaskScheduler daemonTaskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setDaemon(false);
    taskScheduler.setThreadNamePrefix("daemon");
    taskScheduler.setPoolSize(5);
    return taskScheduler;
}
</code>```

or if you want to really get into the details, the config class can be like this

```<code>@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

   @Override
   public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
</code>```

One thing is not supported though is to be able to use multiple TaskSchedulers within a single application. I opened a JIRA for that

Body:
This is the solution using Java config

@Bean
public TaskScheduler daemonTaskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setDaemon(false);
    taskScheduler.setThreadNamePrefix("daemon");
    taskScheduler.setPoolSize(5);
    return taskScheduler;
}

or if you want to really get into the details, the config class can be like this

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

   @Override
   public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

One thing is not supported though is to be able to use multiple TaskSchedulers within a single application. I opened a JIRA for that


问:
Relative URLs in WordPress
I've always found it frustrating in WordPress that images, files, links, etc. are inserted into WordPress with an absolute URL instead of relative URL. A relative url is much more convenient for switching domain names, changing between http and https etc. Today I discovered that if you define WP_CONTENT_URL with a relative url then when you insert files into posts they use the relative url for the src instead of absolute url. Just what I've always wanted! But the official WordPress documentation says that you should use a full URI if you are defining WP_CONTENT_URL.

WordPress codex says:

Set WP_CONTENT_URL to the full URI of this directory (no trailing
  slash), e.g.

```<code>define( 'WP_CONTENT_URL', 'http://example/blog/wp-content');
</code>```

Everything seems to work fine when I use a relative URL, e.g.

```<code>define( 'WP_CONTENT_URL', '/my-content-folder');
</code>```

But is there some problem with using a relative URI? I'm just thinking that there must be a reason for WordPress stating that it should be defined with a full URI.

答:
I solved it in my site making this in functions.php

```<code>add_action("template_redirect", "start_buffer");
add_action("shutdown", "end_buffer", 999);

function filter_buffer($buffer) {
    $buffer = replace_insecure_links($buffer);
    return $buffer;
}
function start_buffer(){
    ob_start("filter_buffer");
}

function end_buffer(){
    if (ob_get_length()) ob_end_flush();
}

function replace_insecure_links($str) {

   $str = str_replace ( array("http://www.yoursite.com/", "https://www.yoursite.com/") , array("/", "/"), $str);

   return apply_filters("rsssl_fixer_output", $str);

}
</code>```

I took part of one plugin, cut it into pieces and make this.
It replaced ALL links in my site (menus, css, scripts etc.) and everything was working.

Title: Relative URLs in WordPress

Body:
I've always found it frustrating in WordPress that images, files, links, etc. are inserted into WordPress with an absolute URL instead of relative URL. A relative url is much more convenient for switching domain names, changing between http and https etc. Today I discovered that if you define WP_CONTENT_URL with a relative url then when you insert files into posts they use the relative url for the src instead of absolute url. Just what I've always wanted! But the official WordPress documentation says that you should use a full URI if you are defining WP_CONTENT_URL.

WordPress codex says:

Set WP_CONTENT_URL to the full URI of this directory (no trailing
  slash), e.g.

define( 'WP_CONTENT_URL', 'http://example/blog/wp-content');

Everything seems to work fine when I use a relative URL, e.g.

define( 'WP_CONTENT_URL', '/my-content-folder');

But is there some problem with using a relative URI? I'm just thinking that there must be a reason for WordPress stating that it should be defined with a full URI.

Body:
I solved it in my site making this in functions.php

add_action("template_redirect", "start_buffer");
add_action("shutdown", "end_buffer", 999);

function filter_buffer($buffer) {
    $buffer = replace_insecure_links($buffer);
    return $buffer;
}
function start_buffer(){
    ob_start("filter_buffer");
}

function end_buffer(){
    if (ob_get_length()) ob_end_flush();
}

function replace_insecure_links($str) {

   $str = str_replace ( array("http://www.yoursite.com/", "https://www.yoursite.com/") , array("/", "/"), $str);

   return apply_filters("rsssl_fixer_output", $str);

}

I took part of one plugin, cut it into pieces and make this.
It replaced ALL links in my site (menus, css, scripts etc.) and everything was working.


问:
sed replace spaces in directory names
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

```<code>cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done
</code>```

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?

答:
```<code>directory=`echo $directory | sed 's/ /-/g'`
</code>```

Title: sed replace spaces in directory names

Body:
I'm trying to replace space with - in directory names, not file names on macOS. I have the following:

cd ~/foo
for directory in **; do
    if [[ -d $directory ]] && [[ -w $directory ]]; then
        sed -i '' 's/  /-/g' "$directory"
    fi
done

However I'm getting an error in-place editing only works for regular files.

How can I replace spaces in directory names?


问:
Node.js callback from one controller method to other
I have created a emailHelper in my project for sending emails.

I wan to get a callback once the email sent successfully

```<code>//emailHelper.js

module.exports = {
    sendMail: (options) => {
        var transporter = nodemailer.createTransport({
            service: 'SendGrid',
            auth: {
                user: keys.sendGridUsername,
                pass: keys.sendGridPassword
            }
        });
        const mailOptions = {
            from: options.from,
            to: options.to,
            subject: options.subject,
            html: options.content
        };
        transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                return false;
            }
            else {
                console.log('mail sent');
                return true;
            }
        });
    }
}
</code>```

I want to save data to database only if the email is sent

```<code>const { sendMail } = require('../helpers/emailHelper');
mail: (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}
</code>```

thank you

答:
Wrap your sendMail in promise and return it:

```<code>return new Promise((resolve, reject) => {
       transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                reject();
            }
            else {
                console.log('mail sent');
                resolve();
            }
        });
});
</code>```

Than you would be able to do this:

```<code>sendMail(emailOptions).then(() => {
 // success save data
}).catch(() => {
 // failure trrow error
});
</code>```

Using async/await you would need to change promise to return some identifier in any case, boolean in this case, and than tweak mail function:

```<code>return new Promise((resolve) => {
           transporter.sendMail(mailOptions, (err, info) => {
                if(err) {
                    console.log(err);
                    resolve(false);
                }
                else {
                    console.log('mail sent');
                    resolve(true);
                }
            });
    });

mail: async (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = await sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}
</code>```

Body:
I have created a emailHelper in my project for sending emails.

I wan to get a callback once the email sent successfully

//emailHelper.js

module.exports = {
    sendMail: (options) => {
        var transporter = nodemailer.createTransport({
            service: 'SendGrid',
            auth: {
                user: keys.sendGridUsername,
                pass: keys.sendGridPassword
            }
        });
        const mailOptions = {
            from: options.from,
            to: options.to,
            subject: options.subject,
            html: options.content
        };
        transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                return false;
            }
            else {
                console.log('mail sent');
                return true;
            }
        });
    }
}

I want to save data to database only if the email is sent

const { sendMail } = require('../helpers/emailHelper');
mail: (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}

thank you

Body:
Wrap your sendMail in promise and return it:

return new Promise((resolve, reject) => {
       transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                console.log(err);
                reject();
            }
            else {
                console.log('mail sent');
                resolve();
            }
        });
});

Than you would be able to do this:

sendMail(emailOptions).then(() => {
 // success save data
}).catch(() => {
 // failure trrow error
});

Using async/await you would need to change promise to return some identifier in any case, boolean in this case, and than tweak mail function:

return new Promise((resolve) => {
           transporter.sendMail(mailOptions, (err, info) => {
                if(err) {
                    console.log(err);
                    resolve(false);
                }
                else {
                    console.log('mail sent');
                    resolve(true);
                }
            });
    });

mail: async (req, res, next) => {
    const emailOptions = {
        from: 'from@email.com',
        to: 'to@email.com',
        subject: 'subject',
        content: 'text'
    };
    const mailResetLink = await sendMail(emailOptions);
    if(mailResetLink) {
        //success save data
    } else {
        //failure trrow error
    }
}


问:
Entity framework DbContext ctx populating null values for newly altered table columns
I am trying to get values from ObservationPrograms table using EF ctx. I got all values in ctx except Op_DetailUniqueId and IsClosed columns. These two columns are newly altered with table and model is updated for these two columns. I have updated model many times but null values are populating.

values retrieved from DB in ctx

Actual values in DB

答:
I got some similar problems in my project and the solution was to delete the updated table from my model and insert the same table again.

This worked for me even i "refreshed" the tables after updating them in the db. (also dont forget to actually save ur model after that).


问:
Render list in ordered structure without unicode characters
I have a list that looks like this:

```<code>[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]
</code>```

I have an ansible playbook that uses a jinja2 template to render the list to a text file. The template file looks like this:

```<code>{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}
</code>```

But this returns the text file to look like this:

```<code>[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]
</code>```

What I want the report to look like is this:

```<code>Element1           Description1           Status1
newElement2        nextDescription2       newStatus2
nextElement3       nextDescription3       nextStatus3
anotherElement4    anotherDescription4    anotherDescription4
</code>```

Is there a way to remove the unicode characters and render the lists this way?

答:
For example:

```<code>{% for row in description %}
{% for cell in row %}
{{ "%-22s"|format(cell) }}
{%- endfor %}

{% endfor %}
</code>```

Yields:

```<code>Element1              Description1          Status1
newElement2           newDescription2       newStatus2
nextElement3          nextDescription3      nextStatus3
anotherElement4       anotherDescription4   anotherStatus4
</code>```

But to get a dynamic padding - depending on a max length of an element in a column - looks like a much more complex task: {{ "%-22s"|format(cell) }} can be replaced with {{ "{0}".format(cell).ljust(width) }} where width can be a variable, but likely it would require another loop first to collect the lengths.

Body:
I have a list that looks like this:

[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)]

I have an ansible playbook that uses a jinja2 template to render the list to a text file. The template file looks like this:

{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}

But this returns the text file to look like this:

[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]

What I want the report to look like is this:

Element1           Description1           Status1
newElement2        nextDescription2       newStatus2
nextElement3       nextDescription3       nextStatus3
anotherElement4    anotherDescription4    anotherDescription4

Is there a way to remove the unicode characters and render the lists this way?

Body:
For example:

{% for row in description %}
{% for cell in row %}
{{ "%-22s"|format(cell) }}
{%- endfor %}

{% endfor %}

Yields:

Element1              Description1          Status1
newElement2           newDescription2       newStatus2
nextElement3          nextDescription3      nextStatus3
anotherElement4       anotherDescription4   anotherStatus4

But to get a dynamic padding - depending on a max length of an element in a column - looks like a much more complex task: {{ "%-22s"|format(cell) }} can be replaced with {{ "{0}".format(cell).ljust(width) }} where width can be a variable, but likely it would require another loop first to collect the lengths.


问:
Error running android: Gradle project sync failed. Please fix your project and try again
Android Studio (1.2 RC0) keeps telling me
Error running android: Gradle project sync failed. Please fix your project and try again.
How can I find out what the problem is? Unfortunately the solutions from this SO thread did not help.

答:
Go to </p>

```<code>file->settings->build,execution,deployment->gradle.
</code>```

<p>(and set gradle home path from your directory)</p>

Body:
Go to

file->settings->build,execution,deployment->gradle.

(and set gradle home path from your directory)