问:
php exec memory usage with phing
I'm automating some tasks using phing and yui compressor and I'm running into a memory problem.  I'm curious if there is a better way to handle this.

Part of phing build script

```<code><target name="finalize">
  <property name="cssfolders" value="folder1, folder2, folder3" />
  <foreach list="${cssfolders}" param="dir" target="minifyCSS" />

  <property name="jsfolders" value="folder1, folder2, folder3" />
  <foreach list="${jsfolders}" param="dir" target="minifyJS" />
</target>

<target name="minifyCSS">
  <exec command="find ${dir}/dev -name '*.css' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" />
</target>

<target name="minifyJS">
  <exec command="find ${dir}/dev -name '*.js' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" />
</target>
</code>```

If I split up the finalize target into two, one for css and one for js - then the script will work.  But when I keep them combined I have a problem.  Before everyone says to just split the target, which I'm ok with doing, I'm afraid as more JS files are added I'm going to eventually run into this problem again.

I'm curious if there is a better way to execute my plan w/out continuously monitoring and increasing php's memory usage.  Perhaps a more efficient command to execute, or utilizing a php function that will allow me to use more memory or the disk if I exhaust allocated resources?

Side project - kudos to anyone who knows how to combine the minify targets into one.  They are practically the same except I need to know what type of file to "find" for each one (css or js).  If there is a way to handle this w/ only one target - I wanna know! :)

答:
The only reason I can see this using so much memory is that the yuiCompressor is outputting a lot of information to stdout. This is then captured by the phing execute task.

Try calling the execute task with spawn parameter set to true which will cause it to redirect the stdout to /dev/null.

```<code><exec command="find ${dir}/dev -name '*.css' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" spawn="true" />
</code>```

As for the side project - maybe something like this would work:

```<code><target name="finalize">
  <property name="cssfolders" value="css:folder1, css:folder2, css:folder3" />
  <foreach list="${cssfolders}" param="toCompress" target="minify" />

  <property name="jsfolders" value="js:folder1, js:folder2, js:folder3" />
  <foreach list="${jsfolders}" param="toCompress" target="minify" />
</target>

<target name="minify">
  <exec command="type=`echo ${toProcess}|cut -d ':' -f 1`;folder=`echo ${toProcess}|cut -d ':' -f 2`; find $folder/dev -name '*.'$type -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o $folder/prod/$file $folder/dev/$file; done" />
</target>
</code>```

Title: php exec memory usage with phing

Body:
I'm automating some tasks using phing and yui compressor and I'm running into a memory problem.  I'm curious if there is a better way to handle this.

Part of phing build script

<target name="finalize">
  <property name="cssfolders" value="folder1, folder2, folder3" />
  <foreach list="${cssfolders}" param="dir" target="minifyCSS" />

  <property name="jsfolders" value="folder1, folder2, folder3" />
  <foreach list="${jsfolders}" param="dir" target="minifyJS" />
</target>

<target name="minifyCSS">
  <exec command="find ${dir}/dev -name '*.css' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" />
</target>

<target name="minifyJS">
  <exec command="find ${dir}/dev -name '*.js' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" />
</target>

If I split up the finalize target into two, one for css and one for js - then the script will work.  But when I keep them combined I have a problem.  Before everyone says to just split the target, which I'm ok with doing, I'm afraid as more JS files are added I'm going to eventually run into this problem again.

I'm curious if there is a better way to execute my plan w/out continuously monitoring and increasing php's memory usage.  Perhaps a more efficient command to execute, or utilizing a php function that will allow me to use more memory or the disk if I exhaust allocated resources?

Side project - kudos to anyone who knows how to combine the minify targets into one.  They are practically the same except I need to know what type of file to "find" for each one (css or js).  If there is a way to handle this w/ only one target - I wanna know! :)

Body:
The only reason I can see this using so much memory is that the yuiCompressor is outputting a lot of information to stdout. This is then captured by the phing execute task.

Try calling the execute task with spawn parameter set to true which will cause it to redirect the stdout to /dev/null.

<exec command="find ${dir}/dev -name '*.css' -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o ${dir}/prod/$file ${dir}/dev/$file; done" spawn="true" />

As for the side project - maybe something like this would work:

<target name="finalize">
  <property name="cssfolders" value="css:folder1, css:folder2, css:folder3" />
  <foreach list="${cssfolders}" param="toCompress" target="minify" />

  <property name="jsfolders" value="js:folder1, js:folder2, js:folder3" />
  <foreach list="${jsfolders}" param="toCompress" target="minify" />
</target>

<target name="minify">
  <exec command="type=`echo ${toProcess}|cut -d ':' -f 1`;folder=`echo ${toProcess}|cut -d ':' -f 2`; find $folder/dev -name '*.'$type -exec basename {} \; | while read file; do java -jar ${yuiCompressor} -o $folder/prod/$file $folder/dev/$file; done" />
</target>


来源: stackexchange

问:
How do I set up continuous integration of a Node.js webjob in VSTS
I am familiar with how to set up continuous integration of node.js web applications using VSTS.

How do I go about setting up continuous integration for a node.js webjob. I have found examples of how to do it with a .NET project using Visual Studio however could not find any documentation on how to do it with a node.js webjob.

答:
To CI build your node.js app, you can manage your code by a repo on VSTS firstly (or remote repo hosted on other sites such as github, bitbucket ect), then create a build definition definition for your node.js webjob. Detail steps as below:

1.   Manage code by VSTS repo (git or TFVC)

You can manage your node.js app to a current repo you used or you can create a new repo to manage your node.js app. Create a new git repo (I use git repo as example, similar with TFVC), you can refer create a git repo for team project.

Push your node.js code to VSTS repo. You can use VS (clone the repo -> copy your code in local repo -> commit -> push) or git commands directly.

2. Create CI build

In Builds Tab -> New -> use the Node.JS With Gulp (PREVIEW) template (or you can use empty template and then add tasks manually) -> Get sources step -> specify repo and branch which your code exists -> specify settings for tasks -> add other tasks if you need -> Triggers Tab -> enable Continuous Integration.

More details for node.js app CI build, you can refer define your CI build for node.js app.

3. Add your app in Azure webjobs

In the CI build definition, add below tasks:

Copy files task: to copy the App you want to run on Azure webjobs from $(System.DefaultWorkingDirectory) to $(Build.ArtifactStagingDirectory).

Archive Files task: create a zip file (such as $(Build.ArtifactStagingDirectory)/webjob.zip) from files in $(Build.ArtifactStagingDirectory).

Azure App Service Deploy task: deploy your zip file ($(Build.ArtifactStagingDirectory)/webjob.zip) to Azure.

And more details, you can also refer this thread.

ContentLicense: CC BY-SA 3.0


问:
Call to ApplicationTokenProvider.LoginSilentAsync never returns
From my local PC I'm trying to connect to the AzureBillingAPI using the following code :

```<code>var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantDomain, clientId, secret);
</code>```

This methods never returns. Debug output displays the following :

Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: Looking up cache for a token...

iisexpress.exe Information: 0 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: Looking up cache for a token...

Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: No matching token was found in the cache

iisexpress.exe Information: 0 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: No matching token was found in the cache

Question: how do I connect ?
Thanks.

答:
According to your description, I guess the reason why this methods never returns is you called the async method in the sync Controller method with wait keywords.

If you call the getResultAsync as below, it will never return the result :

```<code>    public ActionResult Index()
    {
       getResultAsync().Wait();
        return View();
    }

    public static async Task getResultAsync()
    {
        string subscription = "subid";

        string tenantid = "tenantid ";
        string clientId = "clientId ";
        string key = "key";

        var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantDomain, clientId, key);

        BillingManagementClient b1 = new BillingManagementClient(serviceCreds) { SubscriptionId = subscription };

        var result = b1.Operations.List();

    }
</code>```

I suggest you could change the index method as below, it will work well:

```<code>   public async Task<ActionResult> Index()
        {
            await getResultAsync();
            return View();
        }
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
From my local PC I'm trying to connect to the AzureBillingAPI using the following code :

var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantDomain, clientId, secret);

This methods never returns. Debug output displays the following :

Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: Looking up cache for a token...

iisexpress.exe Information: 0 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: Looking up cache for a token...

Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: No matching token was found in the cache

iisexpress.exe Information: 0 : 07/03/2017 14:02:07: e608ec23-675f-4828-aa65-72479409ec63 - TokenCache: No matching token was found in the cache

Question: how do I connect ?
Thanks.

Body:
According to your description, I guess the reason why this methods never returns is you called the async method in the sync Controller method with wait keywords.

If you call the getResultAsync as below, it will never return the result :

    public ActionResult Index()
    {
       getResultAsync().Wait();
        return View();
    }

    public static async Task getResultAsync()
    {
        string subscription = "subid";

        string tenantid = "tenantid ";
        string clientId = "clientId ";
        string key = "key";

        var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantDomain, clientId, key);

        BillingManagementClient b1 = new BillingManagementClient(serviceCreds) { SubscriptionId = subscription };

        var result = b1.Operations.List();

    }

I suggest you could change the index method as below, it will work well:

   public async Task<ActionResult> Index()
        {
            await getResultAsync();
            return View();
        }

Result:


问:
How are the GNU C preprocessor predefined macros used?
I am trying to figure out how the integer type definitions from various header files are related to each other.

I just installed the CygWin. I opened the Cygwin\x86\usr\include\machine\_default_types.h. In it I noticed below code snippets:

```<code>#ifdef __INT8_TYPE__
typedef __INT8_TYPE__ __int8_t;
</code>```

According to here, the __INT8_TYPE__ is one of the predefined pre-processor macros. And:

You should not use these macros directly; instead, include the
  appropriate headers and use the typedefs. Some of these macros may not
  be defined on particular systems if GCC does not provide a stdint.h
  header on those systems.

So it seems the __INT8_TYPE__ should be defined somewhere else. But I searched the whole CygWin installation, there's no definition for it. All I found are some conditional statements just like above one.

Since I shouldn't use it directly. And no other files are defining it. How could this macro ever come into action? Or did I misunderstand something?

答:
This is a predefined macro.  To see them you can:

```<code>gcc -dM -E - < /dev/null
</code>```

e.g.:

```<code>$ gcc -dM -E  - < /dev/null | grep __INT
#define __INTMAX_C(c) c ## L
#define __INT8_C(c) c
#define __INT64_C(c) c ## L
#define __INT32_MAX__ 0x7fffffff
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_FAST64_TYPE__ long int
#define __INT32_C(c) c
#define __INT_FAST32_TYPE__ long int
#define __INT16_MAX__ 0x7fff
#define __INT8_TYPE__ signed char
#define __INT_LEAST16_TYPE__ short int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __INT_FAST8_MAX__ 0x7f
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_MAX__ 0x7fffffff
#define __INT64_TYPE__ long int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST32_TYPE__ int
#define __INT_FAST8_TYPE__ signed char
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INT8_MAX__ 0x7f
#define __INT32_TYPE__ int
#define __INTMAX_TYPE__ long int
#define __INT16_C(c) c
</code>```

Body:
I am trying to figure out how the integer type definitions from various header files are related to each other.

I just installed the CygWin. I opened the Cygwin\x86\usr\include\machine\_default_types.h. In it I noticed below code snippets:

#ifdef __INT8_TYPE__
typedef __INT8_TYPE__ __int8_t;

According to here, the __INT8_TYPE__ is one of the predefined pre-processor macros. And:

You should not use these macros directly; instead, include the
  appropriate headers and use the typedefs. Some of these macros may not
  be defined on particular systems if GCC does not provide a stdint.h
  header on those systems.

So it seems the __INT8_TYPE__ should be defined somewhere else. But I searched the whole CygWin installation, there's no definition for it. All I found are some conditional statements just like above one.

Since I shouldn't use it directly. And no other files are defining it. How could this macro ever come into action? Or did I misunderstand something?

Body:
This is a predefined macro.  To see them you can:

gcc -dM -E - < /dev/null

e.g.:

$ gcc -dM -E  - < /dev/null | grep __INT
#define __INTMAX_C(c) c ## L
#define __INT8_C(c) c
#define __INT64_C(c) c ## L
#define __INT32_MAX__ 0x7fffffff
#define __INT_FAST32_MAX__ 0x7fffffffffffffffL
#define __INT_FAST16_TYPE__ long int
#define __INT_LEAST32_MAX__ 0x7fffffff
#define __INT_FAST64_TYPE__ long int
#define __INT32_C(c) c
#define __INT_FAST32_TYPE__ long int
#define __INT16_MAX__ 0x7fff
#define __INT8_TYPE__ signed char
#define __INT_LEAST16_TYPE__ short int
#define __INT_FAST16_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST16_MAX__ 0x7fff
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST64_TYPE__ long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __INT_FAST8_MAX__ 0x7f
#define __INTPTR_MAX__ 0x7fffffffffffffffL
#define __INTPTR_TYPE__ long int
#define __INT_FAST64_MAX__ 0x7fffffffffffffffL
#define __INT_MAX__ 0x7fffffff
#define __INT64_TYPE__ long int
#define __INT_LEAST64_MAX__ 0x7fffffffffffffffL
#define __INT_LEAST8_MAX__ 0x7f
#define __INT_LEAST32_TYPE__ int
#define __INT_FAST8_TYPE__ signed char
#define __INTMAX_MAX__ 0x7fffffffffffffffL
#define __INT8_MAX__ 0x7f
#define __INT32_TYPE__ int
#define __INTMAX_TYPE__ long int
#define __INT16_C(c) c


问:
routing algorithm different to Dijkstra-concept
what kind of routing algorithms exists that are different to different to Dijkstra-concept?

Dijkstra (and A*,D*, bellman forge etc.) use this concept:
Get the best Node from known Nodes, expand this and save the results to the known Nodes.

Are there any concepts that are fundamental different?

答: Bellman-Ford is fundamentally different. It uses dynamic programing instead of the Dijkstra greedy approach and works for graphs with negative weight edges. </p>

ContentLicense: CC BY-SA 2.5


问:
Spark: Trying to run spark-shell, but get 'cmd' is not recognized as an internal or
I'm trying to install Spark on my Windows desktop. Everything should work fine, but I get an error "'cmd' is not recognized as an internal or external command... "

I installed Scala, Java JDK and unzipped Spark tgz in C:\, but for some reason can't get Spark to start in cmd. Any ideas?

答:
For my case I had similar issue. I had to fix a couple of things.

1- Check JAVA_HOME is correct on both places;

2- Then I had to change following lines in spark-2.1.1-bin-hadoop2.7\bin folder.

Add extra quotation marks around "%RUNNER%". So it will be like ""%RUNNER%""

Then execute .\spark-shell.cmd again.


问:
Use an ephemeral port with socket.io server
I am looking for a way to start a socket.io server with an ephemeral port. How can I get an ephemeral port with socket.io server?

Perhaps all I need to do is:

```<code>const Server = require('socket.io);
const s = new Server('http://localhost');
</code>```

perhaps that will use an ephemeral port, as is?

it so, how can I retrieve the port that socket.io found?

答:
Your example code would just use the default socket.io port which I believe is 8080

My suggestion would be to just select a port number at random that is within the ephemeral range or a range that you define, and then use this library to check to see if it is available or not.  https://github.com/indexzero/node-portfinder

You could also just step through ports in a loop to try and get the lowest available to bind to.  Use portfinder to assure it is available and then use that.

This also have the secondary advantage of being able to then tell you what port was used.

Body:
I am looking for a way to start a socket.io server with an ephemeral port. How can I get an ephemeral port with socket.io server?

Perhaps all I need to do is:

const Server = require('socket.io);
const s = new Server('http://localhost');

perhaps that will use an ephemeral port, as is?

it so, how can I retrieve the port that socket.io found?


问:
How to insert Item to a collectionView ? Swift3
I am creating a chatting app in Xcode 8 with Swift 3 and I am using collectionView for the messages. but I am having an issue with inserting a new item to the collection view when press send:

```<code>msg.append(message) // msg : Messages Array
let item = msg.count - 1
let IndexPath = NSIndexPath(item: item, section: 0)
self.collectionView.insertItems(at: [IndexPath])
</code>```

error show up ( Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

How to solve this issue. and is working with storyboard effecting the work with collectionView because I cannot change the cell size with :

```<code> public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let messageText = msg[indexPath.item].text {
            let size = CGSize(width: 250 , height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let esf = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(18))], context: nil)
            print("Changed")
            return CGSize(dictionaryRepresentation: esf as! CFDictionary)!
        }

          print("Not Changed")
        return CGSize(width: view.frame.width, height: CGFloat(100))

    }
</code>```

I have but a break point and it has not been reached!

答: You are using UIViewController and not UICollectionViewController so you don't get the collectionView property for free. You need to drag in an outlet form your storyboard and name it @IBOutlet var collectionView: UICollectionView!.</p>

Body:
I am creating a chatting app in Xcode 8 with Swift 3 and I am using collectionView for the messages. but I am having an issue with inserting a new item to the collection view when press send:

msg.append(message) // msg : Messages Array
let item = msg.count - 1
let IndexPath = NSIndexPath(item: item, section: 0)
self.collectionView.insertItems(at: [IndexPath])

error show up ( Ambiguous reference to member 'collectionView(_:numberOfItemsInSection:)'

How to solve this issue. and is working with storyboard effecting the work with collectionView because I cannot change the cell size with :

 public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let messageText = msg[indexPath.item].text {
            let size = CGSize(width: 250 , height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let esf = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(18))], context: nil)
            print("Changed")
            return CGSize(dictionaryRepresentation: esf as! CFDictionary)!
        }

          print("Not Changed")
        return CGSize(width: view.frame.width, height: CGFloat(100))

    }

I have but a break point and it has not been reached!


问:
Aligning Tumblr blockquotes below, not within, one another
I'm a newbie to HTML/CSS.  I decided to learn it so I could code my own Tumblr theme (and I'm proud to say it's nearly done!).  I'm trying to style the replies, which are in the form of blockquotes.  I want them to line up below one another, like rectangles one after the other (as in forum posts, etc.) but I can't work out how.  At the moment, they're stacking within one another, as is default:

You can see the problem...1

Any suggestions would be greatly appreciated.  Please and thank you :)

答:
The {Caption} variable doesn't allow any manipulation so you would need to use a script. There is a plugin available to achieve this though, see un-nest tumblr captions.

Alternatively, if you look in the new default tumblr theme's code, you will see that there is a wealth of undocumented variables they have used to achieve this.

For a photo post, this is the code they have:

```<code>{block:NotReblog}
<figcaption class="caption">
    {Caption}
</figcaption>
{/block:NotReblog}

{block:RebloggedFrom}
<div class="reblog-list">
    {block:Reblogs}
    <div class="post-reblog-trail-item{block:isOriginalEntry} original-reblog-content{/block:isOriginalEntry}">
        <div class="post-reblog-header">
            <div class="post-avatar">
                <div class="post-avatar-wrapper">
                    {block:IsActive}
                    <a class="post-avatar-link{block:isNotOriginalEntry} sub-icon-reblog{/block:isNotOriginalEntry}" href="{Permalink}" target="_blank">
                        <img class="post-avatar-image" src="{PortraitURL-64}">
                    </a>
                    {/block:IsActive}
                    {block:IsDeactivated}
                    <span class="inactive reblog-avatar{block:isNotOriginalEntry} sub-icon-reblog{/block:isNotOriginalEntry}">
                        <img class="post-avatar-image" src="{PortraitURL-64}">
                    </span>
                    {/block:IsDeactivated}
                </div>
            </div>
            {block:IsActive}
            <a target="_blank" class="post-tumblelog-name" href="{Permalink}">{Username}</a>
            {/block:IsActive}
            {block:IsDeactivated}
            <span class="inactive post-tumblelog-name">{Username}</span>
            {/block:IsDeactivated}
        </div>
        <div class="post-reblog-content">
            <div class="post-body">
                {Body}
            </div>
        </div>
    </div>
    {/block:Reblogs}
</div>
{/block:RebloggedFrom}
</code>```

Also a side note: From my experimenting with the above code, if you change {Portrait-64} to any of the other standard tumblr avatar sizes (like 30, 24 etc) it will revert back to just the blog that you're on's avatar.

Body:
The {Caption} variable doesn't allow any manipulation so you would need to use a script. There is a plugin available to achieve this though, see un-nest tumblr captions.

Alternatively, if you look in the new default tumblr theme's code, you will see that there is a wealth of undocumented variables they have used to achieve this.

For a photo post, this is the code they have:

{block:NotReblog}
<figcaption class="caption">
    {Caption}
</figcaption>
{/block:NotReblog}

{block:RebloggedFrom}
<div class="reblog-list">
    {block:Reblogs}
    <div class="post-reblog-trail-item{block:isOriginalEntry} original-reblog-content{/block:isOriginalEntry}">
        <div class="post-reblog-header">
            <div class="post-avatar">
                <div class="post-avatar-wrapper">
                    {block:IsActive}
                    <a class="post-avatar-link{block:isNotOriginalEntry} sub-icon-reblog{/block:isNotOriginalEntry}" href="{Permalink}" target="_blank">
                        <img class="post-avatar-image" src="{PortraitURL-64}">
                    </a>
                    {/block:IsActive}
                    {block:IsDeactivated}
                    <span class="inactive reblog-avatar{block:isNotOriginalEntry} sub-icon-reblog{/block:isNotOriginalEntry}">
                        <img class="post-avatar-image" src="{PortraitURL-64}">
                    </span>
                    {/block:IsDeactivated}
                </div>
            </div>
            {block:IsActive}
            <a target="_blank" class="post-tumblelog-name" href="{Permalink}">{Username}</a>
            {/block:IsActive}
            {block:IsDeactivated}
            <span class="inactive post-tumblelog-name">{Username}</span>
            {/block:IsDeactivated}
        </div>
        <div class="post-reblog-content">
            <div class="post-body">
                {Body}
            </div>
        </div>
    </div>
    {/block:Reblogs}
</div>
{/block:RebloggedFrom}

Also a side note: From my experimenting with the above code, if you change {Portrait-64} to any of the other standard tumblr avatar sizes (like 30, 24 etc) it will revert back to just the blog that you're on's avatar.


问:
Could I add param in _init() function when using dlopen() api under linux?
Now I coding a loadable .so module under linux, I want to use dlopen in main program and use _init() in loadable .so module. My program like this:

main program:

```<code>...
dlopen(lib, flags);
...
</code>```

loadable module:

```<code>#define MODULE_EXPORT(name, minit, mexit) \
    int __##name##_init(void) __attribute__((alias(#minit))); \
    void __##name##_exit(void) __attribute__((alias(#mexit)));

MODULE_EXPORT(dump, dump_init, dump_exit);

static int dump_init(void)
{
...
}
</code>```

Now I want to add param into dump_init function, like this:

```<code>static int dump_init(const char *param){}
</code>```

I don't know how to do this, or I could use another new api in linux? Thank you~

答:
No, you cannot pass arguments to a shared library initializer. If you need to pass parameters to your library, use a regular function.

(In your library's case, this should be simple -- remove the MODULE_EXPORT macro, and don't make dump_init static. Just call it normally from the host application.)

Generally speaking, you should avoid explicitly defining initializer and finalizer functions. They are primarily intended for internal use by the compiler, e.g. to call object initializers in C++.

Body:
Now I coding a loadable .so module under linux, I want to use dlopen in main program and use _init() in loadable .so module. My program like this:

main program:

...
dlopen(lib, flags);
...

loadable module:

#define MODULE_EXPORT(name, minit, mexit) \
    int __##name##_init(void) __attribute__((alias(#minit))); \
    void __##name##_exit(void) __attribute__((alias(#mexit)));

MODULE_EXPORT(dump, dump_init, dump_exit);

static int dump_init(void)
{
...
}

Now I want to add param into dump_init function, like this:

static int dump_init(const char *param){}

I don't know how to do this, or I could use another new api in linux? Thank you~


问:
Context menu to add column not working when defining columns property to hide some columns
I needed a way to create a spreadsheet where user can potentially paste in any no of columns. Currently pasting things in the spreadsheet does not work as mentioned here https://github.com/warpech/jquery-handsontable/issues/553, so I wanted to enable the context menu to add column. This works fine when you have plain array as data source and you are not setting the columns property, but if you do need to define the columns attribute then things dont work when setting the

```<code>contextMenu: ['col_right']
</code>```

. I needed to define the columns property because I need to hide certain columns (as mentioned here https://github.com/warpech/jquery-handsontable/issues/120).
The only way to make things work would be to define custom action for context menu, but I am not sure how to go about it.

Here is a jsbin : http://jsfiddle.net/8V4Z5/1/

Thanks

答:
As soon as you initialize a Handsontable with the columns option, you can no longer use the context menu to add a column.

A solution is to use the cell option instead.
To solve your issue, I replaced...

```<code>columns: [{
  data: 1
}, {
  data: 2
}, {
  data: 3
}],
</code>```

...with...

```<code>cells: function (row, col, prop) {
  var cellProperties = {};

  cellProperties.data = col;

  return cellProperties;
},
</code>```

Here's the working fiddle:
http://jsfiddle.net/oyxv3g9w/

Note that I also commented out a callback in the fiddle because the way it was implemented, it prevented the new column from being created despite the context menu item wasn't greyed out anymore.

Body:
I needed a way to create a spreadsheet where user can potentially paste in any no of columns. Currently pasting things in the spreadsheet does not work as mentioned here https://github.com/warpech/jquery-handsontable/issues/553, so I wanted to enable the context menu to add column. This works fine when you have plain array as data source and you are not setting the columns property, but if you do need to define the columns attribute then things dont work when setting the

contextMenu: ['col_right']

. I needed to define the columns property because I need to hide certain columns (as mentioned here https://github.com/warpech/jquery-handsontable/issues/120).
The only way to make things work would be to define custom action for context menu, but I am not sure how to go about it.

Here is a jsbin : http://jsfiddle.net/8V4Z5/1/

Thanks

Body:
As soon as you initialize a Handsontable with the columns option, you can no longer use the context menu to add a column.

A solution is to use the cell option instead.
To solve your issue, I replaced...

columns: [{
  data: 1
}, {
  data: 2
}, {
  data: 3
}],

...with...

cells: function (row, col, prop) {
  var cellProperties = {};

  cellProperties.data = col;

  return cellProperties;
},

Here's the working fiddle:
http://jsfiddle.net/oyxv3g9w/

Note that I also commented out a callback in the fiddle because the way it was implemented, it prevented the new column from being created despite the context menu item wasn't greyed out anymore.


问:
How to combine one android studio project into another android studio project
I have two separate android app projects that were made in android studio I am trying to combine project 1 into project 2 to make it all one app how would I go about doing this? I know how to do it in eclipse but not in android studio.
Please note they are both of these projects are android applications none of them are android libraries.

Any help would be amazing!

When I import project 1 into project module I get this error on grade build:

Warning:Dependency School Tools Calc lib.gz:SchoolTools:unspecified on project app resolves to an APK archive which is not supported as a compilation dependency. File: /Users/chrisdebrodie/Documents/School Tools Calc lib.gz/SchoolTools/build/outputs/apk/SchoolTools-release-unsigned.apk

答:
I write a repo to handle this staff safely and easily: Jacksgong/android-project-combine.

Characteristics:

Just a developing env wrapper, it can't modify projects, safe to use.
Different Android projects develop together at the one Android Studio window.

Find References and Jump into source code rather than .class file on jar package.

Jump out of the each projects compile system and using the official compile system.

Very light, very fast for each time you want to refresh combine project.


问:
Why can I pass by value here but not by reference (C++)?
I have an interesting predicament here where the code will compile if I pass a variable by value to the function but not if I pass it by reference, and I'm not sure why.  In header.h:

```<code>#include <iostream>
#include <string>

void get_name(std::string &name)
{
  getline(std::cin, name);
  return;
}

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T& operator=(const T& arg) {data = arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_string y;

    void f()
    {
      get_name(y); // compile error
    }
};
</code>```

The main.cpp implementation file simply includes this header file, creates an instance of myClass and then calls f().  When doing so, it won't compile properly.  The problem lies in the fact that I'm passing the variable y by reference to the get_name function.  If I change the function so that I pass by value instead, everything compiles properly and works as expected (except I'm obviously not making changes to y anymore).  However, I don't understand this behavior.  Why does this happen and is there an optimal way to fix it in this situation?

答:
Your conversion operator:

```<code>operator const T&() const {return data;}
</code>```

Only allows implicit conversion to a const reference. This makes sense since you are interested in making something read only. But get_name requires a non-const reference to a string. That is, get_name expects to be able to mutate its input. The type being passed in cannot convert to a mutable string reference, only to a constant string reference, so it doesn't compile.

When you pass by value, it simply constructs a new string from the const reference to pass into the function, which is fine.

Intuitively, a function called get_name should probably take a const reference since it shouldn't need to mutate its input just to get the name.

Body:
I have an interesting predicament here where the code will compile if I pass a variable by value to the function but not if I pass it by reference, and I'm not sure why.  In header.h:

#include <iostream>
#include <string>

void get_name(std::string &name)
{
  getline(std::cin, name);
  return;
}

template <class T, class U>
class readonly
{
  friend U;
  private:
    T data;
    T& operator=(const T& arg) {data = arg; return data;}
  public:
    operator const T&() const {return data;}
};

class myClass
{
  private:
    typedef readonly<std::string, myClass> RO_string;

  public:
    RO_string y;

    void f()
    {
      get_name(y); // compile error
    }
};

The main.cpp implementation file simply includes this header file, creates an instance of myClass and then calls f().  When doing so, it won't compile properly.  The problem lies in the fact that I'm passing the variable y by reference to the get_name function.  If I change the function so that I pass by value instead, everything compiles properly and works as expected (except I'm obviously not making changes to y anymore).  However, I don't understand this behavior.  Why does this happen and is there an optimal way to fix it in this situation?

Body:
Your conversion operator:

operator const T&() const {return data;}

Only allows implicit conversion to a const reference. This makes sense since you are interested in making something read only. But get_name requires a non-const reference to a string. That is, get_name expects to be able to mutate its input. The type being passed in cannot convert to a mutable string reference, only to a constant string reference, so it doesn't compile.

When you pass by value, it simply constructs a new string from the const reference to pass into the function, which is fine.

Intuitively, a function called get_name should probably take a const reference since it shouldn't need to mutate its input just to get the name.


问:
Building Strong Classifier from Weak Learners for Adaboost and Using It to Predict Data
I'm trying to understand how Adaboostworks. I know the basic idea of it. I've read many explanations of it, but I couldn't understand how to build strong classifier from the weak classifiers.

I believe the formula to build it goes something like:

```<code>c += sign(alpha(i)*h(i)).
</code>```

I know that alpha is the weight of class "i". But what does sign and h stands for? When 'sign' and 'h' becomes -1 and +1? And how do I predict the class of a new data with the strong classifier?

I've read Combining Weak Learners into a Strong Classifier but I still don't get when h or sign becomes -1 or 1 and predicting the class of a new data with it.

I'm sorry if these questions are too basic to be asked and have been asked for too many times. I've looked for many answers but unfortunately they're not helpful enough to me.

答:
Here's a more precise formula:

H stands for the final strong classifier, its value is equal to the signal of the weighted sum of the weak classifiers. So this formula is for binary classification problem, in other words a two-class problem. alpha_t is the weight of the classifier t and h_t(x) is the evaluation of the weak classifier t for the example x.

Answering your questions more directly:

But what does sign and h stands for?

sign(x) is a function that returns the signal of x (+1 or -1). h is a weak classifier.

When 'sign' and 'h' becomes -1 and +1?

That formula is for two-class problem, that means class -1 or class +1. h returns only one of this two values.

And how do I predict the class of a new data with the strong classifier?

The strong classifier will evaluate to -1 or +1 according to the signal of the expression inside of sign()

Take a look in this tutorial if you still with doubts.

Body:
I'm trying to understand how Adaboostworks. I know the basic idea of it. I've read many explanations of it, but I couldn't understand how to build strong classifier from the weak classifiers.

I believe the formula to build it goes something like:

c += sign(alpha(i)*h(i)).

I know that alpha is the weight of class "i". But what does sign and h stands for? When 'sign' and 'h' becomes -1 and +1? And how do I predict the class of a new data with the strong classifier?

I've read Combining Weak Learners into a Strong Classifier but I still don't get when h or sign becomes -1 or 1 and predicting the class of a new data with it.

I'm sorry if these questions are too basic to be asked and have been asked for too many times. I've looked for many answers but unfortunately they're not helpful enough to me.


问:
Breaking the callback chain - Node
I am wondering if it's possible to assign the value of callback to a variable. I recently ran into a problem with MongoClient's connect method, where I want to get the db object and pass it on to my class methods. Is there a way I can I assign hello world to var b.

```<code>function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  return str;
})

console.log(b) //undefined
</code>```

答:
Currently, you are assigning to b the result of invoking testCB, but testCB doesn't return anything, so nothing is assigned to b.

But there's nothing wrong with this pattern:

```<code>var b;

testCB( (str) => { b = str; } );
</code>```

This is the simplest version of maintaining application state in a variable (b), and modifying that state with asynchronous functions.

If many parts of your application depend on b and you want to define that dependence synchronously: that's what Promises are for!

In that case, you could define:

```<code>var b = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Hello World'), 1000);
});

b.then((str) => {...do something with str...}
b.then((str) => {...do something else with str...}
doSomeThingWithB(b);
</code>```

Where doSomeThingWithB of course knows that b is a promise (or "thennable").

Title: Breaking the callback chain - Node

Body:
I am wondering if it's possible to assign the value of callback to a variable. I recently ran into a problem with MongoClient's connect method, where I want to get the db object and pass it on to my class methods. Is there a way I can I assign hello world to var b.

function testCB(cb){
  setTimeout(() => {
    cb('Hello World')
  }, 1000)
}

let b = testCB('a', (str) => {
  return str;
})

console.log(b) //undefined

Body:
Currently, you are assigning to b the result of invoking testCB, but testCB doesn't return anything, so nothing is assigned to b.

But there's nothing wrong with this pattern:

var b;

testCB( (str) => { b = str; } );

This is the simplest version of maintaining application state in a variable (b), and modifying that state with asynchronous functions.

If many parts of your application depend on b and you want to define that dependence synchronously: that's what Promises are for!

In that case, you could define:

var b = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Hello World'), 1000);
});

b.then((str) => {...do something with str...}
b.then((str) => {...do something else with str...}
doSomeThingWithB(b);

Where doSomeThingWithB of course knows that b is a promise (or "thennable").


问:
Oracle join's order
I have a sql sentence.

```<code>select a.*,b.*,c.*
from a
inner join b
on a.id=b.id
left join c
on b.id=c.id
</code>```

but I not konw it is execute inner join first .then create a temporary table such as temp .and finaly temp left join c.  inner join ,left join and right join do they have same level of execution.Thank you!

答:
SQL is not a procedural language.  A SQL query describes the result set being produced.  When interpreting a query, the join order is from left to right.  So, in your query, the result set is the one produced by an inner join on a and b with that result being left joined to c.

You can add parentheses to avoid ambiguity:

```<code>from (a inner join
      b
      on a.id = b.id
     ) left join
     c
     on b.id = c.id
</code>```

But that is unnecessary.

That is logically how the query is processed.  The optimization engine can choose many different ways of executing the query, some of which might be pretty unrecognizable as relating to this particular query.  The only guarantee is what the result set looks like.

Title: Oracle join's order

Body:
I have a sql sentence.

select a.*,b.*,c.*
from a
inner join b
on a.id=b.id
left join c
on b.id=c.id

but I not konw it is execute inner join first .then create a temporary table such as temp .and finaly temp left join c.  inner join ,left join and right join do they have same level of execution.Thank you!

Body:
SQL is not a procedural language.  A SQL query describes the result set being produced.  When interpreting a query, the join order is from left to right.  So, in your query, the result set is the one produced by an inner join on a and b with that result being left joined to c.

You can add parentheses to avoid ambiguity:

from (a inner join
      b
      on a.id = b.id
     ) left join
     c
     on b.id = c.id

But that is unnecessary.

That is logically how the query is processed.  The optimization engine can choose many different ways of executing the query, some of which might be pretty unrecognizable as relating to this particular query.  The only guarantee is what the result set looks like.


问:
What is the difference between a data flow diagram and a flow chart?
I want to know why we use Data Flow Diagrams instead of flow charts.</p>

答:
Data Flow and Flow Chart differ in processes, flow, and timing.

Processes

a.) On DFDs, processes can operate in parallel (at-the-same-time).

b.) On flowcharts, processes execute one at a time.

Flow

a.) DFDs show the flow of data through a system

b.) Flowcharts show the flow of control (sequence and transfer of control)

Timing

a.) Processes on a DFD can have dramatically different timing (daily, weekly, on demand)

b.)
Processes on flowcharts are part of a single program with consistent timing

OwnerDisplayName: Rahul Vyas


问:
CSS color sections dived diagonally
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="diagonal">
</div></code>```

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

答:
I am able to get the desired result using the following linear gradient:

```<code>linear-gradient( 6deg,  transparent 73%, rgba(50, 87, 106, 0.72) 27%);
</code>```

You can control the shape very easily.

the first parameter or linear-gradient( 6deg... controls the degree of the skew - You can use negative values as well

The percentages after each of the colors control the location of the dividing line.

If the numbers don't add up to 100% the divider will be blurry.

I added an image background and background-blend-mode:overlay; in the example below for demo purposes.

body {
  text-align: center;
}

.test {
  height: 400px;
  width: 500px;
  margin: 0 auto;
  display: inline-block;
  background: url(https://unsplash.it/500/400), linear-gradient( 6deg,  transparent 73%, rgba(50, 87, 106, 0.72) 27%);
  background-blend-mode:overlay;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test"></div></code>```

Title: CSS color sections dived diagonally

Body:
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

Body:
I am able to get the desired result using the following linear gradient:

linear-gradient( 6deg,  transparent 73%, rgba(50, 87, 106, 0.72) 27%);

You can control the shape very easily.

the first parameter or linear-gradient( 6deg... controls the degree of the skew - You can use negative values as well

The percentages after each of the colors control the location of the dividing line.

If the numbers don't add up to 100% the divider will be blurry.

I added an image background and background-blend-mode:overlay; in the example below for demo purposes.

body {
  text-align: center;
}

.test {
  height: 400px;
  width: 500px;
  margin: 0 auto;
  display: inline-block;
  background: url(https://unsplash.it/500/400), linear-gradient( 6deg,  transparent 73%, rgba(50, 87, 106, 0.72) 27%);
  background-blend-mode:overlay;
}

<div class="test"></div>


问:
How to center my buttons vertically?
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html>
    <head>
    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">
    </head>

    <body>

    <h3>make your choice.</h3>

    <div id="light"><button>Light</button></div>
    <div id="dark"><button>Dark</button></div>

    </body>
    </html></code>```

This is a screencap of what this thing is doing:

答:
You forgot to set the #light div to inline-block.  But probably a better way to do it is just to surround both buttons in a div and give that some css of text-align:center like so:

body{
  background:black;
}
h3{
  text-align:center;
  color:white;
  font-family:Courier New;
  font-size:24px;
}
.text-center{
    text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Make Your Choice</h3>
<div class="text-center">
    <button>Light</button>
    <button>Dark</button>
</div></code>```

Title: How to center my buttons vertically?

Body:
I put a div around each button and I set them both to inline. They just want to stack as I keep trying to center them.

This is my HTML:

     body{
  background-color:black;
     }

    #light{
 margin-left:50%;
 margin-right:70%;
    }

    #dark{
 margin-left:50%;
 margin-right:50%;
 display:inline-block;
    }

    h3{
 color:white;
 font-family:Courier New;
 font-size:24px;
 margin-left:500px;
    }

    <!DOCTYPE html>

    <title>question reality.</title>
    <link rel="stylesheet" type="text/css" href="intro page.css">

make your choice.

<button>Light</button>

<button>Dark</button>

This is a screencap of what this thing is doing:

Body:
You forgot to set the #light div to inline-block.  But probably a better way to do it is just to surround both buttons in a div and give that some css of text-align:center like so:

body{
  background:black;
}
h3{
  text-align:center;
  color:white;
  font-family:Courier New;
  font-size:24px;
}
.text-center{
    text-align:center;
}

<h3>Make Your Choice</h3>
<div class="text-center">
    <button>Light</button>
    <button>Dark</button>
</div>


问:
Swift: Catch event for Facebook Login via Facebook app
I have a FB login implemented in my app, it opens a WebView and if a user log in via WebView, everything is ok. Facebook will return results I can work with

Working code with WebView:

```<code>fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: UIApplication.shared.keyWindow?.rootViewController?.presentedViewController) { (result, error) in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    self.getFBUserData()
                    fbLoginManager.logOut()
                }
            }
        }
        else
        {
            FBSDKLoginManager().logOut()
            print(error)
        }
    }
</code>```

However, if user does not log in via WebView, but select option to "Log in with the Facebook app", how can I get the result from Facebook app login?

答:
I had the same problem. it appeared only when I use a custom login button
and call the logIn method of the FBSDKLoginManager

If I use :

```<code>let loginButton = FBSDKLoginButton()
    loginButton.delegate = self
</code>```

and

```<code>func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
</code>```

}

the problem is solved, I have the result from Facebook app login.

You can easily custom the FBSDKLoginButton.

Body:
I have a FB login implemented in my app, it opens a WebView and if a user log in via WebView, everything is ok. Facebook will return results I can work with

Working code with WebView:

fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: UIApplication.shared.keyWindow?.rootViewController?.presentedViewController) { (result, error) in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    self.getFBUserData()
                    fbLoginManager.logOut()
                }
            }
        }
        else
        {
            FBSDKLoginManager().logOut()
            print(error)
        }
    }

However, if user does not log in via WebView, but select option to "Log in with the Facebook app", how can I get the result from Facebook app login?

Body:
I had the same problem. it appeared only when I use a custom login button
and call the logIn method of the FBSDKLoginManager

If I use :

let loginButton = FBSDKLoginButton()
    loginButton.delegate = self

and

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

}

the problem is solved, I have the result from Facebook app login.

You can easily custom the FBSDKLoginButton.


问:
How to send and receive multiple radio buttons value from jsp to jsp
I have list of questions, each question have 4 options Excellent, Better, Good and Poor these questions need to be rated by user any 1 option for each question. I am able to fetch the QID, Question from the MySQL database and list them in table followed by 4 radio button and name of each group of radio button for each question is assigned as their QID. Here is code

```<code><tr>
  <td>Q. No.</td>
  <td>Questions</td>
  <td>Excellent</td>
  <td>Better</td>
  <td>Good</td>
  <td>Poor</td>
  </tr>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback","root", "");
Statement st = con.createStatement();
ResultSet rs;

if(count>0){
rs = st.executeQuery("select * from question");
while(rs.next()){
int qno= rs.getInt(1);
String qname= rs.getString(2);
%>
<tr>
<td class="member"><%=qno %></td>
<td class="member"><%=qname %></td>
<td><input name="<%=qno %>" type="radio"  value="1" required="true"/></td>
<td><input name="<%=qno %>" type="radio"  value="2" required="true"/></td>
<td><input name="<%=qno %>" type="radio"  value="3" required="true"/></td>
<td><input name="<%=qno %>" type="radio"  value="4" required="true"/></td>
</tr>
<%
}%>
<tr>
   <td><input type="submit" value="Submit" /></td>
   <td><input type="reset" value="Reset" /></td>
</tr>
</code>```

I am stuck here now, I am not able to figure how to send the value of selected radio buttons to the jsp page, where I have to fetch the valued and store them in database as 1/ 2/ 3/ 4 of each question.
Here the output of above code
enter image description here

Also I am submitting the view source of html code generated by jsp for reference -

```<code><tr>
    <td>1</td>
    <td>How is your faculty communication</td>
    <td><input name="1" type="radio"  value="1" required="true"/></td>
    <td><input name="1" type="radio"  value="2" required="true"/></td>
    <td><input name="1" type="radio"  value="3" required="true"/></td>
    <td><input name="1" type="radio"  value="4" required="true"/></td>
</tr>
<tr>
    <td>2</td>
    <td>How is your study matrial</td>
    <td><input name="2" type="radio"  value="1" required="true"/></td>
    <td><input name="2" type="radio"  value="2" required="true"/></td>
    <td><input name="2" type="radio"  value="3" required="true"/></td>
    <td><input name="2" type="radio"  value="4" required="true"/></td>
</tr>
<tr>
    <td>3</td>
    <td>How your faculty language</td>
    <td><input name="3" type="radio"  value="1" required="true"/></td>
    <td><input name="3" type="radio"  value="2" required="true"/></td>
    <td><input name="3" type="radio"  value="3" required="true"/></td>
    <td><input name="3" type="radio"  value="4" required="true"/></td>
</tr>
</code>```

Kindly give some code/ suggestion/ guidance.

Thank you to all in advance

答: There is one more way to do this. You can assign same id lets say id="rb" to all the radio buttons and assign each a value using value="here you can use relevant filed from the DB". You will have a array of strings named cb whose values are assigned ffrom the DB field. Then on the next jsp retrieve the String[] cb using request.getParameter.Values("cb").</p>

Body:
I have list of questions, each question have 4 options Excellent, Better, Good and Poor these questions need to be rated by user any 1 option for each question. I am able to fetch the QID, Question from the MySQL database and list them in table followed by 4 radio button and name of each group of radio button for each question is assigned as their QID. Here is code

  Q. No.
  Questions
  Excellent
  Better
  Good
  Poor

<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback","root", "");
Statement st = con.createStatement();
ResultSet rs;

if(count>0){
rs = st.executeQuery("select * from question");
while(rs.next()){
int qno= rs.getInt(1);
String qname= rs.getString(2);
%>

<%=qno %>
<%=qname %>
<input name="<%=qno %>" type="radio"  value="1" required="true"/>
<input name="<%=qno %>" type="radio"  value="2" required="true"/>
<input name="<%=qno %>" type="radio"  value="3" required="true"/>
<input name="<%=qno %>" type="radio"  value="4" required="true"/>

<%
}%>

   <input type="submit" value="Submit" />
   <input type="reset" value="Reset" />

I am stuck here now, I am not able to figure how to send the value of selected radio buttons to the jsp page, where I have to fetch the valued and store them in database as 1/ 2/ 3/ 4 of each question.
Here the output of above code
enter image description here

Also I am submitting the view source of html code generated by jsp for reference -

    1
    How is your faculty communication
    <input name="1" type="radio"  value="1" required="true"/>
    <input name="1" type="radio"  value="2" required="true"/>
    <input name="1" type="radio"  value="3" required="true"/>
    <input name="1" type="radio"  value="4" required="true"/>

    2
    How is your study matrial
    <input name="2" type="radio"  value="1" required="true"/>
    <input name="2" type="radio"  value="2" required="true"/>
    <input name="2" type="radio"  value="3" required="true"/>
    <input name="2" type="radio"  value="4" required="true"/>

    3
    How your faculty language
    <input name="3" type="radio"  value="1" required="true"/>
    <input name="3" type="radio"  value="2" required="true"/>
    <input name="3" type="radio"  value="3" required="true"/>
    <input name="3" type="radio"  value="4" required="true"/>

Kindly give some code/ suggestion/ guidance.

Thank you to all in advance


问:
tightVNC connection from python2.7 error --No connection could be made because the target machine actively refused it
I have installed vncdotool on my python2.7

Download and install python-2.7.5.exe from the Python Downloads website

Open up Powershell, and paste in the following:

Restart your Windows Machine

Upon Restart, go to the Twisted Downloads and get and install 32bit Twisted, Twisted-13.1.0.win32-py2.7.exe

Download and install PIL-1.1.7.win32-py2.7.exe, from PIL Downloads.

Download ez_setup.py and get_pip.py and save them to your Python/Scripts folder, C:\Python27\Scripts

Open up Powershell and type the following:

```<code>pip install pip --upgrade
pip install distribute
pip install setuptools --upgrade
pip install Twisted --upgrade
pip install vncdotool < -- Finally install vncdotool
</code>```

At a Powershell prompt:

vncdo.exe --server 192.168.2.2 type "Hello World"

i tried above follow.
now i got error
like this.

```<code>c:\Python27\Scripts>vncdo.exe --server 192.168.2.11 type "hello world"
</code>```

CRITICAL:root:Connection was refused by other side: 10061: No connection could be made because the target machine actively refused it..

Please help me to solve this problem. Thanks.

答:
Your code has not problem.
May be problem is firewall or antivirus or server will sent your set rather than ack.</p>

Body:
I have installed vncdotool on my python2.7

Download and install python-2.7.5.exe from the Python Downloads website

Open up Powershell, and paste in the following:

Restart your Windows Machine

Upon Restart, go to the Twisted Downloads and get and install 32bit Twisted, Twisted-13.1.0.win32-py2.7.exe

Download and install PIL-1.1.7.win32-py2.7.exe, from PIL Downloads.

Download ez_setup.py and get_pip.py and save them to your Python/Scripts folder, C:\Python27\Scripts

Open up Powershell and type the following:

pip install pip --upgrade
pip install distribute
pip install setuptools --upgrade
pip install Twisted --upgrade
pip install vncdotool < -- Finally install vncdotool

At a Powershell prompt:

vncdo.exe --server 192.168.2.2 type "Hello World"

i tried above follow.
now i got error
like this.

c:\Python27\Scripts>vncdo.exe --server 192.168.2.11 type "hello world"

CRITICAL:root:Connection was refused by other side: 10061: No connection could be made because the target machine actively refused it..

Please help me to solve this problem. Thanks.


问:
Invalid update: invalid number of rows in section
I'm getting this error message which I can't figure out what to do or how to debug:

'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

I have 3 sections in my table. Here's the number of rows in each section before anything changes to my data source happens:

```<code>// Check current data source
date source for section 0: 1 items
data source for section 1: 8 items
data source for section 2: 8 items

sections count: 3
section 0 1 rows
section 1 8 rows
section 2 8 rows
</code>```

Here are what prints out after I delete a row from section 1 and I want to move it to section 2:

```<code>// Updated my date source
date source for section 0: 1 items
data source for section 1: 7 items
data source for section 2: 9 items

sections count: 3
section 0 1 rows
section 1 7 rows
section 2 9 rows

// Then the crash message happen
</code>```

Please help. Thanks.

答:
You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation.

Basically the same question in stackoverflow

Body:
I'm getting this error message which I can't figure out what to do or how to debug:

'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

I have 3 sections in my table. Here's the number of rows in each section before anything changes to my data source happens:

// Check current data source
date source for section 0: 1 items
data source for section 1: 8 items
data source for section 2: 8 items

sections count: 3
section 0 1 rows
section 1 8 rows
section 2 8 rows

Here are what prints out after I delete a row from section 1 and I want to move it to section 2:

// Updated my date source
date source for section 0: 1 items
data source for section 1: 7 items
data source for section 2: 9 items

sections count: 3
section 0 1 rows
section 1 7 rows
section 2 9 rows

// Then the crash message happen

Please help. Thanks.


问:
using http2 with okhttp in android, why 20 stream is created for 20 request
Using okhttp 3.8.1

I use okhttp http2 to request for 20 same pictures at the same time using multiple thread with same okhttpclient.

I use tcp dump to capture the traffic. Found that there are still 20 tcp stream, with one much larger, and the other 19 smaller.

My question is what are these 19 streams for. Or am I using ok http in the wrong way?

```<code>    up      down    count
    2510    56320   1
    352     3492    19
</code>```

my code is something like this

```<code>    OkHttpClient client = builder.build();
    for (int i = 0; i < urls.length; i++) {
        runTest(urls[i], client);
        }
...
    private void runTest(...)
        new Thread(new Runnable() {
                @Override
                public void run() {
                        Request request = new Request.Builder()
                                .url(url)
                                .build();
                        try {
                            Response response = client.newCall(request).execute();
                            result = response.body().string();
                        } catch (IOException e) {
                        }
                    }
                }
            }).start();
    }
</code>```

答:
the answer lies in the discussions here https://github.com/square/okhttp/issues/3442

in brief, when the concurrent requests starts, there's not a usable tcp channel yet, so okhttp create new tcp channel for each request(20). after the first one is establish, with the coalescing mechanism, the other requests will abandon the tcp channel it create and use the first established one.

Body:
Using okhttp 3.8.1

I use okhttp http2 to request for 20 same pictures at the same time using multiple thread with same okhttpclient.

I use tcp dump to capture the traffic. Found that there are still 20 tcp stream, with one much larger, and the other 19 smaller.

My question is what are these 19 streams for. Or am I using ok http in the wrong way?

    up      down    count
    2510    56320   1
    352     3492    19

my code is something like this

    OkHttpClient client = builder.build();
    for (int i = 0; i < urls.length; i++) {
        runTest(urls[i], client);
        }
...
    private void runTest(...)
        new Thread(new Runnable() {
                @Override
                public void run() {
                        Request request = new Request.Builder()
                                .url(url)
                                .build();
                        try {
                            Response response = client.newCall(request).execute();
                            result = response.body().string();
                        } catch (IOException e) {
                        }
                    }
                }
            }).start();
    }


问:
If else statement depending on textfield (swif3)
I would like my code to simply display a label if and only if there is text in the textfiled if there is no text the label should be hidden. Thats it. My code below does not do what I have described above.</p>

```<code>   import UIKit
class ViewController: UIViewController {

  @IBOutlet var label: UILabel!
  @IBOutlet var txtfield: UITextField!
 override func viewDidLoad() {
super.viewDidLoad()
appear()

  }
   func appear() {

if (txtfield.text?.isEmpty)! {
    label.isHidden = true

}
else {
    label.isHidden = false
}}}
</code>```

答:
Your code won't work because the check is only being performed ONCE when the View Controller is loaded.

What you have to do is run the appear() function every time the user finishes editing the text field.

So just set the delegate of your text view to this view controller and implement this function:

```<code>optional func textViewDidEndEditing(_ textView: UITextView)
</code>```

https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618628-textviewdidendediting

Then just call the appear() inside it.

Edit: Text Field version

```<code>optional func textFieldDidEndEditing(_ textField: UITextField)
</code>```

https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619591-textfielddidendediting

Body:
I would like my code to simply display a label if and only if there is text in the textfiled if there is no text the label should be hidden. Thats it. My code below does not do what I have described above.

   import UIKit
class ViewController: UIViewController {

  @IBOutlet var label: UILabel!
  @IBOutlet var txtfield: UITextField!
 override func viewDidLoad() {
super.viewDidLoad()
appear()

  }
   func appear() {

if (txtfield.text?.isEmpty)! {
    label.isHidden = true

}
else {
    label.isHidden = false
}}}

Body:
Your code won't work because the check is only being performed ONCE when the View Controller is loaded.

What you have to do is run the appear() function every time the user finishes editing the text field.

So just set the delegate of your text view to this view controller and implement this function:

optional func textViewDidEndEditing(_ textView: UITextView)

https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618628-textviewdidendediting

Then just call the appear() inside it.

Edit: Text Field version

optional func textFieldDidEndEditing(_ textField: UITextField)

https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619591-textfielddidendediting


答:
Try this

CSS

```<code> body{
 background-color:black;
 }

#light,#dark,h3{
  text-align:center;
}

h3{
color:white;
font-family:Courier New;
font-size:24px;
}
</code>```

use text-align:center property instead of margins on left and right

Hope this helps...

Title: How to center my buttons vertically?

Body:
Try this

CSS

 body{
 background-color:black;
 }

#light,#dark,h3{
  text-align:center;
}

h3{
color:white;
font-family:Courier New;
font-size:24px;
}

use text-align:center property instead of margins on left and right

Hope this helps...


问:
Get value from multi tr of table
I have many table row, i want to get the value (it's a number) of each row to an array !

```<code><form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]" /></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]" /></td>
        </tr>
    </tbody>
</table>
</code>```

Like this code, i want to get the value of each "pduct" !

答:
JQuery

You can use serialize() and serializeArray() to grab all the input values of a form.

In your example, you can do something like this:

var formData = $('#form1').serializeArray();    \\Outputs in the form [{name, value}]
var formArray = formData.map(function(element){ \\If you only want the values
 return element.value;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" value="1"/></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]"  value="2"/></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]"  value="3"/></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]"  value="4"/></td>
        </tr>
    </tbody>
</table>
</form></code>```

Native Javascript

You can do the same in native javascript by instantiating a FormData object and using it's methods to grab all the input values.

var form = document.getElementById("form1");
var formData = new FormData(form);
var formArray = [];
for(var value of formData.values()){
 formArray.push(value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" value="1"/></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]"  value="2"/></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]"  value="3"/></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]"  value="4"/></td>
        </tr>
    </tbody>
</table>
</form></code>```

Title: Get value from multi tr of table

Body:
I have many table row, i want to get the value (it's a number) of each row to an array !

<form class="form-horizontal" id="form1" name="form1" method="post" action="url">

            Name
            Number

            A
            <input type="number" id="pduct1" class="product" name="pduct[]" />

            B
            <input type="number" id="pduct2" class="product" name="pduct[]" />

            C
            <input type="number" id="pduct3" class="product" name="pduct[]" />

            D
            <input type="number" id="pduct4" class="product" name="pduct[]" />

Like this code, i want to get the value of each "pduct" !

Body:
JQuery

You can use serialize() and serializeArray() to grab all the input values of a form.

In your example, you can do something like this:

var formData = $('#form1').serializeArray();    \\Outputs in the form [{name, value}]
var formArray = formData.map(function(element){ \\If you only want the values
 return element.value;
})

<form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" value="1"/></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]"  value="2"/></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]"  value="3"/></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]"  value="4"/></td>
        </tr>
    </tbody>
</table>
</form>

Native Javascript

You can do the same in native javascript by instantiating a FormData object and using it's methods to grab all the input values.

var form = document.getElementById("form1");
var formData = new FormData(form);
var formArray = [];
for(var value of formData.values()){
 formArray.push(value);
}

<form class="form-horizontal" id="form1" name="form1" method="post" action="url">
<table id="temp1" class="table datatable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>A</td>
            <td><input type="number" id="pduct1" class="product" name="pduct[]" value="1"/></td>
        </tr>
        <tr>
            <td>B</td>
            <td><input type="number" id="pduct2" class="product" name="pduct[]"  value="2"/></td>
        </tr>
        <tr>
            <td>C</td>
            <td><input type="number" id="pduct3" class="product" name="pduct[]"  value="3"/></td>
        </tr>
        <tr>
            <td>D</td>
            <td><input type="number" id="pduct4" class="product" name="pduct[]"  value="4"/></td>
        </tr>
    </tbody>
</table>
</form>


问:
Return only the item with 10th total Sale
I need to write a query that ONLY returns the item which has the 10th totalSale value. I know that I can use TOP to get the first 10items, but I want it to only show the 10th item. Here is the query that I have written:

```<code>SELECT TOP 10 D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I JOIN FCT_Sales F_S ON D_I.ID = F_S.ID
GROUP BY D_I.ID
</code>```

Please help! thank you

答:
```<code>SELECT D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I
JOIN FCT_Sales F_S
ON D_I.ID = F_S.ID
GROUP BY D_I.ID
Offset 9 rows fetch next 1 rows only
Order by TotalSale
</code>```

Offset will skip the first 9 rows, next 1 row will be selected. Do order by asc or desc , based on your requirement.

Body:
I need to write a query that ONLY returns the item which has the 10th totalSale value. I know that I can use TOP to get the first 10items, but I want it to only show the 10th item. Here is the query that I have written:

SELECT TOP 10 D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I JOIN FCT_Sales F_S ON D_I.ID = F_S.ID
GROUP BY D_I.ID

Please help! thank you

Body:
SELECT D_I.ID, SUM(F_S.Sale) AS TOTALSALE
FROM Dim_ItemsD_I
JOIN FCT_Sales F_S
ON D_I.ID = F_S.ID
GROUP BY D_I.ID
Offset 9 rows fetch next 1 rows only
Order by TotalSale

Offset will skip the first 9 rows, next 1 row will be selected. Do order by asc or desc , based on your requirement.


问:
How To Asynchronously Read/Write A Named Pipe In C#
I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.

This all works fine.

On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.

Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.

Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?

Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)

GUpdater (The Named Pipe Server):

```<code>private void WaitForClientCommands()
{
    // Wait for a connection from a Named Pipe Client (The GUpControl)
    pipeStream.WaitForConnection();
    pipeConnected = true;

    // Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
    pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
    pipeStreamReader = new StreamReader(pipeStream);

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if(isWritingToPipe) continue;

        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        switch(message)
        {
            case "CheckForUpdates":
                //MessageBox.Show("Told to check for updates");
                SendMessageToClient("Checking For Updates, Woot!");
                break;
            case "DownloadUpdate":
                MessageBox.Show("Told to download update");
                break;
            case "ApplyUpdate":
                MessageBox.Show("Told to apply update");
                break;
        }
    }
}
</code>```

GUpControl (The Named Pipe Client):

```<code>private void WaitForServerCommands()
{
    if(!pipeConnected) return;

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if (isWritingToPipe) continue;

        // Attempt to read a line from the pipe
        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        MessageBox.Show("I got a message from the server!!\r\n" + message);
    }
}
</code>```

The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient and SendMessageToServer)

```<code>private void SendMessageToServer(string message)
{
    if(pipeConnected)
    {
        isWritingToPipe = true;
        pipeStreamWriter.WriteLine(message);
        isWritingToPipe = false;
    }
}
</code>```

The isWritingToPipe variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.

Any help is much appreciated!

答: when you send a signal  to server for checking updates then do it in BackgroundWorker class</p>

Body:
I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.

This all works fine.

On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.

Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.

Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?

Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)

GUpdater (The Named Pipe Server):

private void WaitForClientCommands()
{
    // Wait for a connection from a Named Pipe Client (The GUpControl)
    pipeStream.WaitForConnection();
    pipeConnected = true;

    // Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
    pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
    pipeStreamReader = new StreamReader(pipeStream);

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if(isWritingToPipe) continue;

        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        switch(message)
        {
            case "CheckForUpdates":
                //MessageBox.Show("Told to check for updates");
                SendMessageToClient("Checking For Updates, Woot!");
                break;
            case "DownloadUpdate":
                MessageBox.Show("Told to download update");
                break;
            case "ApplyUpdate":
                MessageBox.Show("Told to apply update");
                break;
        }
    }
}

GUpControl (The Named Pipe Client):

private void WaitForServerCommands()
{
    if(!pipeConnected) return;

    // Now that we have a connection, start reading in messages and processing them
    while (true)
    {
        // Skip this time if we are currently writing to the pipe
        if (isWritingToPipe) continue;

        // Attempt to read a line from the pipe
        var message = pipeStreamReader.ReadLine();
        if (message == null)
        {
            // We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
            Thread.Sleep(500);
            continue;
        }

        MessageBox.Show("I got a message from the server!!\r\n" + message);
    }
}

The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient and SendMessageToServer)

private void SendMessageToServer(string message)
{
    if(pipeConnected)
    {
        isWritingToPipe = true;
        pipeStreamWriter.WriteLine(message);
        isWritingToPipe = false;
    }
}

The isWritingToPipe variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.

Any help is much appreciated!


问:
Must NuGet configure project's include paths?
I have downloaded Dropbox CPP REST sample from official MS site. In order to use cpprestsdk I asked NuGet to download package. It has downloaded packages for various tool sets:

When I build project I got error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   C1083   Cannot open include file: 'uri.h': No such file or directory    DropboxApp  d:\code_podurirest0813\dropboxapp\dropboxapp\oAuth.h    30
</code>```

uri.h is part of library. I was expecting NuGet set up include paths in project. Do I expect too much or there might be other issues?

UPD

MS Dropbox sample was not happy about changing uri.h to cpprest\uri.h. It can't find new include ither.

Since this reason I have created my own console application and asked NuGet download cpprestsdk. After procedure was done I found that no automatic library and include paths setup was performed:

```<code>1>  Creating directory "D:\Code_PoduriREST0813\2012\ConsoleApplication1\Debug\".
1>InitializeBuildStatus:
1>  Creating "Debug\ConsoleApplication1.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  stdafx.cpp
1>  ConsoleApplication1.cpp
1>d:\code_podurirest0813\2012\consoleapplication1\consoleapplication1\consoleapplication1.cpp(5): fatal error C1083: Cannot open include file: 'cpprest\uri.h': No such file or directory
</code>```

答:
I was expecting NuGet set up include paths in project. Do I expect too much or there might be other issues?

No, after installed that package, NuGet would set the header files and library paths automatically, no need to add them manually. But we should carefully how to include the header file. You will notice that there are two subfolder "cpprest", "pplx" in the "include" folder. So we should use "cpprest\uri.h" to include the header file:

So please check the way of including the header file in the project.

Update:

I have noticed the difference is that the version of your Visual Studio is 2012 (the default version of NuGet is 2.8.6), my Visual Studio is 2015(The version of NuGet is 3.4.4). Then I test it on the Visual Studio 2012 and 2013, only failed on Visual Studio 2012, not sure why the old version of NuGet(2.8.6) could not setup library and header paths automatically. However, we could not use the new version of NuGet in Visual Studio 2012, so to resolve this issue, we have to add the path of library and header file manually or you can update you Visual Studio to 2013 and later.

Body:
I have downloaded Dropbox CPP REST sample from official MS site. In order to use cpprestsdk I asked NuGet to download package. It has downloaded packages for various tool sets:

When I build project I got error:

Severity    Code    Description Project File    Line    Suppression State
Error   C1083   Cannot open include file: 'uri.h': No such file or directory    DropboxApp  d:\code_podurirest0813\dropboxapp\dropboxapp\oAuth.h    30

uri.h is part of library. I was expecting NuGet set up include paths in project. Do I expect too much or there might be other issues?

UPD

MS Dropbox sample was not happy about changing uri.h to cpprest\uri.h. It can't find new include ither.

Since this reason I have created my own console application and asked NuGet download cpprestsdk. After procedure was done I found that no automatic library and include paths setup was performed:

1>  Creating directory "D:\Code_PoduriREST0813\2012\ConsoleApplication1\Debug\".
1>InitializeBuildStatus:
1>  Creating "Debug\ConsoleApplication1.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>ClCompile:
1>  stdafx.cpp
1>  ConsoleApplication1.cpp
1>d:\code_podurirest0813\2012\consoleapplication1\consoleapplication1\consoleapplication1.cpp(5): fatal error C1083: Cannot open include file: 'cpprest\uri.h': No such file or directory


问:
Combine 2 android projects into one
I have 2 android project 1 and 2. I need to create one screen with button A and B. If i click A screen it should invoke 1 project same if i click B it should invoke 2. But it should create one apk. Can you please suggest your ideas.</p>

答: very recommend to use the repo to handle your require safely and easily: Jacksgong/android-project-combine, which just mock an wrapper env project to let you maintain multiple projects on one Android Studio window.

Title: Combine 2 android projects into one