问:
PHP Garbage collection and memory optimizations
I'm doing some PHP memory benchmarks and i'm wondering if there is a way to optimize the garbage collector in order to reduce the memory consumption (as it is possible in other languages such as JAVA).

I've found only three customizable parameters related to GC in the php.ini: session.gc_probability, session.gc_divisor and session.gc_maxlifetime. This is only for sessions and i'm not benchmarking that.

Possible optimizations i know so far are code related, such as avoiding circular references and by forcing a garbage collecting cycle by calling gc_collect_cycles() (thanks to this article http://www.alexatnet.com/comment/86).

Someone know any configuration tricks or good practices in PHP memory management ?

答:
In general PHPs memory management works out of the box for all variables that you declare and use. Using the concept refcounting, PHP sees if a variable is not used anymore and then automatically cleans it up.

The garbage collector is only interesting for the cases where objects have cyclic references, A points to B, B points back to A. In this case refcounting doesn't work.

If there are exactly 10.000 objects in PHP memory that are potentically cyclic, potentially not used anymore, then the PHP garbage collector triggers if it enabled, which it is by default. You can disable or enable it with gc_enable() and gc_disable() at runtime.

You can also call gc_collect_cycles() to cleanup these objects manually.

But how to optimize this process, if you need to? Running the cycle collector doesn't have to be efficient or useful, from the 10.000 potential objects, many of them could still be in use and cannot be cleaned up. In this case you are wasting CPU cycles to check all objects and deciding not to clean them up. There will be no memory reduction if you do this.

Usually the GC only triggers in long running scripts, and only sometimes in short web-requests when they create too many objects. In general you shouldn't think about this too much, because the defaults work for 99% of the use-cases.

With the "garbage_stats" PHP extension you can access metrics and stats about how efficient and fast the GC ran and how much memory was reduced. It works on PHP 7+ (because hooks are only available since then): https://github.com/tideways/php_garbage_stats

If you have installed the extension, you can see garbage collection stats for CLI scripts by calling them:

```<code>$ php -dgc_stats.enable=1 -dgc_stats.show_report=1 test.php

Found 7 garbage collection runs in current script.

Collected | Efficency% | Duration | Memory Before | Memory After | Reduction% | Function
----------|------------|----------|---------------|--------------|------------|---------
        0 |     0.00 % |  0.01 ms |        365824 |       366320 |    -0.14 % | gc_collect_cycles
    10000 |   100.00 % |  2.75 ms |       4651320 |       491816 |    89.43 % | foo
    10000 |   100.00 % |  3.54 ms |       4652784 |       493280 |    89.40 % | foo
    10000 |   100.00 % |  2.11 ms |       4654248 |       494744 |    89.37 % | foo
    10000 |   100.00 % |  3.26 ms |       4656168 |       496664 |    89.33 % | Test::foo
     9000 |    90.00 % |  1.51 ms |       4694680 |       951176 |    79.74 % | Test::foo
    10000 |   100.00 % |  3.11 ms |       5112272 |       952768 |    81.36 % | Test::foo
</code>```

From a web (Apache or FPM for example) request, you can use the function $runs = gc_stats(); to access this information and write it to a log file.

based on this information you can make the only decision possible to optimize: To enable or disable the GC in your script depending on how efficient it runs.

Body:
In general PHPs memory management works out of the box for all variables that you declare and use. Using the concept refcounting, PHP sees if a variable is not used anymore and then automatically cleans it up.

The garbage collector is only interesting for the cases where objects have cyclic references, A points to B, B points back to A. In this case refcounting doesn't work.

If there are exactly 10.000 objects in PHP memory that are potentically cyclic, potentially not used anymore, then the PHP garbage collector triggers if it enabled, which it is by default. You can disable or enable it with gc_enable() and gc_disable() at runtime.

You can also call gc_collect_cycles() to cleanup these objects manually.

But how to optimize this process, if you need to? Running the cycle collector doesn't have to be efficient or useful, from the 10.000 potential objects, many of them could still be in use and cannot be cleaned up. In this case you are wasting CPU cycles to check all objects and deciding not to clean them up. There will be no memory reduction if you do this.

Usually the GC only triggers in long running scripts, and only sometimes in short web-requests when they create too many objects. In general you shouldn't think about this too much, because the defaults work for 99% of the use-cases.

With the "garbage_stats" PHP extension you can access metrics and stats about how efficient and fast the GC ran and how much memory was reduced. It works on PHP 7+ (because hooks are only available since then): https://github.com/tideways/php_garbage_stats

If you have installed the extension, you can see garbage collection stats for CLI scripts by calling them:

$ php -dgc_stats.enable=1 -dgc_stats.show_report=1 test.php

Found 7 garbage collection runs in current script.

Collected | Efficency% | Duration | Memory Before | Memory After | Reduction% | Function
----------|------------|----------|---------------|--------------|------------|---------
        0 |     0.00 % |  0.01 ms |        365824 |       366320 |    -0.14 % | gc_collect_cycles
    10000 |   100.00 % |  2.75 ms |       4651320 |       491816 |    89.43 % | foo
    10000 |   100.00 % |  3.54 ms |       4652784 |       493280 |    89.40 % | foo
    10000 |   100.00 % |  2.11 ms |       4654248 |       494744 |    89.37 % | foo
    10000 |   100.00 % |  3.26 ms |       4656168 |       496664 |    89.33 % | Test::foo
     9000 |    90.00 % |  1.51 ms |       4694680 |       951176 |    79.74 % | Test::foo
    10000 |   100.00 % |  3.11 ms |       5112272 |       952768 |    81.36 % | Test::foo

From a web (Apache or FPM for example) request, you can use the function $runs = gc_stats(); to access this information and write it to a log file.

based on this information you can make the only decision possible to optimize: To enable or disable the GC in your script depending on how efficient it runs.


来源: stackexchange

问:
How to set CONSISTENCY level in cassandra permanently?
I want to set consistency level to QUORUM, I am able to do this using cqlsh with using 'CONSISTENCY QUORUM'. but the problem is that that was set to only for that particular time. I don't see any property related to CONSISTENCY level in cassandra.yaml.

Is there any way to set it permanently, any configuration file?

答:
There is no such properly in cassandra.yaml. But you can do it by appropriately setting the below line in bin/cqlsh.py</p>

```<code>self.consistency_level = cassandra.ConsistencyLevel.QUORUM
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is no such properly in cassandra.yaml. But you can do it by appropriately setting the below line in bin/cqlsh.py

self.consistency_level = cassandra.ConsistencyLevel.QUORUM

ContentLicense: CC BY-SA 3.0


问:
Make sure html elements are closed when showing a substring on a webpage (ruby on rails)
Let's say I am doing this:

entries.each do |entry|
  entry[0,1000] + "..."
end

Let's say that entry has a
 and a
 that were not closed, because it chopped the entry in the middle of a list. How can I make sure to close those tags out, so rendering isn't messed up?

I was considering creating a method that found the last index of
 and made sure it was less than the last index of
, etc. This seems cumbersome though. Any ideas on how to solve this with ruby on rails?

Thanks!

答:
Check out the hpricot gem:</p>

```<code>Hpricot("<ul><li>foo<ul><li>bar").to_html
=> "<ul><li>foo<ul><li>bar</li></ul></li></ul>"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Check out the hpricot gem:

Hpricot("<ul><li>foo<ul><li>bar").to_html
=> "<ul><li>foo<ul><li>bar</li></ul></li></ul>"


问:
Loop through an array column in order to find the required values python
I have a minimum and a maximum value, i also have a 70X3 array. I would like to find all the values from the second column of the array which are within the range of the min and max value and export all 3 columns of the array for those values.

For example

```<code>A=[2,3,4
   3,5,6
   5,5,5
   5,6,7
   10,11,22
   3,50,6]
</code>```

Max value is 11 and min is 5 the result of the matrix would be something like

```<code>B=[3,5,6
   5,5,5
   5,6,7
   10,11,22]
</code>```

Up till now i what i did is :

```<code>for i in MatrixA[:,1]):
    if i<maximum and i>minimum:
        aa.append(i)
aa=np.asarray(aa)
</code>```

But this only finds the range of values i need from the second column and not the corresponding values from column 1 and 3

Body:
I have a minimum and a maximum value, i also have a 70X3 array. I would like to find all the values from the second column of the array which are within the range of the min and max value and export all 3 columns of the array for those values.

For example

A=[2,3,4
   3,5,6
   5,5,5
   5,6,7
   10,11,22
   3,50,6]

Max value is 11 and min is 5 the result of the matrix would be something like

B=[3,5,6
   5,5,5
   5,6,7
   10,11,22]

Up till now i what i did is :

for i in MatrixA[:,1]):
    if i<maximum and i>minimum:
        aa.append(i)
aa=np.asarray(aa)

But this only finds the range of values i need from the second column and not the corresponding values from column 1 and 3

Body:
You can use

A[numpy.logical_and(5 <= A[:, 1], A[:, 1] <= 11), :]


问:
How do I automatically update a Subversion working copy?
Does anybody know how I can automatically run svn update? If anybody has a script or something like that, could you show me an example?

答: You can also download and use Commit-Monitor from http://code.google.com/p/commitmonitor/. It monitors SVN repositories for commits and notifies the user when it happens. It is in GNU GPL, ver 2.

OwnerDisplayName: Marko


问:
Show a
 at bottom right corner without position: absolute
I have a
 like below

```<code><div style="right:0px;bottom:0px;position:absolute;">

</div>
</code>```

When my mobile site is opened in portrait mode, this div is displayed correctly at the bottom right corner.
But, when opened in landscape mode it is displayed at corner and overlaps the elements already present.

I want this div to be at the bottom of all elements at the bottom right corner of the page. How do I do it?

答:
I would suggest to use flexbox - but it could need to reorganise a little your css code

.page {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  height:100vh;
}

.element {
  height: 10px;
  width: 80%;
  border: 1px solid #000;
  padding: 20px 0;
}

.element.bottom {
  margin-top: auto;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element bottom">
  </div>
</div></code>```

Title: Show a <div> at bottom right corner without position: absolute

Body:
I have a
 like below

When my mobile site is opened in portrait mode, this div is displayed correctly at the bottom right corner.
But, when opened in landscape mode it is displayed at corner and overlaps the elements already present.

I want this div to be at the bottom of all elements at the bottom right corner of the page. How do I do it?

Body:
I would suggest to use flexbox - but it could need to reorganise a little your css code

.page {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  height:100vh;
}

.element {
  height: 10px;
  width: 80%;
  border: 1px solid #000;
  padding: 20px 0;
}

.element.bottom {
  margin-top: auto;
  background: red;
}

<div class="page">
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element">
  </div>
  <div class="element bottom">
  </div>
</div>


问:
How to make table borders invisible with CSS
I know this is an oft asked question, but I've tried some of the solutions (such as How to make separating lines/borders in a table disappear with CSS?) but I still can't quite get it.

I have defined via css a table structure with alternating row colors. I'd like the (in particular vertical) borders between teh cells to be invisible and so suppose I either need a zero td border width, or the alternating td border colors to be the same as the background colors.

Example below is what I've tried, in calling a table1 id from html, I get a nice alternating colored row table but with obvious cell borders still - appreciate your help.

#table1 table, tr, td, th {
     border: 0;
}

#table1 tbody tr:nth-child(odd) {
     background-color: #A3B9D2;
}

#table1 tbody tr:nth-child(even) {
     background-color: #E7EDF3;
}
```

<p>and then sample html;</p>

<pre class="lang-html prettyprint-override"><code><table id="table1" >
   <tr>
     <td>Test</td><td>(value)</td>
   </tr>
   <tr>
     <td>Test2</td><td>(value2)</td>
   </tr>
</table>
</code>```

答:
Try this:</p>

```<code>table,td,tr,th{
  border:0;
}
</code>```

Body:
I know this is an oft asked question, but I've tried some of the solutions (such as How to make separating lines/borders in a table disappear with CSS?) but I still can't quite get it.

I have defined via css a table structure with alternating row colors. I'd like the (in particular vertical) borders between teh cells to be invisible and so suppose I either need a zero td border width, or the alternating td border colors to be the same as the background colors.

Example below is what I've tried, in calling a table1 id from html, I get a nice alternating colored row table but with obvious cell borders still - appreciate your help.

#table1 table, tr, td, th {
     border: 0;
}

#table1 tbody tr:nth-child(odd) {
     background-color: #A3B9D2;
}

#table1 tbody tr:nth-child(even) {
     background-color: #E7EDF3;
}

and then sample html;

     Test	(value)

     Test2	(value2)

Body:
Try this:

table,td,tr,th{
  border:0;
}


问:
Vim - don't delete upon visual paste
Copying a word into a register, selecting a different word with visual mode, and pasting over the second word deletes the original word in the register.

For example, running vey on Word_1, then running vep on Word_2 now puts Word_2 in the "* register. I would like the "* register to maintain the Word_1 value. Any ideas?

I was thinking of mapping paste in visual mode to a custom range function, saving the register before pasting, and then restoring the register after pasting. I just need some help doing that.

答:
I need this so often, I wrote a plugin to simplify and allow maximum speed: ReplaceWithRegister.

This plugin offers a two-in-one gr command that replaces text covered by a {motion} / text object, entire line(s) or the current selection with the contents of a register; the old text is deleted into the black-hole register, i.e. it's gone. It transparently handles many corner cases and allows for a quick repeat via the standard . command. Should you not like it, its page has links to alternatives.

Title: Vim - don't delete upon visual paste


问:
Sql Custom Pivot - Is this possible?
I am using sql server 2014

I have a set of data rows like this in #TEMP_TABLE:

```<code>SCORE_ID     DAY_ID      DAY     OPEN    CLOSED     DATE       STATUS
   1          1          Mon     1pm      4pm     1/1/17     green
   2          1          Mon     2pm      4pm     1/1/17     green
   3          1          Mon     3pm      5pm     1/1/17     red
   4          1          Mon     4pm      6pm     1/2/17     yellow
   5          1          Mon     5pm      7pm     1/2/17     yellow

   6          2          Tues    1pm      4pm     1/1/17     green
   7          2          Tues    2pm      4pm     1/1/17     green
   8          2          Tues    3pm      5pm     1/1/17     red
   9          2          Tues    4pm      6pm     1/2/17     yellow
   10         2          Tues    5pm      7pm     1/2/17     yellow

   11         5          Fri     12am     12am    1/1/17     green
</code>```

I want to try and pivot my data table so it can look like this. The column names will always be constant, but the values will vary. We can ignore SCORE_ID and DAY_ID.:

```<code> DATE       STATUS      Mon        Tues      Wed      Thurs       Fri
 1/1/17     green       1-4pm      1-4pm      -         -         12am-12am
 1/1/17     green       2-4pm      2-4pm      -         -         -
 1/1/17     red         3-5pm      3-5pm      -         -         -
 1/2/17     yellow      4-6pm      4-6pm      -         -         -
 1/2/17     yellow      5-7pm      5-7pm      -         -         -
</code>```

I tried to google how to use PIVOT, but I feel like the ones I did find don't really apply to how I want my data to be structured.

```<code>select DATE, STATUS, 'Mon', 'Tues', 'Wed, 'Thurs', Fri'
from (
    select DATE, STATUS
    from #TEMP_TABLE
) d

...
</code>```

Is the way I want to structure it possible?

答:
Heres a long winded way of doing a kind of pivot table manually.
It confirms what jyelle said though, you can't consolidate a friday timespan for a different period... And you'd have to keep joining back for each day more times than just Mon, Tues, Fri.. At least I got all 11 facts in my result in just 6 rows.</p>

Title: Sql Custom Pivot - Is this possible?

Body:
I am using sql server 2014

I have a set of data rows like this in #TEMP_TABLE:

SCORE_ID     DAY_ID      DAY     OPEN    CLOSED     DATE       STATUS
   1          1          Mon     1pm      4pm     1/1/17     green
   2          1          Mon     2pm      4pm     1/1/17     green
   3          1          Mon     3pm      5pm     1/1/17     red
   4          1          Mon     4pm      6pm     1/2/17     yellow
   5          1          Mon     5pm      7pm     1/2/17     yellow

   6          2          Tues    1pm      4pm     1/1/17     green
   7          2          Tues    2pm      4pm     1/1/17     green
   8          2          Tues    3pm      5pm     1/1/17     red
   9          2          Tues    4pm      6pm     1/2/17     yellow
   10         2          Tues    5pm      7pm     1/2/17     yellow

   11         5          Fri     12am     12am    1/1/17     green

I want to try and pivot my data table so it can look like this. The column names will always be constant, but the values will vary. We can ignore SCORE_ID and DAY_ID.:

 DATE       STATUS      Mon        Tues      Wed      Thurs       Fri
 1/1/17     green       1-4pm      1-4pm      -         -         12am-12am
 1/1/17     green       2-4pm      2-4pm      -         -         -
 1/1/17     red         3-5pm      3-5pm      -         -         -
 1/2/17     yellow      4-6pm      4-6pm      -         -         -
 1/2/17     yellow      5-7pm      5-7pm      -         -         -

I tried to google how to use PIVOT, but I feel like the ones I did find don't really apply to how I want my data to be structured.

select DATE, STATUS, 'Mon', 'Tues', 'Wed, 'Thurs', Fri'
from (
    select DATE, STATUS
    from #TEMP_TABLE
) d

...

Is the way I want to structure it possible?


问:
How to trigger canvas drawing line animation without actual mouse move?
I am currently figuring out how to draw lines on page load without even having to actually moving the mouse to draw

Here is my code which draws line only when mouse is moved.

https://codepen.io/arvi/pen/RgYZqB

I added a "load" event listener and tied it to documentMouseMoveHandler but it seems not the solution for this scenario.

```<code>window.addEventListener('load', documentMouseMoveHandler, false);
</code>```

Is it possible?

答:
Ok do something like this until you get a mouse event , take random moue point in a interval if mouse event came, then remove it;</p>

```<code>var intervalId;
function documentMouseMoveHandler(event) {
  if (!event) {
    intervalId = setInterval(function () {
       mouseX = Math.floor(Math.random() * (window.innerWidth - 1));
       mouseY = Math.floor(Math.random() * (window.innerHeight + 1));
      }, 3000);
    return;
  }
  if (event && intervalId) {
    clearInterval(intervalId);
  }

  mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
  mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}`
</code>```

Body:
I am currently figuring out how to draw lines on page load without even having to actually moving the mouse to draw

Here is my code which draws line only when mouse is moved.

https://codepen.io/arvi/pen/RgYZqB

I added a "load" event listener and tied it to documentMouseMoveHandler but it seems not the solution for this scenario.

window.addEventListener('load', documentMouseMoveHandler, false);

Is it possible?

Body:
Ok do something like this until you get a mouse event , take random moue point in a interval if mouse event came, then remove it;

var intervalId;
function documentMouseMoveHandler(event) {
  if (!event) {
    intervalId = setInterval(function () {
       mouseX = Math.floor(Math.random() * (window.innerWidth - 1));
       mouseY = Math.floor(Math.random() * (window.innerHeight + 1));
      }, 3000);
    return;
  }
  if (event && intervalId) {
    clearInterval(intervalId);
  }

  mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
  mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}`


问:
What is the best way to chain observables in Angular?
If I have a service call that relies on the result of another service call what is the best way to chain them?

myService.getStuffFromServer().subscribe(data => {
  let manipulatedData = functionThatManipulatesData(data);
  myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
    doStuffWithMoreData(moreData);
  });
});
```

Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?

答:
```<code>myService.getStuffFromServer()
  .subscribe(data => {
     let manipulatedData = functionThatManipulatesData(data);
     return myService.getMoreStuffFromServer(manipulatedData);
  })
  .subscribe(moreData => {
     doStuffWithMoreData(moreData);
  });
</code>```

Body:
If I have a service call that relies on the result of another service call what is the best way to chain them?

myService.getStuffFromServer().subscribe(data => {
  let manipulatedData = functionThatManipulatesData(data);
  myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
    doStuffWithMoreData(moreData);
  });
});

Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?


问:
Match a set of characters from one table into the records of an other table
I have two tables (T-SQL):

```<code>tblInvalidCharactersList         tblMonthsRecords
+-----------+-----------+        +--------+-------------+
| CodePoint | Character |        | RecRef | Name        |
+-----------+-----------+        +--------+-------------+
|    38     |     &     |        | 21     | Firs> name  |
+-----------+-----------+        +--------+-------------+
|    64     |     @     |        | 89     | @Second name|
+-----------+-----------+        +--------+-------------+
|    62     |     >     |        | 321    | Third n«me  |
+-----------+-----------+        +--------+-------------+
|    171    |     «     |        | 381    | Fourth name |
+-----------+-----------+        +--------+-------------+
</code>```

I want to find those records of the tblMonthsRecords which have at least  one (or more) character(s) from the Character column of the tblInvalidCharactersList table.

I tried:

```<code>SELECT
    [RecRef],
    [Name]
FROM [tblMonthsRecords]
WHERE [Name] IN (SELECT Character FROM [tblInvalidCharactersList])
</code>```

and it returns no results at all.

I even tried the NOT IN clause and as you may guess, returns all records.

The reason why I am not hardcoding the characters list within a LIKE clause is because I want the list to be dynamically updated.

You can think the tblInvalidCharactersList as a characters "black list".

答:
IN will look for exact character match in Name column it will not search for the character in Name column

Use LIKE operator

```<code>select Distinct a.*
from tblMonthsRecords a
join tblInvalidCharactersList b
  on a.Name like '%' + b.Character + '%'
</code>```

Another way using charindex

```<code>charindex(b.Character,a.Name) > 0
</code>```

Body:
I have two tables (T-SQL):

tblInvalidCharactersList         tblMonthsRecords
+-----------+-----------+        +--------+-------------+
| CodePoint | Character |        | RecRef | Name        |
+-----------+-----------+        +--------+-------------+
|    38     |     &     |        | 21     | Firs> name  |
+-----------+-----------+        +--------+-------------+
|    64     |     @     |        | 89     | @Second name|
+-----------+-----------+        +--------+-------------+
|    62     |     >     |        | 321    | Third n«me  |
+-----------+-----------+        +--------+-------------+
|    171    |     «     |        | 381    | Fourth name |
+-----------+-----------+        +--------+-------------+

I want to find those records of the tblMonthsRecords which have at least  one (or more) character(s) from the Character column of the tblInvalidCharactersList table.

I tried:

SELECT
    [RecRef],
    [Name]
FROM [tblMonthsRecords]
WHERE [Name] IN (SELECT Character FROM [tblInvalidCharactersList])

and it returns no results at all.

I even tried the NOT IN clause and as you may guess, returns all records.

The reason why I am not hardcoding the characters list within a LIKE clause is because I want the list to be dynamically updated.

You can think the tblInvalidCharactersList as a characters "black list".

Body:
IN will look for exact character match in Name column it will not search for the character in Name column

Use LIKE operator

select Distinct a.*
from tblMonthsRecords a
join tblInvalidCharactersList b
  on a.Name like '%' + b.Character + '%'

Another way using charindex

charindex(b.Character,a.Name) > 0


问:
NLog with Postsharp not logging
I found out what the problem is. There is no problem with the code. The problem that I wrote column name incorrect in the query. I do not know how I missed such a thing, but thank you for all your help. You can use the codes for the NLog if you want.

( I trying to Logging with NLog into AOP. I working Winform and using Postsharp. NLog codes into ExceptionLoggingAttribute.cs . This codes studies in Form1.cs but does not working in Aspect. Please Help me! )

AOP inside

namespace LogLibrary
{
    [PSerializable]
    public class ExceptionLoggingAttribute : OnExceptionAspect
    {
        public FlowBehavior flowbehavior { get; set; }
        public override void OnException(MethodExecutionArgs args)
        {
            NLog.Logger logger = LogManager.GetLogger("databaseLogger");
            logger.Error(args.Exception.Message);
            logger.Fatal(args.Exception.Message);
            logger.Debug(args.Exception.Message);
            logger.Trace(args.Exception.Message);
            args.FlowBehavior = FlowBehavior.Continue;
        }
  }
```

<p>Nlog.Config İnside</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <variable name="myvar" value="myvalue"/>

  <targets>

    <target name="database" xsi:type="Database"

      connectionStringName="NLogConn"

      commandText="exec dbo.dlog @username,@ErrorName,@MethodName,@StackName, @Date_Time">

      <parameter name="@username" layout="${identity}"/>
      <parameter name="@ErrorName" layout="${message}"/>
      <parameter name="@MethodName" layout="${machinename}"/>
      <parameter name="@StackName" layout="${stacktrace}"/>
      <parameter name="@Date_Time" layout="${date}"/>

    </target>

  </targets>

  <rules>
    <logger name="databaseLogger" minlevel="Trace" writeTo="database" />
  </rules>
</nlog>
</code>```

App.Config İnside

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="NLogConn" connectionString="Data Source=DMGM0349997\MSSQLSERVER01; Initial Catalog=deneme; Integrated Security=true;"  providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
```

<p>Form1 inside</p>

<pre class="lang-cs prettyprint-override"><code>using System.Windows.Forms;
using PostSharp.Aspects;
using NLog;
using LogLibrary;

namespace LogApp
{
    [ExceptionLogging]
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            throw new Exception("bla bla");
        }
    }
}
</code>```

I hope this photo helps you for understand me

答:
You have to enable first the internal log, set internalLogLevel on "info":

```<code>internalLogLevel="Info" internalLogFile="c:\temp\nlog-internal.log"
</code>```

If there is still no internalLogFile, then NLog can't find you nlog.config. Check the location of nlog.config.

Alternative you read it config like this:

```<code>LogManager.Configuration = new XmlLoggingConfiguration("pathTo_Nlog.config")
</code>```

Or set-up the config on C#

Title: NLog with Postsharp not logging

Body:
I found out what the problem is. There is no problem with the code. The problem that I wrote column name incorrect in the query. I do not know how I missed such a thing, but thank you for all your help. You can use the codes for the NLog if you want.

( I trying to Logging with NLog into AOP. I working Winform and using Postsharp. NLog codes into ExceptionLoggingAttribute.cs . This codes studies in Form1.cs but does not working in Aspect. Please Help me! )

AOP inside

namespace LogLibrary
{
    [PSerializable]
    public class ExceptionLoggingAttribute : OnExceptionAspect
    {
        public FlowBehavior flowbehavior { get; set; }
        public override void OnException(MethodExecutionArgs args)
        {
            NLog.Logger logger = LogManager.GetLogger("databaseLogger");
            logger.Error(args.Exception.Message);
            logger.Fatal(args.Exception.Message);
            logger.Debug(args.Exception.Message);
            logger.Trace(args.Exception.Message);
            args.FlowBehavior = FlowBehavior.Continue;
        }
  }

Nlog.Config İnside

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <variable name="myvar" value="myvalue"/>

  <targets>

    <target name="database" xsi:type="Database"

      connectionStringName="NLogConn"

      commandText="exec dbo.dlog @username,@ErrorName,@MethodName,@StackName, @Date_Time">

      <parameter name="@username" layout="${identity}"/>
      <parameter name="@ErrorName" layout="${message}"/>
      <parameter name="@MethodName" layout="${machinename}"/>
      <parameter name="@StackName" layout="${stacktrace}"/>
      <parameter name="@Date_Time" layout="${date}"/>

    </target>

  </targets>

  <rules>
    <logger name="databaseLogger" minlevel="Trace" writeTo="database" />
  </rules>
</nlog>

App.Config İnside

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="NLogConn" connectionString="Data Source=DMGM0349997\MSSQLSERVER01; Initial Catalog=deneme; Integrated Security=true;"  providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Form1 inside

using System.Windows.Forms;
using PostSharp.Aspects;
using NLog;
using LogLibrary;

namespace LogApp
{
    [ExceptionLogging]
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            throw new Exception("bla bla");
        }
    }
}

I hope this photo helps you for understand me

Body:
You have to enable first the internal log, set internalLogLevel on "info":

internalLogLevel="Info" internalLogFile="c:\temp\nlog-internal.log"

If there is still no internalLogFile, then NLog can't find you nlog.config. Check the location of nlog.config.

Alternative you read it config like this:

LogManager.Configuration = new XmlLoggingConfiguration("pathTo_Nlog.config")

Or set-up the config on C#


问:
VUE 2 trouble passing through data to component
I am current new to Vue and have trouble passing data from an api to a view to a component in Vue.

This is my view:

```<code><template lang="pug">
div.mt-3
    licenses(v-show="navItem == 'Licenses'", :data="data")
    products(v-show="navItem == 'Products'")
    users(v-show="navItem == 'Users'")
    locations(v-show="navItem == 'Locations'")
</template>

<script>
import licenses from '../components/licenses.vue';
import products from '../components/products.vue';
import users from '../components/users.vue';
import locations from '../components/locations.vue';

 export default {
        components:{
            licenses,
            products,
            users,
            locations
        },

        mounted(){

            window.axios.get('/clients/1').then((response) => {
                this.data = response.data;
            });

        }
    }
</code>```

my component:

```<code><template lang="pug">
    .row.mt-3
        .col-sm-4(v-for="item in data.licenses")
        //.col-sm-4(v-for="item in data.licenses")
            b-card.mb-2( :header="item.product.name")
                h4.text-capitalize(slot="header") {{item.product.name}} License Usage
                p {{item.product.description}}
                div.text-center
                    .col-sm-10.offset-1
                        div.progress-number {{item.amountUsed}}/{{item.amountAllocated}}
                        b-progress(v-model="item.amountUsed", :max="item.amountAllocated", animation=true)
                            span.progress-item
                        p.text-center.mt-3 This means you have {{item.amountRemaining}} licenses left.
                .form-group.mt-1
                    label LICENSES KEY
                    input.form-control.text-center(:placeholder="item.licenseKey", readonly)

</template>
<style>

</style>
<script>
    export default{
        props:{
            data
        }
    }
</script>
</code>```

Is it possible to use data which has been passed in a v-for?

Sorry I am not having much luck with the documentation, please help!

答:
You should initialize the data property in tour data option beforehand

```<code>export default {
    data(){
        return{
            data: null
        }
    },
    components:{
        licenses,
        bproducts,
          users,
        locations
    },

    mounted(){

        window.axios.get('/clients/1').then((response) => {
            this.data = response.data;
        });

    }
}
</code>```

Then you can set the value in your axios request this.data = response.data

See declaring reactive properties in reactivity in depth.

Body:
I am current new to Vue and have trouble passing data from an api to a view to a component in Vue.

This is my view:

<template lang="pug">
div.mt-3
    licenses(v-show="navItem == 'Licenses'", :data="data")
    products(v-show="navItem == 'Products'")
    users(v-show="navItem == 'Users'")
    locations(v-show="navItem == 'Locations'")
</template>

Is it possible to use data which has been passed in a v-for?

Sorry I am not having much luck with the documentation, please help!

Body:
You should initialize the data property in tour data option beforehand

export default {
    data(){
        return{
            data: null
        }
    },
    components:{
        licenses,
        bproducts,
          users,
        locations
    },

    mounted(){

        window.axios.get('/clients/1').then((response) => {
            this.data = response.data;
        });

    }
}

Then you can set the value in your axios request this.data = response.data

See declaring reactive properties in reactivity in depth.


问:
Processing large xlsx file
I need to auto-fit all rows in large (30k+ rows) xlsx file.

The following code via apache poi works on small files, but goes out with OutOfMemoryError on large ones:

```<code>Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);

for (Row row : sheet) {
    row.setHeight((short) -1);
}

workbook.write(outputStream);
</code>```

Update: Unfortunately, increasing heap size is not an option - OutOfMemoryError appears at -Xmx1024m and 30k rows is not an upper limit.

答:
I used SAX parser to process XML structure. It works for XLSX files.

https://stackoverflow.com/a/44969009/4587961

Title: Processing large xlsx file

Body:
I need to auto-fit all rows in large (30k+ rows) xlsx file.

The following code via apache poi works on small files, but goes out with OutOfMemoryError on large ones:

Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);

for (Row row : sheet) {
    row.setHeight((short) -1);
}

workbook.write(outputStream);

Update: Unfortunately, increasing heap size is not an option - OutOfMemoryError appears at -Xmx1024m and 30k rows is not an upper limit.


问:
Create Procedure Permission ONLY
I have a requirement in SQL Server 2008 in development database

Only DBA's ( who are database owners ) can create, alter tables .
Developer's should not create or alter tables .

Developers can create/alter Stored Procedure/User Defined functions
in dbo schema and can execute SP/UDF.

Developers should have SELECT,INSERT,DELETE,UPDATE on tables (
tables in dbo schema

How to achieve this using GRANT statement

Found a sample solution from Google, but still have issue

```<code>CREATE LOGIN testdev WITH PASSWORD = 'sldkjlkjlkj 987kj//'

CREATE USER testdev

GRANT ALTER ON SCHEMA::dbo TO testdev
GRANT CREATE PROCEDURE TO testdev
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO testdev

CREATE TABLE mysig (a int NOT NULL)
EXECUTE AS USER = 'testdev'
go

CREATE PROCEDURE slaskis AS PRINT 12
go

CREATE TABLE hoppsan(a int NOT NULL) -- FAILS!
go

INSERT mysig (a) VALUES(123)
go

REVERT
go

DROP PROCEDURE slaskis
DROP TABLE mysig
DROP USER testdev
DROP LOGIN testdev
</code>```

The syntax above able to block developer to create table but cant block developer to use SSMS design and alter the table.

Thanks.

答:
The following Code will Create the user and role in sql server 2012 :

```<code> USE PermissionDB;
 ---Select Your database
 CREATE ROLE Employee;
 ---Create role
 CREATE USER Employee1 Without Login;
 ---Create User

 ----Execute the Above query
 EXEC sp_addrolemember @rolename = 'Employee', @membername = 'Employee1';
</code>```

Hope This would be helpful....

Title: Create Procedure Permission ONLY

Body:
I have a requirement in SQL Server 2008 in development database

Only DBA's ( who are database owners ) can create, alter tables .
Developer's should not create or alter tables .

Developers can create/alter Stored Procedure/User Defined functions
in dbo schema and can execute SP/UDF.

Developers should have SELECT,INSERT,DELETE,UPDATE on tables (
tables in dbo schema

How to achieve this using GRANT statement

Found a sample solution from Google, but still have issue

CREATE LOGIN testdev WITH PASSWORD = 'sldkjlkjlkj 987kj//'

CREATE USER testdev

GRANT ALTER ON SCHEMA::dbo TO testdev
GRANT CREATE PROCEDURE TO testdev
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO testdev

CREATE TABLE mysig (a int NOT NULL)
EXECUTE AS USER = 'testdev'
go

CREATE PROCEDURE slaskis AS PRINT 12
go

CREATE TABLE hoppsan(a int NOT NULL) -- FAILS!
go

INSERT mysig (a) VALUES(123)
go

REVERT
go

DROP PROCEDURE slaskis
DROP TABLE mysig
DROP USER testdev
DROP LOGIN testdev

The syntax above able to block developer to create table but cant block developer to use SSMS design and alter the table.

Thanks.

Body:
The following Code will Create the user and role in sql server 2012 :

 USE PermissionDB;
 ---Select Your database
 CREATE ROLE Employee;
 ---Create role
 CREATE USER Employee1 Without Login;
 ---Create User

 ----Execute the Above query
 EXEC sp_addrolemember @rolename = 'Employee', @membername = 'Employee1';

Hope This would be helpful....


问:
Creating View Using Synonyms in a Database Project (Visual Studio 2012)

I am hitting my head against the wall for a weird error I am getting in VS2012.
I have a database project which includes some Synonyms. They are basically table references to another database in order to avoid dynamic SQL generation. I already added the required reference database for the Synonyms. Everything works great except a couple of views that are using some of those Synonyms! Since I am using the same Synonyms in my stored procedures and they are not causing any build failure, I am not sure why the views are causing problem.

The error message says: "SQL05313: Synonym 'xxx' refers to an invalid object.'
Here is a sample code -

dbo.MyTable.sql...

    CREATE SYNONYM [dbo].[MyTable] FOR [$(FOO_DB)].[dbo].[MyTable];

dbo.MyProc

    CREATE [dbo].[MyProc] AS SELECT col1, col2, col3 FROM [dbo].[MyTable];

    SUCCESS: this works

dbo.MyView.sql...

    CREATE VIEW [dbo].[MyView] AS SELECT col1, col2, col3 FROM [dbo].[MyTable];

    ERROR: SQL05313 Synonym '[dbo].[MyTable]' refers to an invalid object.

Has anyone else faced this issue? If yes, I appreciate your assistance :)

答:
I got this error, and I eventually found that I had run CREATE SYNONYM fred FOR ... instead of CREATE SYNONYM **dbo**.fred FOR ...
It therefore created the synonym in my personal schema, instead of dbo, and this stopped the CREATE VIEW.
I know that your code includes [dbo].[MyTable], but do you have an identical synonym in your own schema, from a previous CREATE SYNONYM command that did not include the [dbo], which might be confusing the CREATE VIEW command?


问:
Assign a value to drop down list on page_load
I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,

```<code>if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
    {
        string selectedReg = Request.QueryString["selectedReg"];
        ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
    }
</code>```

If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance

答:
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.

After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        FillDropDown();

        if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
        {
            string selectedReg = Request.QueryString["selectedReg"];
            ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
        }
    }

   protected void FillDropDown()
    {
        using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);

            DataTable dt = new DataTable("Test");
            adp.Fill(dt);

            ddlVehicleReg.DataValueField = "Id";
            ddlVehicleReg.DataTextField = "Value";
            ddlVehicleReg.DataSource = dt;
            ddlVehicleReg.DataBind();
        }
    }
</code>```

Body:
I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,

if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
    {
        string selectedReg = Request.QueryString["selectedReg"];
        ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
    }

If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance

Body:
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.

After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load

protected void Page_Load(object sender, EventArgs e)
    {
        FillDropDown();

        if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
        {
            string selectedReg = Request.QueryString["selectedReg"];
            ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
        }
    }

   protected void FillDropDown()
    {
        using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);

            DataTable dt = new DataTable("Test");
            adp.Fill(dt);

            ddlVehicleReg.DataValueField = "Id";
            ddlVehicleReg.DataTextField = "Value";
            ddlVehicleReg.DataSource = dt;
            ddlVehicleReg.DataBind();
        }
    }


问:
What is the difference between DoS and Brute Force attacks?
I was reading about DoS attacks on Apache servers but the "Brute Force" word pops up sometimes I know DoS attacks but "Brute Force" seems to be similar, is there a difference or it is just another word of DoS?</p>

答:
Just to give an example of a DoS attack that doesn't involve brute force, pretend that there's a website that locks a user account after three failed login attempts.  I know that you have an account on that site and I know that your username is jdoe.  I decide I don't want you to be able to use the site so I try to log in as you three times, failing each time.  Your account gets locked out and you have to call the admin to get it reactivated.  Then I do it again the next week just to make a nuisance of myself.  In essence I'm using the site's lockout feature to deny service to you, but brute force isn't involved.

I suspect that the confusion between the two stems from the following. The most popular cases of DoS involve overwhelming servers with network requests. Sounds like somebody is applying "brute force" to the server, and in common everyday language that might be right.  But really brute force has a special meaning in computing. It describes algorithms that exhaustively search a solution space for a correct solution, instead of using more "refined" methods like heuristics, intelligent guessing, or whatever. So in security a brute force attack involves trying all possible keys, all possible passwords, etc.

OwnerDisplayName: Sulaiman

LastEditorDisplayName: Jeremy Ruten


问:
Force R to print 0/0 as 1
When I execute 0 / 0 in R, I would get a NaN as an output. But is there any way I could print 0 / 0 as 1? I know I could use some if statements to achieve it. I would like to know if there is any other way to achieve this.

答:
You could define your own division symbol especially for this. For example,</p>

```<code>'|' <- function(a,b)ifelse(a==0 & b==0, 1, a/b)

> 0|0
[1] 1
> 3|4
[1] 0.75
</code>```

Title: Force R to print 0/0 as 1

Body:
You could define your own division symbol especially for this. For example,

'|' <- function(a,b)ifelse(a==0 & b==0, 1, a/b)

> 0|0
[1] 1
> 3|4
[1] 0.75


问:
Unable to show legend in seaborn distplot
I am new to plotting in python and trying following code to plot distribution in seaborn but unable to see the legend, i.e., test_label1 and test_label1 on the plot.

```<code>import matplotlib.pylab as plt
import seaborn as sns
import numpy as np

plt.figure("Test Plots")
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1, label='test_label1', color="0.25")
sns.distplot(lst2, label='test_label2', color="0.25")

plt.show()
</code>```

答:
As you have already labelled your plots using label= inside your sns.distplot then all you have to do is show your legend. This is done by adding plt.legend() just before plt.show()

More information on matplotlib legends can be found in the documentation

Body:
I am new to plotting in python and trying following code to plot distribution in seaborn but unable to see the legend, i.e., test_label1 and test_label1 on the plot.

import matplotlib.pylab as plt
import seaborn as sns
import numpy as np

plt.figure("Test Plots")
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1, label='test_label1', color="0.25")
sns.distplot(lst2, label='test_label2', color="0.25")

plt.show()


问:
PL/SQL Calculate sum of start/end dates difference
I have a table with start and end dates of non-attendance and  i want to get the sum of days of absenteeism grouped by id and by month. I do this by calculating difference between dates +1. The problem is that sometimes dates periods overlap with each others. Here is an example:

```<code>ID   ABS_START    ABS_END        NBR_ABS

5    04/02/2016   04/02/2016         1
5    05/02/2016   05/02/2016         1
5    06/02/2016   07/02/2016         2
5    07/02/2016   20/02/2016         14
5    08/02/2016   14/02/2016         7

NBR_ABS = number of absences relative to dates period
</code>```

Expected results:

```<code>ID   ABS_MONTH    NBR_ABS_MONTH

5    2016/02           17
6    2016/02           0
7    2016/02           5
8    2016/02           13
9    2016/02           2

NBRE_ABS_MONTH = number of absences by id for whole month
</code>```

Is there any way to deal with such issue in oracle environment ?
Thanks for your answers!

答:
One simple way is to get a list of dates in a range and check.  For instance:</p>

```<code>with dates as (
      select (date '2016-02-01') + rownum - 1
      from all_objects
      where rownum <= 29
     )
select i.id, count(*) as absence_201602
from dates cross join
     (select distinct id from t) i
where exists (select 1
              from t
              where t.id = i.id and
                    d.date between t.abs_start and t.abs_end
             )
group by id;
</code>```

Body:
I have a table with start and end dates of non-attendance and  i want to get the sum of days of absenteeism grouped by id and by month. I do this by calculating difference between dates +1. The problem is that sometimes dates periods overlap with each others. Here is an example:

ID   ABS_START    ABS_END        NBR_ABS

5    04/02/2016   04/02/2016         1
5    05/02/2016   05/02/2016         1
5    06/02/2016   07/02/2016         2
5    07/02/2016   20/02/2016         14
5    08/02/2016   14/02/2016         7

NBR_ABS = number of absences relative to dates period

Expected results:

ID   ABS_MONTH    NBR_ABS_MONTH

5    2016/02           17
6    2016/02           0
7    2016/02           5
8    2016/02           13
9    2016/02           2

NBRE_ABS_MONTH = number of absences by id for whole month

Is there any way to deal with such issue in oracle environment ?
Thanks for your answers!

Body:
One simple way is to get a list of dates in a range and check.  For instance:

with dates as (
      select (date '2016-02-01') + rownum - 1
      from all_objects
      where rownum <= 29
     )
select i.id, count(*) as absence_201602
from dates cross join
     (select distinct id from t) i
where exists (select 1
              from t
              where t.id = i.id and
                    d.date between t.abs_start and t.abs_end
             )
group by id;


问:
Head -1 in windows batch file
I'd like to get the first line only from the following command output in windows pe.  See below:

```<code>wmic nic where "NetConnectionStatus=2" get netconnectionid |findstr /v "^Net"|findstr /v "^$"
</code>```

Select -First would be an option, but it doesn't work.
I'm not familiar with windows too much I'm familiar with linux.

How could I get only the first line of the output.

If it's possible without findstr even better.

答:
How to get the first line is described here at SO. But you have to escape the ^ and the | characters like it's said in this guide.

The following snipped will work:

```<code>@echo off

set "command=wmic nic where "netconnectionstatus=2" get netconnectionid ^| findstr /v "^^net" ^| findstr /v "^^$""
echo command: ^<%command%^>

for /f "delims=" %%a in ('%command%') do (
    set tempvar=%%a
    goto :print
)

:print
echo result: %tempvar%
</code>```

I think the last pipe to findstr /v "^^$"" is unnecessary.

Title: Head -1 in windows batch file

Body:
I'd like to get the first line only from the following command output in windows pe.  See below:

wmic nic where "NetConnectionStatus=2" get netconnectionid |findstr /v "^Net"|findstr /v "^$"

Select -First would be an option, but it doesn't work.
I'm not familiar with windows too much I'm familiar with linux.

How could I get only the first line of the output.

If it's possible without findstr even better.

Body:
How to get the first line is described here at SO. But you have to escape the ^ and the | characters like it's said in this guide.

The following snipped will work:

@echo off

set "command=wmic nic where "netconnectionstatus=2" get netconnectionid ^| findstr /v "^^net" ^| findstr /v "^^$""
echo command: ^<%command%^>

for /f "delims=" %%a in ('%command%') do (
    set tempvar=%%a
    goto :print
)

:print
echo result: %tempvar%

I think the last pipe to findstr /v "^^$"" is unnecessary.


问:
pass method with template arguments to a macro
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

```<code>ASSERT_THROW(Matrix<5,1>(), std::runtime_error);
</code>```

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

```<code>warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'
</code>```

Whereas there are no problems with:

```<code>ASSERT_THROW(Matrix<1>(), std::runtime_error);
</code>```

How can I overcome this problem?

Thanks!

答:
the problem is the extra comma, you will need to protect it from the macro. Try </p>

```<code>ASSERT_THROW((Matrix<5,1>()), std::runtime_error);
</code>```

Body:
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws:

ASSERT_THROW(Matrix<5,1>(), std::runtime_error);

(this example doesn't make a lot of sense, of course this shoud not throw, but it is what stayed after simplifying what I had.)

I get this output from MS VC++ 2008:

warning C4002: too many actual parameters for macro 'ASSERT_THROW'
error C2143: syntax error : missing ',' before ';'

Whereas there are no problems with:

ASSERT_THROW(Matrix<1>(), std::runtime_error);

How can I overcome this problem?

Thanks!

Body:
the problem is the extra comma, you will need to protect it from the macro. Try

ASSERT_THROW((Matrix<5,1>()), std::runtime_error);


问:
Storing passport facebook session in Node
I am trying to setup Facebook authentication following the example on passport-facebook GitHub, but I am not getting the session to store. As soon as I log into Facebook and am redirected back to "/", there is no evidence that I am logged in in my application. Since it is directing me back to the successRedirect route when my login is indeed successful on Facebook, it seems that I am missing code needed to save the session.

In my app.js file I have the following.

```<code>       var express = require("express"),
            bodyParser = require("body-parser"),
            passport = require("./auth/local"),
            FacebookStrategy = require("passport-facebook"),
            LinkedInStrategy = require("passport-linkedin"),
            GoogleStrategy = require("passport-google"),
            cookieParser = require('cookie-parser'),
            session = require("express-session"),
            fbStrategy = require("./auth/facebook");
    var  app = express();

app.use(cookieParser());
app.use(session({
    resave: true,
    saveUninitialized: true
}));

app.use(express.static(__dirname + "/public"));
app.set("view engine","ejs");

app.use(passport.initialize());
app.use(passport.session());

app.get('./auth/facebook',
  fbStrategy.authenticate('facebook'
));

app.get('./auth/facebook/callback',
  fbStrategy.authenticate('facebook', {
      successRedirect: "/",
      failureRedirect: '/login' })
);
</code>```

In the route /auth/facebook.js I have the following code

```<code>   var passport = require('passport'),
        FacebookStrategy = require('passport-facebook'),
        authHelpers = require("./_helpers");

    var init = require('./passport');

    init();

    passport.use(new FacebookStrategy({
        clientID: [...],
        clientSecret: [...],
        callbackURL: "callbackurl",
        //for profFields look here for definitions... https://developers.facebook.com/docs/graph-api/reference/v2.5/user
        profileFields: ['id','first_name','last_name','gender','political','verified','currency','birthday']
      },
      function(accessToken, refreshToken, profile, done) {
        function(accessToken, refreshToken, profile, cb) {
function(accessToken, refreshToken, profile, done) {
  knex('user').select('email','user_id').where({facebookID:profile.id})
  .then((user) => {
    if (user.length==0) {
      knex('user').insert({
      email: profile.emails[0].value,
      facebookID:profile.id,
      firstname: profile.name.givenName,
      lastname: profile.name.familyName
      })
      return done(null,user);
    } else {
      return done(null, user);
    }
  })
  .catch((err) => {console.log("problem near line 24 in auth/facebook.js... "+err); return done(err); });
       }
    }));

module.exports = passport;
</code>```

My database configuration is working fine everywhere else, so I did not include the configuration code/file in the above snippets.

答: Please check the code here on https://github.com/rupalipemare/Todo-Demo, wherein there is complete example demonstrating passport authentication using local , facebook, and google.</p>

Body:
I am trying to setup Facebook authentication following the example on passport-facebook GitHub, but I am not getting the session to store. As soon as I log into Facebook and am redirected back to "/", there is no evidence that I am logged in in my application. Since it is directing me back to the successRedirect route when my login is indeed successful on Facebook, it seems that I am missing code needed to save the session.

In my app.js file I have the following.

       var express = require("express"),
            bodyParser = require("body-parser"),
            passport = require("./auth/local"),
            FacebookStrategy = require("passport-facebook"),
            LinkedInStrategy = require("passport-linkedin"),
            GoogleStrategy = require("passport-google"),
            cookieParser = require('cookie-parser'),
            session = require("express-session"),
            fbStrategy = require("./auth/facebook");
    var  app = express();

app.use(cookieParser());
app.use(session({
    resave: true,
    saveUninitialized: true
}));

app.use(express.static(__dirname + "/public"));
app.set("view engine","ejs");

app.use(passport.initialize());
app.use(passport.session());

app.get('./auth/facebook',
  fbStrategy.authenticate('facebook'
));

app.get('./auth/facebook/callback',
  fbStrategy.authenticate('facebook', {
      successRedirect: "/",
      failureRedirect: '/login' })
);

In the route /auth/facebook.js I have the following code

   var passport = require('passport'),
        FacebookStrategy = require('passport-facebook'),
        authHelpers = require("./_helpers");

    var init = require('./passport');

    init();

    passport.use(new FacebookStrategy({
        clientID: [...],
        clientSecret: [...],
        callbackURL: "callbackurl",
        //for profFields look here for definitions... https://developers.facebook.com/docs/graph-api/reference/v2.5/user
        profileFields: ['id','first_name','last_name','gender','political','verified','currency','birthday']
      },
      function(accessToken, refreshToken, profile, done) {
        function(accessToken, refreshToken, profile, cb) {
function(accessToken, refreshToken, profile, done) {
  knex('user').select('email','user_id').where({facebookID:profile.id})
  .then((user) => {
    if (user.length==0) {
      knex('user').insert({
      email: profile.emails[0].value,
      facebookID:profile.id,
      firstname: profile.name.givenName,
      lastname: profile.name.familyName
      })
      return done(null,user);
    } else {
      return done(null, user);
    }
  })
  .catch((err) => {console.log("problem near line 24 in auth/facebook.js... "+err); return done(err); });
       }
    }));

module.exports = passport;

My database configuration is working fine everywhere else, so I did not include the configuration code/file in the above snippets.


问:
Limit iOS App even after the user re-installs it
I created an app that gives the user 3 coins at the first launch.

Once the user finished the 3 coins he should buy unlimited coins by an In-App purchase.

The problem is that if the user doesn't want to buy unlimited coins he can delete the app, install the app again and he will have again the 3 coins again.
And he can do this forever without ever buying the In-App purchase.

Is there a simple way to prevent this? How can I know if a user finished the coins inside the app even after deleting it?

答:
Any local DB, SQLite, Core Data, File Archiving, plist won't survive if app is deleted.
There are three ways to get persisted data after app reinstall on iOS:

Saving the data on server. But this case will only work if user is always logged into account.

Using Keychain to store the data. There are good Keychain implementations like JNKeychain

Using iCloud. Implementing CloudKit in your app will enable you to save data
  corresponding to the iCloud user which can be retrieved later on
  reinstallation.


问:
No Certificates are available provisioning portal
Today I tried to upload a new version of my app, that uses Push Notifications, and XCode showed and error that I didnt have any valid Distribution profile.
When I logged in the Provisioning Profile I saw that ALL my Distribution Profiles had expired, even though the last one, the one I was using for this specific app, was only 2 weeks old.

I tried renewing the profile from XCode but it gives this error No value was provided for the parameter 'certificateIds'. So I tried to make another Distribution Profile, but when I do so it doesnt find any Certificate Available.

I try to do another certificate, clicking on that button, the certificate is created, it appears as a APNs Production iOS but when I go back it keeps saying there are no available Certificates.

So I have no idea what Im doing wrong, I recreated the CertificateSigningRequest and still nothing.
I downloaded and installed the AppleWWDRCA but I dont know what to do with that, I installed it and that's it.

Any ideas? Im completly lost.

答:
May be the certificate you created were APNs certificate.You should create a development certificate.
APNs certificate is only for the purpose of push related use, thats why its not enough to create a provision.That may be issue.</p>


问:
Python py2exe "IOError...unknown url type: https" issue
So my Web Scrapper works fine when ran with IDLE/Python, but when I compile it into a single .exe file (using py2exe), it raises an IOError.

When using urllib module:

```<code>IOError: [Errno url error] unknown url type: 'https'
</code>```

When using requests module:

```<code>requests.exceptions.SSLError: Can't connect to HTTPS URL because the SSL module is not available.
</code>```

I did notice, when compiling with py2exe, it said at the end that several "modules appear to be missing", including a OpenSSL.SSL, and several references to urllib, which might be the problem?

Any ideas, solutions...?

答:
try this out
set "skip_archive": True,"unbuffered": True

```<code>setup(
      version = "1.0",
      name = "MyApplication",
      url = "http://www.example.com",
      author = "yourname",
      author_email = "yourname@gmail.com",
      license = "https://www.binpress.com/license/",
      copyright = 'Copyright (c) 2017 MyApplication',
      windows=[{'script': "yourfile.py","icon_resources": [(0, "youricon.ico")],'copyright': "Copyright (c) 2017 MyApplication"}] ,options={'py2exe':{"skip_archive": True,"unbuffered": True,'packages':['Tkinter','PIL','sip','pyavrophonetic','speech_recognition','simplejson','tkSimpleDialog','tkFileDialog','io','tkMessageBox','Tkconstants','random','pyaudio','os','wave','pocketsphinx','sphinxbase','pyttsx']}}
     )
#name your reqired modules
</code>```

then carefully copy paste the files said missing manually to under dist directory and other files under their respective directory as you can find some files missing under modules. Then make an installer for your exe using Inno Setup. Hope this helps.
EDIT
You can find extra installed modules in location likeD:\Python\Lib\site-packages and most of python's own modules in D:\Python\Lib

Body:
So my Web Scrapper works fine when ran with IDLE/Python, but when I compile it into a single .exe file (using py2exe), it raises an IOError.

When using urllib module:

IOError: [Errno url error] unknown url type: 'https'

When using requests module:

requests.exceptions.SSLError: Can't connect to HTTPS URL because the SSL module is not available.

I did notice, when compiling with py2exe, it said at the end that several "modules appear to be missing", including a OpenSSL.SSL, and several references to urllib, which might be the problem?

Any ideas, solutions...?

Body:
try this out
set "skip_archive": True,"unbuffered": True

setup(
      version = "1.0",
      name = "MyApplication",
      url = "http://www.example.com",
      author = "yourname",
      author_email = "yourname@gmail.com",
      license = "https://www.binpress.com/license/",
      copyright = 'Copyright (c) 2017 MyApplication',
      windows=[{'script': "yourfile.py","icon_resources": [(0, "youricon.ico")],'copyright': "Copyright (c) 2017 MyApplication"}] ,options={'py2exe':{"skip_archive": True,"unbuffered": True,'packages':['Tkinter','PIL','sip','pyavrophonetic','speech_recognition','simplejson','tkSimpleDialog','tkFileDialog','io','tkMessageBox','Tkconstants','random','pyaudio','os','wave','pocketsphinx','sphinxbase','pyttsx']}}
     )
#name your reqired modules

then carefully copy paste the files said missing manually to under dist directory and other files under their respective directory as you can find some files missing under modules. Then make an installer for your exe using Inno Setup. Hope this helps.
EDIT
You can find extra installed modules in location likeD:\Python\Lib\site-packages and most of python's own modules in D:\Python\Lib


问:
connecting to a database in OrientDB console
I'm trying to connect to the GratefulDeadConcerts without any sucess.
I'm using docker.

```<code>orientdb> connect remote:localhost root root

Disconnecting from the database [null]...OK
Connecting to remote Server instance [remote:localhost] with user 'root'...OK
orientdb {server=remote:localhost/}> list databases

Found 5 databases:

* VehicleHistoryGraph (plocal)
* GratefulDeadConcerts (plocal)
* OpenBeer (plocal)
* BetterDemo (plocal)
* Tolkien-Arda (plocal)

orientdb {server=remote:localhost/}> connect plocal:../databases/GratefulDeadConcerts root root

Disconnecting from remote server [remote:localhost/]...
OK
Connecting to database [plocal:../databases/GratefulDeadConcerts] with user 'root'...
Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open local storage '../databases/GratefulDeadConcerts' with mode=rw
        DB name="GratefulDeadConcerts"

Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open the storage 'GratefulDeadConcerts' because it does not exist in path: ../databases/GratefulDeadConcerts
        DB name="GratefulDeadConcerts"
</code>```

what I am doing wrong?

答:
Maybe you could try this?</p>

```<code>connect remote:localhost/databases/GratefulDeadConcerts root root
</code>```

Body:
I'm trying to connect to the GratefulDeadConcerts without any sucess.
I'm using docker.

orientdb> connect remote:localhost root root

Disconnecting from the database [null]...OK
Connecting to remote Server instance [remote:localhost] with user 'root'...OK
orientdb {server=remote:localhost/}> list databases

Found 5 databases:

* VehicleHistoryGraph (plocal)
* GratefulDeadConcerts (plocal)
* OpenBeer (plocal)
* BetterDemo (plocal)
* Tolkien-Arda (plocal)

orientdb {server=remote:localhost/}> connect plocal:../databases/GratefulDeadConcerts root root

Disconnecting from remote server [remote:localhost/]...
OK
Connecting to database [plocal:../databases/GratefulDeadConcerts] with user 'root'...
Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open local storage '../databases/GratefulDeadConcerts' with mode=rw
        DB name="GratefulDeadConcerts"

Error: com.orientechnologies.orient.core.exception.OStorageException: Cannot open the storage 'GratefulDeadConcerts' because it does not exist in path: ../databases/GratefulDeadConcerts
        DB name="GratefulDeadConcerts"

what I am doing wrong?

Body:
Maybe you could try this?

connect remote:localhost/databases/GratefulDeadConcerts root root


问:
Hide certain legend elements
I am using the names property to label a scatter chart legend. I have not been able to find a way to only show the legend for only data14, data15, data16 and data17 and hide the legend elements for data1 through data13.

data1 through data13 will always be the same, data14 through data17 could expand or collapse in number and the label text will change.

```<code>  names: {
        data1: '2%',
        data2: '5%',
        data3: '10%',
        data4: '15%',
        data5: '20%',
        data6: '25%',
        data7: '30%',
        data8: '35%',
        data9: '40%',
        data10: '45%',
        data11: '50%',
        data12: '55%',
        data13: '60%',

        data14: 'Oracle',
        data15: 'HP',
        data16: 'MS',
        data17: 'Oracle'
   },
</code>```

答:
Set your chart legend not visible:

```<code>legend: {
  show: false
}
</code>```

Then, make the legend visible only with elements you want:

```<code>chart.legend.show(['data14', 'data15', 'data16', 'data17'])
</code>```

Title: Hide certain legend elements

Body:
I am using the names property to label a scatter chart legend. I have not been able to find a way to only show the legend for only data14, data15, data16 and data17 and hide the legend elements for data1 through data13.

data1 through data13 will always be the same, data14 through data17 could expand or collapse in number and the label text will change.

  names: {
        data1: '2%',
        data2: '5%',
        data3: '10%',
        data4: '15%',
        data5: '20%',
        data6: '25%',
        data7: '30%',
        data8: '35%',
        data9: '40%',
        data10: '45%',
        data11: '50%',
        data12: '55%',
        data13: '60%',

        data14: 'Oracle',
        data15: 'HP',
        data16: 'MS',
        data17: 'Oracle'
   },

Body:
Set your chart legend not visible:

legend: {
  show: false
}

Then, make the legend visible only with elements you want:

chart.legend.show(['data14', 'data15', 'data16', 'data17'])


问:
MYSQL/PHP: Possible to Join on One to Many Field?
I have three tables, authors, books and borrowed.  There are multiple books for each author.  And a book may or not appear in the borrowed table.  Here is the schema:

Authors

```<code>id|authornamename
</code>```

Books

```<code>id|bookname|authorid
</code>```

Borrowed

```<code>id|bookid|borrowerid|onloan //onloan is a boolean
</code>```

Whenever a book is borrowed, it appears in the Borrowed table.  However, only some books appear in the borrowed table.  If ever borrowed, they can have value for onloan of TRUE or FALSE.

The following query returns a list of authors with a comma-delimitied list of bookids and booknames by each:

```<code>SELECT
a.*,a.id as `authorid`, bookids,booknames
from authors `a`
LEFT JOIN (
  SELECT group_concat(id ORDER BY id ASC) as `bookids`,
group_concat(bookname ORDER BY id ASC) as `booknames`
   FROM   books
   GROUP  BY authorid
   ) b ON b.authorid = a.id
GROUP BY a.id";
</code>```

How could I also get, a list for each book of whether the book is borrowed (onloan field) given that there is not an entry for each book in the borrowed table?  I would like the list of onloan to have the same number of entries as books, so I can tell if a book is onloan at a given time.  If it has never been borrowed, I would like to have a value of 0--ie the same value as if it had been borrowed but Onloan was FALSE.

So if the bookids list is something like:

```<code>"32,77,84"
</code>```

The onloan list should be something like

```<code>"0,1,1"
</code>```

where 1 means it is onloan (out) and 0 means it is not onloan (in library).

I need the onloan list to have the same number of elements as the bookids list so there is a 1 to 1 correspondence between the to and I can laster use the index to reassemble a books array.

Thanks for any suggestions.

答:
Try this:

```<code>SELECT
  aid,
  group_concat(bookid ORDER BY bookid ASC) AS bookids,
  group_concat(bookname ORDER BY bookid ASC) AS booknames,
  group_concat(onloan ORDER BY bookid ASC) AS onloan
FROM (
  SELECT a.id AS aid, b.id AS bookid, b.bookname AS bookname, IF(bo.onloan IS NOT NULL, bo.onloan, 0) AS onloan
  FROM authors a
  LEFT JOIN books b ON b.authorid = a.id
  LEFT JOIN borrowed bo ON bo.bookid = b.id
) t
GROUP BY aid
</code>```

Notice the IF. That guarantees you have always a result for onloan.

Body:
I have three tables, authors, books and borrowed.  There are multiple books for each author.  And a book may or not appear in the borrowed table.  Here is the schema:

Authors

id|authornamename

Books

id|bookname|authorid

Borrowed

id|bookid|borrowerid|onloan //onloan is a boolean

Whenever a book is borrowed, it appears in the Borrowed table.  However, only some books appear in the borrowed table.  If ever borrowed, they can have value for onloan of TRUE or FALSE.

The following query returns a list of authors with a comma-delimitied list of bookids and booknames by each:

SELECT
a.*,a.id as `authorid`, bookids,booknames
from authors `a`
LEFT JOIN (
  SELECT group_concat(id ORDER BY id ASC) as `bookids`,
group_concat(bookname ORDER BY id ASC) as `booknames`
   FROM   books
   GROUP  BY authorid
   ) b ON b.authorid = a.id
GROUP BY a.id";

How could I also get, a list for each book of whether the book is borrowed (onloan field) given that there is not an entry for each book in the borrowed table?  I would like the list of onloan to have the same number of entries as books, so I can tell if a book is onloan at a given time.  If it has never been borrowed, I would like to have a value of 0--ie the same value as if it had been borrowed but Onloan was FALSE.

So if the bookids list is something like:

"32,77,84"

The onloan list should be something like

"0,1,1"

where 1 means it is onloan (out) and 0 means it is not onloan (in library).

I need the onloan list to have the same number of elements as the bookids list so there is a 1 to 1 correspondence between the to and I can laster use the index to reassemble a books array.

Thanks for any suggestions.

Body:
Try this:

SELECT
  aid,
  group_concat(bookid ORDER BY bookid ASC) AS bookids,
  group_concat(bookname ORDER BY bookid ASC) AS booknames,
  group_concat(onloan ORDER BY bookid ASC) AS onloan
FROM (
  SELECT a.id AS aid, b.id AS bookid, b.bookname AS bookname, IF(bo.onloan IS NOT NULL, bo.onloan, 0) AS onloan
  FROM authors a
  LEFT JOIN books b ON b.authorid = a.id
  LEFT JOIN borrowed bo ON bo.bookid = b.id
) t
GROUP BY aid

Notice the IF. That guarantees you have always a result for onloan.


问:
What data structure should I use to store a collection of items in C#?
I have following string : [Value:"Car" - Name:"Manufactor" [Value:"Audi" - Name:"A6"][Value:"BMW" - Name:"M4"]]]

I need to split the string and save data into suitable data structure. Starting bracket "[" indicates the beginning of the collection, and
matching ending bracket "]" indicates the end of the collection. The "-" character seperates key and values. So I was wondering what is most
logical datastructure to use here? Is using a tree good solution? I have splitted the string up in parts, I only need help to choose a logical datastructure.

Thanks!

答:
Using a tree is not a good solution, as you don't have something like branches with multiple leafs in your structure.

Without knowing your use case, I would use a list or an array of Car-Objects, each having a property Name and Manufacturer.


问:
set boundary limit for draggable pane inside its parent pane
I have a draggable pane which is inside another pane. I want to make the child pane be draggable only inside the boundary of the parent pane but by default, the child pane can be dragged anywhere. How to solve this problem.</p>

答:
Adding to xuesheng answer, instead of

```<code> if (newX > 200 || newX < 10) { return; }
</code>```

use

```<code>if( outSideParentBounds(label.getLayoutBounds(), newX, newY) ) {    return; }
</code>```

Where outSideParentBounds is defined by:

```<code>private boolean outSideParentBounds( Bounds childBounds, double newX, double newY) {

        Bounds parentBounds = getLayoutBounds();

        //check if too left
        if( parentBounds.getMaxX() <= (newX + childBounds.getMaxX()) ) {
            return true ;
        }

        //check if too right
        if( parentBounds.getMinX() >= (newX + childBounds.getMinX()) ) {
            return true ;
        }

        //check if too down
        if( parentBounds.getMaxY() <= (newY + childBounds.getMaxY()) ) {
            return true ;
        }

        //check if too up
        if( parentBounds.getMinY() >= (newY + childBounds.getMinY()) ) {
            return true ;
        }

        return false;

        /* Alternative implementation
        Point2D topLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMinY());
        Point2D topRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMinY());
        Point2D bottomLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMaxY());
        Point2D bottomRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMaxY());
        Bounds newBounds = BoundsUtils.createBoundingBox(topLeft, topRight, bottomLeft, bottomRight);

        return ! parentBounds.contains(newBounds);
         */
    }
</code>```

Body:
Adding to xuesheng answer, instead of

 if (newX > 200 || newX < 10) { return; }

use

if( outSideParentBounds(label.getLayoutBounds(), newX, newY) ) {    return; }

Where outSideParentBounds is defined by:

private boolean outSideParentBounds( Bounds childBounds, double newX, double newY) {

        Bounds parentBounds = getLayoutBounds();

        //check if too left
        if( parentBounds.getMaxX() <= (newX + childBounds.getMaxX()) ) {
            return true ;
        }

        //check if too right
        if( parentBounds.getMinX() >= (newX + childBounds.getMinX()) ) {
            return true ;
        }

        //check if too down
        if( parentBounds.getMaxY() <= (newY + childBounds.getMaxY()) ) {
            return true ;
        }

        //check if too up
        if( parentBounds.getMinY() >= (newY + childBounds.getMinY()) ) {
            return true ;
        }

        return false;

        /* Alternative implementation
        Point2D topLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMinY());
        Point2D topRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMinY());
        Point2D bottomLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMaxY());
        Point2D bottomRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMaxY());
        Bounds newBounds = BoundsUtils.createBoundingBox(topLeft, topRight, bottomLeft, bottomRight);

        return ! parentBounds.contains(newBounds);
         */
    }


问:
How do I execute "use dbname" over Oracle dblink to Sybase?
How do I access tables in my user schema in Sybase from Oracle?

In isql I can do

```<code>use mydb
go
</code>```

How do I select from mydb tables from Oracle using dblink NITSYB5?

This does not work:

```<code>select count(*) from  "mydb"."lon_client_confirm_exec"@NITSYB5;
</code>```

Error:

```<code>ORA-00942: table or view does not exist
[Oracle][ODBC Sybase Wire Protocol driver][SQL Server]"mydb"."lon_client_confirm_exec" not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
 {42S02,NativeErr = 208}
ORA-02063: preceding 3 lines from NITSYB5
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 3 Column: 30
</code>```

答:
SERVER 1 AND SERVER 2
open SSH server2 telnet server 1 host, its ok to done
su oracle

```<code>1) cd $ORACLE_HOME/bin
2) TNSPING database1 name
</code>```

its ok done

```<code>create public database link
  LINK_NAME
connect to
  DB1USERNAME
identified by
  111
using 'DB1NAME';
</code>```

select * from dual@LINK_NAME, result x, finish.

Body:
How do I access tables in my user schema in Sybase from Oracle?

In isql I can do

use mydb
go

How do I select from mydb tables from Oracle using dblink NITSYB5?

This does not work:

select count(*) from  "mydb"."lon_client_confirm_exec"@NITSYB5;

Error:

ORA-00942: table or view does not exist
[Oracle][ODBC Sybase Wire Protocol driver][SQL Server]"mydb"."lon_client_confirm_exec" not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
 {42S02,NativeErr = 208}
ORA-02063: preceding 3 lines from NITSYB5
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:
Error at Line: 3 Column: 30

Body:
SERVER 1 AND SERVER 2
open SSH server2 telnet server 1 host, its ok to done
su oracle

1) cd $ORACLE_HOME/bin
2) TNSPING database1 name

its ok done

create public database link
  LINK_NAME
connect to
  DB1USERNAME
identified by
  111
using 'DB1NAME';

select * from dual@LINK_NAME, result x, finish.


问:
constructing future coupon payment dates for bonds
I have a Problem and would be very grateful if you could help me.

starting Situation:

Bonds: "026351AZ9" "026351BC9"

First Coupon Date of These Bonds: "2029-02-15" "2010-09-11" (class date)

Count of the years where the bonds pay coupons: 3 years and 1 years

each years has also a Coupon frequency: 2 and 4, that means that during the next year there will be 2 payments (4 payments)

First case: 3 years and each year 2 times Coupon payment -> so every 6 month Coupon payment for the next 3 years. Same with 1 year and 4 times coupn payment.

Result:
It should be look like this:

datesBond1 = "2029-02-15" "2029-08-15" "2030-02-15" "2030-08-15" "2031-02-15" "2031-08-15"

datesBond2 = "2010-09-11" "2010-12-11" "2010-03-11" "2010-06-11"

This is just a sample. In my case I have a lot more ISINS, Dates, and various years and Coupon frequencies.

Thank you

答:
You can use the months function to contruct future coupon payments dates and wrap the calculation in a
custom function that could be accessed for individual bonds.

There is typo in your expected output for bond 2 where last two values should correspond to year 2011.

```<code>fn_cpnPayDates = function(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6) {

# number of coupon payments per year
numPayPerYear = 12 / freq

#total payments
numPayments = numYears * numPayPerYear

cpnDatesAll = rep(cpnStartDt, numPayments)

for(i in 1:numPayments) cpnDatesAll[i] = cpnDatesAll[i] + months((i-1)* freq)

return(cpnDatesAll)

}

datesBond1 = fn_cpnPayDates(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6)
datesBond1
#[1] "2029-02-15" "2029-08-15" "2030-02-15" "2030-08-15" "2031-02-15" "2031-08-15"

datesBond2 = fn_cpnPayDates(cpnStartDt = as.Date("2010-09-11"),numYears = 1, freq = 3)
datesBond2
#[1] "2010-09-11" "2010-12-11" "2011-03-11" "2011-06-11"
</code>```

Body:
You can use the months function to contruct future coupon payments dates and wrap the calculation in a
custom function that could be accessed for individual bonds.

There is typo in your expected output for bond 2 where last two values should correspond to year 2011.

fn_cpnPayDates = function(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6) {

# number of coupon payments per year
numPayPerYear = 12 / freq

#total payments
numPayments = numYears * numPayPerYear

cpnDatesAll = rep(cpnStartDt, numPayments)

for(i in 1:numPayments) cpnDatesAll[i] = cpnDatesAll[i] + months((i-1)* freq)

return(cpnDatesAll)

}

datesBond1 = fn_cpnPayDates(cpnStartDt = as.Date("2029-02-15"),numYears = 3, freq = 6)
datesBond1
#[1] "2029-02-15" "2029-08-15" "2030-02-15" "2030-08-15" "2031-02-15" "2031-08-15"

datesBond2 = fn_cpnPayDates(cpnStartDt = as.Date("2010-09-11"),numYears = 1, freq = 3)
datesBond2
#[1] "2010-09-11" "2010-12-11" "2011-03-11" "2011-06-11"


问:
How to resize NSTextView according to its content?
I am trying to set an attributed string within NSTextView. I want to increase its height based on its content, initially it is set to some default value.

So I tried this method:

I set content in NSTextView. When we set some content in NSTextView its size automatically increases. So I increased height of its super view that is NSScrollView to its height, but NSScrollView is not getting completely resized, it is showing scroller on right.

```<code>float xCoordinate = 15.0;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)];

[[xContentView textStorage] setAttributedString:xContents];

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)];
</code>```

Can anyone suggest me some way or method to resolve this issue. By doing google search I found that in UITextView there is contentSize method which can get size of its content, I tried to find similar method in NSTextView but could not get any success :(

答:
```<code>+ (float)heightForString:(NSString *)myString font:(NSFont *)myFont andWidth:(float)myWidth andPadding:(float)padding {
     NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:myString];
     NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)];
     NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
     [layoutManager addTextContainer:textContainer];
     [textStorage addLayoutManager:layoutManager];
     [textStorage addAttribute:NSFontAttributeName value:myFont
                    range:NSMakeRange(0, textStorage.length)];
     textContainer.lineFragmentPadding = padding;

     (void) [layoutManager glyphRangeForTextContainer:textContainer];
     return [layoutManager usedRectForTextContainer:textContainer].size.height;
}
</code>```

I did the function using this reference: Documentation

Example:

```<code>float width = textView.frame.size.width - 2 * textView.textContainerInset.width;
float proposedHeight = [Utils heightForString:textView.string font:textView.font andWidth:width
                                   andPadding:textView.textContainer.lineFragmentPadding];
</code>```

Body:
I am trying to set an attributed string within NSTextView. I want to increase its height based on its content, initially it is set to some default value.

So I tried this method:

I set content in NSTextView. When we set some content in NSTextView its size automatically increases. So I increased height of its super view that is NSScrollView to its height, but NSScrollView is not getting completely resized, it is showing scroller on right.

float xCoordinate = 15.0;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)];

[[xContentView textStorage] setAttributedString:xContents];

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)];

Can anyone suggest me some way or method to resolve this issue. By doing google search I found that in UITextView there is contentSize method which can get size of its content, I tried to find similar method in NSTextView but could not get any success :(

Body:
+ (float)heightForString:(NSString *)myString font:(NSFont *)myFont andWidth:(float)myWidth andPadding:(float)padding {
     NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:myString];
     NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(myWidth, FLT_MAX)];
     NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
     [layoutManager addTextContainer:textContainer];
     [textStorage addLayoutManager:layoutManager];
     [textStorage addAttribute:NSFontAttributeName value:myFont
                    range:NSMakeRange(0, textStorage.length)];
     textContainer.lineFragmentPadding = padding;

     (void) [layoutManager glyphRangeForTextContainer:textContainer];
     return [layoutManager usedRectForTextContainer:textContainer].size.height;
}

I did the function using this reference: Documentation

Example:

float width = textView.frame.size.width - 2 * textView.textContainerInset.width;
float proposedHeight = [Utils heightForString:textView.string font:textView.font andWidth:width
                                   andPadding:textView.textContainer.lineFragmentPadding];


问:
How to detect when an AutoCompleteTextView popup is opened?
How can I do something when a popup just opens? There is a method isPopupShowing(), but nothing like onPopupShow() callback unfortunately.

答:
My answer could be a little bit different but it works when you have valid results.

1.- Extend your own class of AutoCompleteTextView:

```<code>public class ContractsAutoCompleteTextView extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public ContractsAutoCompleteTextView(Context context) {
        super(context);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

}
</code>```

2.- We know that onFilterComplete(int count) will get notified when items are filtered (and just later shown). Introduce that in your class:

```<code>    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
    }
</code>```

3.- Create an interface to notify the UI how many items are filtered every time you change text:

```<code>    interface OnContractsAvailability {
        void contractsRetrieved(int count);
    }

    private OnContractsAvailability onContractsAvailability;
    public void setOnContractsAvailability(OnContractsAvailability onContractsAvailability) {
        this.onContractsAvailability = onContractsAvailability;
    }
</code>```

4.- Now notify your interface:

```<code>    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
        if (onContractsAvailability != null) {
            onContractsAvailability.contractsRetrieved(count);
        }
    }
</code>```

This is the whole class

```<code>/**
 * Created by rafaelruizmunoz on 07/07/2017.
 */

public class ContractsAutoCompleteTextView extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public ContractsAutoCompleteTextView(Context context) {
        super(context);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
        if (onContractsAvailability != null) {
            onContractsAvailability.contractsRetrieved(count);
        }
    }

    interface OnContractsAvailability {
        void contractsRetrieved(int count);
    }

    private OnContractsAvailability onContractsAvailability;
    public void setOnContractsAvailability(OnContractsAvailability onContractsAvailability) {
        this.onContractsAvailability = onContractsAvailability;
    }
}
</code>```

This is the UI implementation

```<code>    contractsET.setOnContractsAvailability(count -> System.out.println(String.valueOf(count)));
</code>```

And these are the results

07-07 11:51:36.975 32174-32174/? I/System.out: 3138

07-07 11:51:37.520 32174-32174/? I/System.out: 1147

07-07 11:51:37.656 32174-32174/? I/System.out: 167

07-07 11:51:38.538 32174-32174/? I/System.out: 87

07-07 11:51:39.240 32174-32174/? I/System.out: 17

07-07 11:51:40.039 32174-32174/? I/System.out: 3

07-07 11:51:41.343 32174-32174/? I/System.out: 0

Body:
My answer could be a little bit different but it works when you have valid results.

1.- Extend your own class of AutoCompleteTextView:

public class ContractsAutoCompleteTextView extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public ContractsAutoCompleteTextView(Context context) {
        super(context);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

}

2.- We know that onFilterComplete(int count) will get notified when items are filtered (and just later shown). Introduce that in your class:

    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
    }

3.- Create an interface to notify the UI how many items are filtered every time you change text:

    interface OnContractsAvailability {
        void contractsRetrieved(int count);
    }

    private OnContractsAvailability onContractsAvailability;
    public void setOnContractsAvailability(OnContractsAvailability onContractsAvailability) {
        this.onContractsAvailability = onContractsAvailability;
    }

4.- Now notify your interface:

    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
        if (onContractsAvailability != null) {
            onContractsAvailability.contractsRetrieved(count);
        }
    }

This is the whole class

/**
 * Created by rafaelruizmunoz on 07/07/2017.
 */

public class ContractsAutoCompleteTextView extends android.support.v7.widget.AppCompatAutoCompleteTextView {
    public ContractsAutoCompleteTextView(Context context) {
        super(context);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ContractsAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onFilterComplete(int count) {
        super.onFilterComplete(count);
        if (onContractsAvailability != null) {
            onContractsAvailability.contractsRetrieved(count);
        }
    }

    interface OnContractsAvailability {
        void contractsRetrieved(int count);
    }

    private OnContractsAvailability onContractsAvailability;
    public void setOnContractsAvailability(OnContractsAvailability onContractsAvailability) {
        this.onContractsAvailability = onContractsAvailability;
    }
}

This is the UI implementation

    contractsET.setOnContractsAvailability(count -> System.out.println(String.valueOf(count)));

And these are the results

07-07 11:51:36.975 32174-32174/? I/System.out: 3138

07-07 11:51:37.520 32174-32174/? I/System.out: 1147

07-07 11:51:37.656 32174-32174/? I/System.out: 167

07-07 11:51:38.538 32174-32174/? I/System.out: 87

07-07 11:51:39.240 32174-32174/? I/System.out: 17

07-07 11:51:40.039 32174-32174/? I/System.out: 3

07-07 11:51:41.343 32174-32174/? I/System.out: 0