问:
Create class from Nested JSON with code re usability in C#
I have JSON data coming as

```<code>{ "ResultOne":{ "Value1":2,"Value2":3,"Type":"SimpleAdd","Result":5}}
</code>```

Few other JSON data as

```<code>{ "ResultTwo":{ "Value1":2,"Value2":3,"Type":"SimpleSubtract","Result":-1}}

{ "ResultThree":{ "Value1":2,"Value2":3,"Type":"SimpleMultiply","Result":6}}
</code>```

and so on.

So basically, the inner JSON remains the same, while the outer value keeps changing. I use json2csharp.com to generate class (to make things easier).

```<code>    public class ResultOne
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public string Type { get; set; }
    public int Result { get; set; }
}

public class RootObject
{
    public ResultOne ResultOne { get; set; }
}
</code>```

How can I create a class in C# to reuse code (instead of creating multiple properties for each results in Rootobject, may be reflection ?
any pointers in the right direction is helpful. thanks.

EDIT:
I am actually using a Delegate to call the server to get JSON response.

```<code> delegate Task<RootObject> Operation(int Value1, int Value2);
</code>```

The delegate is used to pass in as variable in the method below. This Operation opMeth will determine the type of result that we receive. That will depend on the user input. so I cannot use ResultOne, but need a generic result in the method below.

```<code>private async Task<string> DoSomeOp(int Value1, int Value2, Operation opMeth)
    {
        var opResult = await opMeth(Value1, Value1);
        string resultValue = opResult.ResultOne.Result;
        return resultValue;
    }
</code>```

答:
Well, though your JSON is pretty simple and represent simple Dictionary type, you can avoid creating any classes at all, by using dynamic:</p>

```<code>using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = "{ \"ResultTwo\":{ \"Value1\":2,\"Value2\":3,\"Type\":\"SimpleSubtract\",\"Result\":-1}}";

            dynamic des = JsonConvert.DeserializeObject(str);
            var val = (int)des.ResultTwo.Value1;
            Console.WriteLine(val);
        }
    }
}
</code>```

Body:
I have JSON data coming as

{ "ResultOne":{ "Value1":2,"Value2":3,"Type":"SimpleAdd","Result":5}}

Few other JSON data as

{ "ResultTwo":{ "Value1":2,"Value2":3,"Type":"SimpleSubtract","Result":-1}}

{ "ResultThree":{ "Value1":2,"Value2":3,"Type":"SimpleMultiply","Result":6}}

and so on.

So basically, the inner JSON remains the same, while the outer value keeps changing. I use json2csharp.com to generate class (to make things easier).

    public class ResultOne
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public string Type { get; set; }
    public int Result { get; set; }
}

public class RootObject
{
    public ResultOne ResultOne { get; set; }
}

How can I create a class in C# to reuse code (instead of creating multiple properties for each results in Rootobject, may be reflection ?
any pointers in the right direction is helpful. thanks.

EDIT:
I am actually using a Delegate to call the server to get JSON response.

 delegate Task<RootObject> Operation(int Value1, int Value2);

The delegate is used to pass in as variable in the method below. This Operation opMeth will determine the type of result that we receive. That will depend on the user input. so I cannot use ResultOne, but need a generic result in the method below.

private async Task<string> DoSomeOp(int Value1, int Value2, Operation opMeth)
    {
        var opResult = await opMeth(Value1, Value1);
        string resultValue = opResult.ResultOne.Result;
        return resultValue;
    }

Body:
Well, though your JSON is pretty simple and represent simple Dictionary type, you can avoid creating any classes at all, by using dynamic:

using Newtonsoft.Json;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var str = "{ \"ResultTwo\":{ \"Value1\":2,\"Value2\":3,\"Type\":\"SimpleSubtract\",\"Result\":-1}}";

            dynamic des = JsonConvert.DeserializeObject(str);
            var val = (int)des.ResultTwo.Value1;
            Console.WriteLine(val);
        }
    }
}


来源: stackexchange

问:
How to stop a loop when pressing "OK" on a message box with VBS?
I want to write a bot for a video game I play to type stuff.

```<code>set sellAllTyping = wscript.CreateObject("WScript.Shell")

x= MsgBox ("To stop the bot, click OK. /// Coded by Vncz with a little help from StackOverflow! :^) RIP Yams ;-;",vbOK+vbInformation,"sell all Bot")

if x=vbOK then
' *** I don't know what to write here. ***

sellAllTyping.sendkeys "t"
wscript.sleep 1000
sellAllTyping.sendkeys "/sell all"
wscript.sleep 1000
sellAllTyping.sendkeys "{ENTER}"
wscript.sleep 5000
loop
</code>```

I want to have the loop on the very bottom stop if I press OK on the message box I summoned. In place of the comment, what code should I write, if I'm even doing it right?

答:
Unfortuately, msgbox freeze the execution.

In others words, you cannot loop between the moment the message apear and the moment you click on Ok or Cancel.

The only way to achieve this is to make a HTA file like this:

```<code><SCRIPT LANGUAGE="VBScript" src="test.vbs"> </SCRIPT>
<input type='button' value='Start' onclick='startLoop()'>
<input type='button' value='Stop' onclick='stopLoop()'>
</code>```

then, on the linked vbs file (for this example, it's test.vbs), you must write something like this:

```<code>set sellAllTyping = CreateObject("Wscript.shell")
loopState = true

sub startLoop()
    do while loopState = true
        msgbox "yeah"
    loop
end sub

sub stopLoop()
    loopState = false
end sub
</code>```

The only problem now is that the app is freezing because of the loop (if I replace msgbox with sendkeys) or is always hide behind the msgbox.

this code work well (with a sleep function):

```<code>set sellAllTyping = CreateObject("Wscript.shell")
loopState = true

sub startLoop()
    do while loopState = true
        msgbox "yeah"
        sleep(2)
    loop
end sub

sub stopLoop()
    loopState = false
end sub

Sub sleep (Timesec)
  sellAllTyping.Run "Timeout /T " & Timesec & " /nobreak" ,0 ,true
End Sub
</code>```

Make sure you name the hta file "something.hta" and NOT "something.html"

ContentLicense: CC BY-SA 4.0

Body:
I want to write a bot for a video game I play to type stuff.

set sellAllTyping = wscript.CreateObject("WScript.Shell")

x= MsgBox ("To stop the bot, click OK. /// Coded by Vncz with a little help from StackOverflow! :^) RIP Yams ;-;",vbOK+vbInformation,"sell all Bot")

if x=vbOK then
' *** I don't know what to write here. ***

sellAllTyping.sendkeys "t"
wscript.sleep 1000
sellAllTyping.sendkeys "/sell all"
wscript.sleep 1000
sellAllTyping.sendkeys "{ENTER}"
wscript.sleep 5000
loop

I want to have the loop on the very bottom stop if I press OK on the message box I summoned. In place of the comment, what code should I write, if I'm even doing it right?

Body:
Unfortuately, msgbox freeze the execution.

In others words, you cannot loop between the moment the message apear and the moment you click on Ok or Cancel.

The only way to achieve this is to make a HTA file like this:

<SCRIPT LANGUAGE="VBScript" src="test.vbs"> </SCRIPT>
<input type='button' value='Start' onclick='startLoop()'>
<input type='button' value='Stop' onclick='stopLoop()'>

then, on the linked vbs file (for this example, it's test.vbs), you must write something like this:

set sellAllTyping = CreateObject("Wscript.shell")
loopState = true

sub startLoop()
    do while loopState = true
        msgbox "yeah"
    loop
end sub

sub stopLoop()
    loopState = false
end sub

The only problem now is that the app is freezing because of the loop (if I replace msgbox with sendkeys) or is always hide behind the msgbox.

this code work well (with a sleep function):

set sellAllTyping = CreateObject("Wscript.shell")
loopState = true

sub startLoop()
    do while loopState = true
        msgbox "yeah"
        sleep(2)
    loop
end sub

sub stopLoop()
    loopState = false
end sub

Sub sleep (Timesec)
  sellAllTyping.Run "Timeout /T " & Timesec & " /nobreak" ,0 ,true
End Sub

Make sure you name the hta file "something.hta" and NOT "something.html"

ContentLicense: CC BY-SA 3.0


问:
"Cannot create infinite type" error in Haskell
I'd like to know why Haskell accepts this

```<code>perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
</code>```

but won't accept that:

```<code>perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
</code>```

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

```<code>Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)
</code>```

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

```<code>perms [] = [[]]
</code>```

at the top.

Thanks

答:
My brain hurts and I'm not an expert, but I think:

In

```<code>perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
</code>```

perms (takeOut i  xs) is a list of lists. x is consed onto each element of that list. Perms is invoked on the list as a whole, so perms is a function taking list-of-thing.

In

```<code>perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
</code>```

(takeOut i xs) is a list, and for each element of that list x is consed onto perms of that element. Perms is invoked on each element of the list, so perms is a function taking thing.

Only the former case is internally consistent, and the typechecker loves you.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to know why Haskell accepts this

perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]

but won't accept that:

perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

perms [] = [[]]

at the top.

Thanks

Body:
My brain hurts and I'm not an expert, but I think:

In

perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]

perms (takeOut i  xs) is a list of lists. x is consed onto each element of that list. Perms is invoked on the list as a whole, so perms is a function taking list-of-thing.

In

perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]

(takeOut i xs) is a list, and for each element of that list x is consed onto perms of that element. Perms is invoked on each element of the list, so perms is a function taking thing.

Only the former case is internally consistent, and the typechecker loves you.


问:
Is there a way to synchronously wait for the completion of a recursive asynchronous function in Javascript?
I have the following javascript code written to run in node.js:

```<code>const fs = require("fs");
const path = require("path");

var copy = function(paramSource, paramDestination, paramCallback) {
  if (fs.existsSync(paramDestination)) {
    return paramCallback("Destination Exists"); //TODO make formal error code
  } else {
    fs.lstat(paramSource, function(error, sourceStats) {
      if (error) {
        return paramCallback(error);
      } else {
        if (sourceStats.isDirectory()) {
          fs.readdir(paramSource, function(error, sourceContents) {
            if (error) {
              return paramCallback(error);
            } else {
              fs.mkdir(paramDestination, sourceStats.mode, function(error) {
                if (error) {
                  paramCallback(error);
                } else {
                  if (sourceContents.length > 0) {
                    sourceContents.forEach(function(sourceChild) {
                      copy(path.join(paramSource, sourceChild), path.join(paramDestination, sourceChild), paramCallback);
                    });
                  }
                  return paramCallback(null, paramDestination);
                }
              });
            }
          });
        } else {
          var sourceFile = fs.createReadStream(paramSource);
          var destinationFile = fs.createWriteStream(paramDestination); //TODO permissions
          sourceFile.on("error", function(error) {
            return paramCallback(error);
          });
          destinationFile.on("error", function(error) {
            return paramCallback(error);
          });
          sourceFile.on("close", function() {
            //return paramCallback(null, paramSource);
          });
          destinationFile.on("close", function() {
            return paramCallback(null, paramDestination);
          });
          sourceFile.pipe(destinationFile);
        }
      }
    });
  }
};

var entities = 0;

copy("/home/fatalkeystroke/testing/directory_01", "/home/fatalkeystroke/testing/directory_01_copy", function(error, name) {
  if (error) {
    console.log(error);
  } else {
    console.log(name);
    entities++;
  }
});

console.log("Copied " + entities + " entities.");
console.log("Program Done.");
</code>```

It's a testing exerpt from an application I'm working on. I would like to keep the asynchronous nature of the copy() function, however I also want a way to know when the full copy is complete (as the code related to entities implies). The reasoning is because I want to be able to tell when it's done of course, but also implement a progress tracking capability.

Is there a way to synchronously wait for the completion of a recursive asynchronous function in Javascript?

答:
This could be done with sequential executor nsynjs. Your code will transform as follows:

```<code>var copy = function (src,dst) {
    if(nsynFs.lstat(nsynjsCtx, src).data.isDirectory()) {
        var files = nsynFs.readdir(nsynjsCtx, src).data;
        nsynFs.mkdir(nsynjsCtx,dst);
        for(var i=0; i<files.length; i++) {
            var f=files[i];
            console.log(f);
            copy(src+"/"+f, dst+"/"+f);
        }
    }
    else { // is File
        var input = nsynFs.open(nsynjsCtx,src,'r').data;
        var output = nsynFs.open(nsynjsCtx,dst,'w').data;
        var buf = Buffer.alloc(4096);
        while(true) {
            var readCnt = nsynFs.read(nsynjsCtx,input,buf,0,4096,null).data;
            if(!readCnt)
                break;
            nsynFs.write(nsynjsCtx,output,buf,0,readCnt,null);
        }
        nsynFs.close(nsynjsCtx,input);
        nsynFs.close(nsynjsCtx,output);
    }
};

copy("test1","test2");
</code>```

Please see full working example here: https://github.com/amaksr/nsynjs/blob/master/examples/node-copy-files/index.js

Body:
I have the following javascript code written to run in node.js:

const fs = require("fs");
const path = require("path");

var copy = function(paramSource, paramDestination, paramCallback) {
  if (fs.existsSync(paramDestination)) {
    return paramCallback("Destination Exists"); //TODO make formal error code
  } else {
    fs.lstat(paramSource, function(error, sourceStats) {
      if (error) {
        return paramCallback(error);
      } else {
        if (sourceStats.isDirectory()) {
          fs.readdir(paramSource, function(error, sourceContents) {
            if (error) {
              return paramCallback(error);
            } else {
              fs.mkdir(paramDestination, sourceStats.mode, function(error) {
                if (error) {
                  paramCallback(error);
                } else {
                  if (sourceContents.length > 0) {
                    sourceContents.forEach(function(sourceChild) {
                      copy(path.join(paramSource, sourceChild), path.join(paramDestination, sourceChild), paramCallback);
                    });
                  }
                  return paramCallback(null, paramDestination);
                }
              });
            }
          });
        } else {
          var sourceFile = fs.createReadStream(paramSource);
          var destinationFile = fs.createWriteStream(paramDestination); //TODO permissions
          sourceFile.on("error", function(error) {
            return paramCallback(error);
          });
          destinationFile.on("error", function(error) {
            return paramCallback(error);
          });
          sourceFile.on("close", function() {
            //return paramCallback(null, paramSource);
          });
          destinationFile.on("close", function() {
            return paramCallback(null, paramDestination);
          });
          sourceFile.pipe(destinationFile);
        }
      }
    });
  }
};

var entities = 0;

copy("/home/fatalkeystroke/testing/directory_01", "/home/fatalkeystroke/testing/directory_01_copy", function(error, name) {
  if (error) {
    console.log(error);
  } else {
    console.log(name);
    entities++;
  }
});

console.log("Copied " + entities + " entities.");
console.log("Program Done.");

It's a testing exerpt from an application I'm working on. I would like to keep the asynchronous nature of the copy() function, however I also want a way to know when the full copy is complete (as the code related to entities implies). The reasoning is because I want to be able to tell when it's done of course, but also implement a progress tracking capability.

Is there a way to synchronously wait for the completion of a recursive asynchronous function in Javascript?

Body:
This could be done with sequential executor nsynjs. Your code will transform as follows:

var copy = function (src,dst) {
    if(nsynFs.lstat(nsynjsCtx, src).data.isDirectory()) {
        var files = nsynFs.readdir(nsynjsCtx, src).data;
        nsynFs.mkdir(nsynjsCtx,dst);
        for(var i=0; i<files.length; i++) {
            var f=files[i];
            console.log(f);
            copy(src+"/"+f, dst+"/"+f);
        }
    }
    else { // is File
        var input = nsynFs.open(nsynjsCtx,src,'r').data;
        var output = nsynFs.open(nsynjsCtx,dst,'w').data;
        var buf = Buffer.alloc(4096);
        while(true) {
            var readCnt = nsynFs.read(nsynjsCtx,input,buf,0,4096,null).data;
            if(!readCnt)
                break;
            nsynFs.write(nsynjsCtx,output,buf,0,readCnt,null);
        }
        nsynFs.close(nsynjsCtx,input);
        nsynFs.close(nsynjsCtx,output);
    }
};

copy("test1","test2");

Please see full working example here: https://github.com/amaksr/nsynjs/blob/master/examples/node-copy-files/index.js


问:
Node-Mysql throwing connection timeout
My node.js app gives 5xx due to connection timeouts at random times. Here's how I connect and query:

```<code>var mysql = require('mysql');
var config = {
            host: '172.10.1.1',
            port: 3306,
            user: 'user',
            password: 'pwd',
            database: 'mydb',
            connectionLimit: 15,
            queueLimit: 30
        }

var poolCluster = mysql.createPool(config);

var queryDB = function(query, cb) {
    poolCluster.getConnection(function(err, connection) {
        if(err) {
            cb(err, null);
        }
        else {
            connection.query(query, function (err, rows) {
                connection.release();
                cb(err, rows);
            });
        }
    });
};
</code>```

Also, in another alternate version, with connection pooling disabled, the code looks like this:

```<code>queryDB = function(query, cb) {
    var connection = mysql.createConnection(config);
    connection.query(query, function(err, rows) {
        connection.end();
        cb(err, rows);
    });
};
</code>```

But both the setups give
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout

A similar project to my current setup can be seen here: https://github.com/hay-wire/NodeBootstrap/blob/master/models/UsersUtils.js

It would be great if you could point out what could be going wrong with the connections. Thanks.

UPDATE

Since the node.js service was running in cluster mode, I thought maybe a race condition across the threads to acquire mysql connection resource from the shared connection pool is the reason. So I switched off the cluster mode to single thread mode and connection timeouts stopped.

Still I'm not convinced it was the race condition causing this issue. Any way to verify this?

答:
This has nothing to do with the timeout. I noticed the following (if you are using it in something like AWS Lambda functions, I think this also applies to many situations with callbacks).

You are calling the connection.end(); before it actually sends the COM_QUIT packet to the MySQL server to close the connection. So the next time you just import var mysql = require('mysql'); (in my case at least) it will throw a timeout error as the previous connection still seems open to your machine but has actually been closed by MySQL.

Please see this link from directly from the documentation on terminating connections

So to fix this condition use .destroy() instead of .end().

```<code>connection.query(query, function(err, rows)
{
    connection.destroy();
    cb(err, rows);
});
</code>```

Other wise use .end() correctly with a callback as in:

```<code>connection.query(query, function(err, rows)
{
    connection.end(function(errCon) //Don't do anything with end Error
    {
       // The connection is terminated now
       cb(err, rows);
    });
});
</code>```

Title: Node-Mysql throwing connection timeout

Body:
My node.js app gives 5xx due to connection timeouts at random times. Here's how I connect and query:

var mysql = require('mysql');
var config = {
            host: '172.10.1.1',
            port: 3306,
            user: 'user',
            password: 'pwd',
            database: 'mydb',
            connectionLimit: 15,
            queueLimit: 30
        }

var poolCluster = mysql.createPool(config);

var queryDB = function(query, cb) {
    poolCluster.getConnection(function(err, connection) {
        if(err) {
            cb(err, null);
        }
        else {
            connection.query(query, function (err, rows) {
                connection.release();
                cb(err, rows);
            });
        }
    });
};

Also, in another alternate version, with connection pooling disabled, the code looks like this:

queryDB = function(query, cb) {
    var connection = mysql.createConnection(config);
    connection.query(query, function(err, rows) {
        connection.end();
        cb(err, rows);
    });
};

But both the setups give
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout

A similar project to my current setup can be seen here: https://github.com/hay-wire/NodeBootstrap/blob/master/models/UsersUtils.js

It would be great if you could point out what could be going wrong with the connections. Thanks.

UPDATE

Since the node.js service was running in cluster mode, I thought maybe a race condition across the threads to acquire mysql connection resource from the shared connection pool is the reason. So I switched off the cluster mode to single thread mode and connection timeouts stopped.

Still I'm not convinced it was the race condition causing this issue. Any way to verify this?

Body:
This has nothing to do with the timeout. I noticed the following (if you are using it in something like AWS Lambda functions, I think this also applies to many situations with callbacks).

You are calling the connection.end(); before it actually sends the COM_QUIT packet to the MySQL server to close the connection. So the next time you just import var mysql = require('mysql'); (in my case at least) it will throw a timeout error as the previous connection still seems open to your machine but has actually been closed by MySQL.

Please see this link from directly from the documentation on terminating connections

So to fix this condition use .destroy() instead of .end().

connection.query(query, function(err, rows)
{
    connection.destroy();
    cb(err, rows);
});

Other wise use .end() correctly with a callback as in:

connection.query(query, function(err, rows)
{
    connection.end(function(errCon) //Don't do anything with end Error
    {
       // The connection is terminated now
       cb(err, rows);
    });
});


问:
iOS - pause AVSpeech while reading a specific word
I'm working on an app that reads the text in a UITextField using AVSpeech and I'm trying to pause reading when it reads a specific word, for example its reading this This is awesome. and I want it to pause reading for 2 seconds when it reads is and then complete reading. Here is my code to read the string.

```<code>AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"This is awesome"];
utterance.rate = 0.15;
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-us"];
[synth speakUtterance:utterance];
</code>```

Thanks

答: Split into two utterances and set the second with .preUtteranceDelay = 2.0</p>

Body:
I'm working on an app that reads the text in a UITextField using AVSpeech and I'm trying to pause reading when it reads a specific word, for example its reading this This is awesome. and I want it to pause reading for 2 seconds when it reads is and then complete reading. Here is my code to read the string.

AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"This is awesome"];
utterance.rate = 0.15;
utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-us"];
[synth speakUtterance:utterance];

Thanks


问:
Firefox overriding style of html select option
Ok, so this has been annoying me now for some time and I can not figure out what is causing this. I am wondering if anyone else is having this issue or noticed this.

In my css I have the html select options styled to look similar to this

On some computers it looks like how I've styled it and on some it appears something is overriding the style and then it looks like this

Some facts so far to help determine what is causing this.
All the computers I've tested are running windows 7.
My main pc that has numerous programs installed doe not have this issue.
My laptop has this issue.
My small pc that has a clean install with very few programs has this issue, also does not have any adobe products installed.
On the PC's with the issue, if I do a refresh in firefox the issue is fixed for about 5-10 min and then comes back.

If this were a CSS issue why would refreshing firefox temporarily fix and then later come back?

This leads me to think that some background plugin or setting is getting fetched after a refresh.

Could this be some other application on windows causing this?

Can someone tell me if they can reproduce this issue and also how to fix this and what is causing it?

Here is my CSS

```<code>SELECT {
    color: #555558;
    font-size: 16px;
    margin: 0px 0px 8px 12px;
    padding: 2px 0px 2px 5px;
    width: 203px;
}
</code>```

html

```<code><select>
<option> - Select a Page - </option>
<option>Home Page</option>
<option>About Us</option>
<option>Camping Tips</option>
</select>
</code>```

I posted several months ago regarding this issue however now the issue is not related to the version of firefox or CSS so the answers provided are misguided. Did Firefox 48 remove ability to style the select element?

Here is a list of plugins, as stated above, default installation produces this issue.

答:
Ok, so the solution here is to disable -> Multiprocess Windows

type about:config in the browser

then search for browser.tabs.remote.autostart (mine had a browser.tabs.remote.autostart.2)

change this to FALSE then restart the browser
this will make firefox run Multiprocess Windows disabled which fixes the issue

Body:
Ok, so this has been annoying me now for some time and I can not figure out what is causing this. I am wondering if anyone else is having this issue or noticed this.

In my css I have the html select options styled to look similar to this

On some computers it looks like how I've styled it and on some it appears something is overriding the style and then it looks like this

Some facts so far to help determine what is causing this.
All the computers I've tested are running windows 7.
My main pc that has numerous programs installed doe not have this issue.
My laptop has this issue.
My small pc that has a clean install with very few programs has this issue, also does not have any adobe products installed.
On the PC's with the issue, if I do a refresh in firefox the issue is fixed for about 5-10 min and then comes back.

If this were a CSS issue why would refreshing firefox temporarily fix and then later come back?

This leads me to think that some background plugin or setting is getting fetched after a refresh.

Could this be some other application on windows causing this?

Can someone tell me if they can reproduce this issue and also how to fix this and what is causing it?

Here is my CSS

SELECT {
    color: #555558;
    font-size: 16px;
    margin: 0px 0px 8px 12px;
    padding: 2px 0px 2px 5px;
    width: 203px;
}

html

<select>
<option> - Select a Page - </option>
<option>Home Page</option>
<option>About Us</option>
<option>Camping Tips</option>
</select>

I posted several months ago regarding this issue however now the issue is not related to the version of firefox or CSS so the answers provided are misguided. Did Firefox 48 remove ability to style the select element?

Here is a list of plugins, as stated above, default installation produces this issue.


问:
Apollo: Call a mutation server-side from cron job?
I have a Meteor app that uses Apollo and I am using SyncedCron (https://github.com/percolatestudio/meteor-synced-cron) to schedule an update operation on the database every 2 hours.

Every two hours, fetch X data from some external API and store in Y collection of the database. Rinse and repeat.

My question is this: should this update operation be implemented as a graphQL mutation, and called server-side from within the cron job (if so, how do you do it?!), or should this be implemented as a normal JS function since it will only ever execute on the server?

All the mutation examples I can find online are invoked from the client by wrapping your View component in a graphql-enabled HOC.

Perhaps I am just misunderstanding the scope of mutations, and the larger question here is whether or not mutations CAN be invoked from the server, or if they are client-side only.

Hoping to find some clarification here on mutation best practices. Thanks!

答: I think you would just use axios (http call) or a meteor method here. I think mutations are just for browser-to-server.</p>


问:
Different behavior of the same two operations on pointers
I write this code and the output was like this B C D E

```<code>char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = a + 2;
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}
</code>```

But when I add reference like this :

```<code>char a[5] = {'A' , 'B' , 'C' , 'D'};
    char *b = &a + 2;
    int i = 0 ;
    for(i = 0 ; i < 4 ; i ++)
    {
        *b = (a[i] + 1);
        printf("%c",*b);
    }
</code>```

the output become just B.

答:
Compiler should report error on

```<code>char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = &a + 2; // <<< compile error
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}
</code>```

and if you remove the line that generates compile error, the output should be no difference from your first piece of code.

Body:
I write this code and the output was like this B C D E

char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = a + 2;
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}

But when I add reference like this :

char a[5] = {'A' , 'B' , 'C' , 'D'};
    char *b = &a + 2;
    int i = 0 ;
    for(i = 0 ; i < 4 ; i ++)
    {
        *b = (a[i] + 1);
        printf("%c",*b);
    }

the output become just B.

Body:
Compiler should report error on

char a[5] = {'A' , 'B' , 'C' , 'D'};
char *b = &a + 2; // <<< compile error
int i = 0 ;
for(i = 0 ; i < 4 ; i ++)
{
    *b = (a[i] + 1);
    printf("%c",*b);
}

and if you remove the line that generates compile error, the output should be no difference from your first piece of code.


问:
captcha or not?
i hate captcha, do you think there is a better solution </p>

答:
You may check Practical non-image based CAPTCHA approaches?

I asked a question earlier Need suggestions/ideas for easy-to-use but secure captchas

However if you are irritated due to the difficulty faced by users because of the very existence of captchas, then there has been a lot of debate over this and people are still trying hard to come up with a universal solution which can work even for very popular sites.

You should see http://nedbatchelder.com/text/stopbots.html for implementation of Negative captchas. But sadly, this is not effective as yet for site specific spam attacks (when your site gets very popular) as far as I have understood. The author says he has been using these techniques successfully for less popular sites. The overall conclusion with the state-of-the-art negative captchas is that whatever technique you use, spammers can program their bots to crack it in some time if they target your site. And they will probably target your site when it gets very popular. But you can definitely use them till your site is not very popular.

Title: captcha or not?


问:
How do I delete a specific row when I click a button using jquery?
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css"></link>
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/script.js"></script>
    </head>
<body>
    <!-- Create a table-->
    <table style width="800" border="1" cellpadding="1" cellspacing="1">
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <!-- Create headings. Every row is defined as with <tr> tag-->
    <tr>
    <th>Player ID</th>
    <th>Player Name</th>
    <th>Player Position</th>
    <th>Delete</th>
    </tr>

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "<div class = 'row'>";
            echo "<tr>";
            echo "<td>".$row['id']."</td>";
            echo "<td>".$row['surname']."</td>";
            echo "<td>".$row['position']."</td>";
            echo "<td><button id = 'dlt_btn' type='button'>Delete</button></td>";
            echo "</tr>";
            echo "</div>";

        }

    ?>

</body>
</code>```

script.js

```<code>$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});
</code>```

delete.php

```<code>?
</code>```

答:
You should be using a class vs ID in this context, but you can use $(this) to locate the clicked element, and traverse/remove via .parent() jquery method. This is purely to remove the row from the DOM, you would need to perform an ajax request to tell the server which row to remove from the database.  In this case, you should add the row ID attribute to the html, and send this along with the AJAX request.

You could append the row ID in the button as an attribute, like

<button id = 'dlt_btn' type='button' row-id='<?=$yourRowID%>'>Delete</button>```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$(document).ready(function () {

    $("#dlt_btn").click(function(){
        let rowId = $(this).attr('row-id'); //Pull the attribute from your button
        let tr =  $(this).parent().parent(); //Define the TR itself

        $.post('/delete.php', {row_id:  rowId}, function(result){
          //Do something with the message your page returns after deleting
          tr.remove(); //Remove the TR from the dom
        });
    });

});</code>```

Body:
I have a table of player data with a delete button next to each row.
When the button is clicked, it should delete that specific row instantly using jQuery. I have included my code thus far. I am really stuck when the button should be clicked. Should I use a header function?

index.php

<!DOCTYPE html>

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

    Player ID
    Player Name
    Player Position
    Delete

    <?php
        require "php/conn.php";
        //Select query
        $res = $db -> query ("SELECT * FROM player");
        //Set pointer to 1
        $res -> data_seek(0);
        //Display data using while loop
        while ($row = $res -> fetch_assoc()) {
            // Write html code in php using this method
            echo "
";
            echo "
";
            echo "".$row['id']."	";
            echo "".$row['surname']."	";
            echo "".$row['position']."	";
            echo "<button id = 'dlt_btn' type='button'>Delete</button>	";
            echo "
";
            echo "
";

        }

    ?>

script.js

$(document).ready(function () {

    $("#dlt_btn").click(function(){
        //Activate 'delete.php'
    });

});

delete.php

?

Body:
You should be using a class vs ID in this context, but you can use $(this) to locate the clicked element, and traverse/remove via .parent() jquery method. This is purely to remove the row from the DOM, you would need to perform an ajax request to tell the server which row to remove from the database.  In this case, you should add the row ID attribute to the html, and send this along with the AJAX request.

You could append the row ID in the button as an attribute, like

<button id = 'dlt_btn' type='button' row-id='<?=$yourRowID%>'>Delete</button>

$(document).ready(function () {

    $("#dlt_btn").click(function(){
        let rowId = $(this).attr('row-id'); //Pull the attribute from your button
        let tr =  $(this).parent().parent(); //Define the TR itself

        $.post('/delete.php', {row_id:  rowId}, function(result){
          //Do something with the message your page returns after deleting
          tr.remove(); //Remove the TR from the dom
        });
    });

});


问:
How to set DialogFragment's width and height?
Let's say I specify the layout of my DialogFragment in an xml layout file named my_dialog_fragment.xml and I specify the layout_width and layout_height values of its root view to a fixed value (e.g. 100dp). I then inflate this layout in my DialogFragment's onCreateView(...) method as follows:

View view = inflater.inflate(R.layout.my_dialog_fragment, container, false);
```
<p>When my <code>DialogFragment</code> appears, it does not respect the <code>layout_width</code> and <code>layout_height</code> values specified in its xml layout file and instead shrinks or expands depending on its content. Does anybody know whether or how I can get my <code>DialogFragment</code> to respect the <code>layout_width</code> and <code>layout_height</code> values specified in its xml layout file? At the moment I'm having to specify the width and height of the <code>Dialog</code> again in my <code>DialogFragment</code>'s <code>onResume()</code> method as follows:</p>
<pre class="lang-java prettyprint-override"><code>getDialog().getWindow().setLayout(width, height);
</code>```

The problem with this is that I have to remember to make any future changes to the width and height in two places.

答:
One of the earlier solutions almost worked. I tried something slightly different and it ended up working for me.

(Make sure you look at his solution)
This was his solution.. Click Here
It worked except for: builder.getContext().getTheme().applyStyle(R.style.Theme_Window_NoMinWidth, true);

I changed it to

```<code> @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Get layout inflater
        LayoutInflater layoutInflater = getActivity().getLayoutInflater();

        // Set layout by setting view that is returned from inflating the XML layout
        builder.setView(layoutInflater.inflate(R.layout.dialog_window_layout, null));

        AlertDialog dialog = builder.create();

        dialog.getContext().setTheme(R.style.Theme_Window_NoMinWidth);
</code>```

The last line is whats different really.

Body:
Let's say I specify the layout of my DialogFragment in an xml layout file named my_dialog_fragment.xml and I specify the layout_width and layout_height values of its root view to a fixed value (e.g. 100dp). I then inflate this layout in my DialogFragment's onCreateView(...) method as follows:

View view = inflater.inflate(R.layout.my_dialog_fragment, container, false);

When my DialogFragment appears, it does not respect the layout_width and layout_height values specified in its xml layout file and instead shrinks or expands depending on its content. Does anybody know whether or how I can get my DialogFragment to respect the layout_width and layout_height values specified in its xml layout file? At the moment I'm having to specify the width and height of the Dialog again in my DialogFragment's onResume() method as follows:

getDialog().getWindow().setLayout(width, height);

The problem with this is that I have to remember to make any future changes to the width and height in two places.

Body:
One of the earlier solutions almost worked. I tried something slightly different and it ended up working for me.

(Make sure you look at his solution)
This was his solution.. Click Here
It worked except for: builder.getContext().getTheme().applyStyle(R.style.Theme_Window_NoMinWidth, true);

I changed it to

 @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Get layout inflater
        LayoutInflater layoutInflater = getActivity().getLayoutInflater();

        // Set layout by setting view that is returned from inflating the XML layout
        builder.setView(layoutInflater.inflate(R.layout.dialog_window_layout, null));

        AlertDialog dialog = builder.create();

        dialog.getContext().setTheme(R.style.Theme_Window_NoMinWidth);

The last line is whats different really.


问:
Formatting a String to have a string with the words/numbers in line
So I am trying to create function that returns a String. The String starts off with the inputed word, then a certain number of spaces, and then a number. The number of spaces varies based on the length of the word. The idea is that all the words and numbers should be in line when the method is called multiple times. I have a picture of how I would like the String to be formatted.

Format Example

This is the function I currently have. When I type several random words and numbers into the function and use a printLn statement each time, the function works correctly and prints as I would like it to be formatted (or as shown above in the example)

```<code>public String formatList(String x, int y){
    String z = x;
    int stringLength=x.length();
    int i=0;
    while(i<(30-stringLength)){
     z+=" ";
     i++;
    }
    z+=String.valueOf(y);
    return z;
}
</code>```

However, when I have a for loop enter a list of words and numbers, and add it to a JTextArea titled wordList, I get the following (note that the wordDistribution is an object I defined that is essentially an ArrayList of map entries  and getDistribution is a function that returns this ArrayList)
:

```<code>String x="";

for(int i=0; i<wordDistribution.getDistribution().size();i++){
        String word = wordDistribution.getDistribution().get(i).getKey();
        int count = wordDistribution.getDistribution().get(i).getValue();
        x+=formatList(word,count)+"\n";
    }
    wordList.setText(x);
</code>```

Resulting format

答:
Use String.format(), e.g.

```<code>StringBuilder buf = new StringBuilder();
buf.append(String.format("%-20s%4d%n", "Foo", 42));
buf.append(String.format("%-20s%4d%n", "Hello World", 11));
buf.append(String.format("%-20s%4d%n", "This is Great", 999));
System.out.print(buf);
</code>```

Output

Foo                   42
Hello World           11
This is Great        999
```

Body:
So I am trying to create function that returns a String. The String starts off with the inputed word, then a certain number of spaces, and then a number. The number of spaces varies based on the length of the word. The idea is that all the words and numbers should be in line when the method is called multiple times. I have a picture of how I would like the String to be formatted.

Format Example

This is the function I currently have. When I type several random words and numbers into the function and use a printLn statement each time, the function works correctly and prints as I would like it to be formatted (or as shown above in the example)

public String formatList(String x, int y){
    String z = x;
    int stringLength=x.length();
    int i=0;
    while(i<(30-stringLength)){
     z+=" ";
     i++;
    }
    z+=String.valueOf(y);
    return z;
}

However, when I have a for loop enter a list of words and numbers, and add it to a JTextArea titled wordList, I get the following (note that the wordDistribution is an object I defined that is essentially an ArrayList of map entries  and getDistribution is a function that returns this ArrayList)
:

String x="";

for(int i=0; i<wordDistribution.getDistribution().size();i++){
        String word = wordDistribution.getDistribution().get(i).getKey();
        int count = wordDistribution.getDistribution().get(i).getValue();
        x+=formatList(word,count)+"\n";
    }
    wordList.setText(x);

Resulting format

Body:
Use String.format(), e.g.

StringBuilder buf = new StringBuilder();
buf.append(String.format("%-20s%4d%n", "Foo", 42));
buf.append(String.format("%-20s%4d%n", "Hello World", 11));
buf.append(String.format("%-20s%4d%n", "This is Great", 999));
System.out.print(buf);

Output

Foo                   42
Hello World           11
This is Great        999


问:
can the extract fun rarfile module handle the chinese character?
I used the rarfile and unrar in Python to extract some chinese character named files in the rar archives.
when I use rarobj.extractall(TargetDir) function , It works.
BUT when I use

```<code>#encoding:utf-8
...
for fl in rarobj.namelist():
    rarobj.extract(fl,TargetDir)
</code>```

There is an Error:

```<code>rarfile.RarNoFilesError: No files that match pattern were found [10]
</code>```

and changed in following:

```<code>#encoding:gbk
    ...
    for fl in rarobj.namelist():
        rarobj.extract(fl,TargetDir)
</code>```

There is another Error:

```<code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)
</code>```

and use

```<code>for fl in rarobj.namelist():
    rarobj.extract(fl.encode('gbk'),TargetDir)
</code>```

Can eliminate this error,however It can't extract the fl file , for the filename is not in the rar archive.

How I can handle this problem?

The rarobj.namelist() is

```<code>[u'E:\\2y.pptx', u'E:\\\u6211\u662fabc.pptx', 'E:\\3b.docx', u'E:\\2x.docx', 'E:\\1a.pptx', 'E:\\1b.docx']
</code>```

答:
Use open instead of extract

```<code>file_like_object = rarobj.open(fl)
data = file_like_object.read()
</code>```

Body:
I used the rarfile and unrar in Python to extract some chinese character named files in the rar archives.
when I use rarobj.extractall(TargetDir) function , It works.
BUT when I use

#encoding:utf-8
...
for fl in rarobj.namelist():
    rarobj.extract(fl,TargetDir)

There is an Error:

rarfile.RarNoFilesError: No files that match pattern were found [10]

and changed in following:

#encoding:gbk
    ...
    for fl in rarobj.namelist():
        rarobj.extract(fl,TargetDir)

There is another Error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)

and use

for fl in rarobj.namelist():
    rarobj.extract(fl.encode('gbk'),TargetDir)

Can eliminate this error,however It can't extract the fl file , for the filename is not in the rar archive.

How I can handle this problem?

The rarobj.namelist() is

[u'E:\\2y.pptx', u'E:\\\u6211\u662fabc.pptx', 'E:\\3b.docx', u'E:\\2x.docx', 'E:\\1a.pptx', 'E:\\1b.docx']

Body:
Use open instead of extract

file_like_object = rarobj.open(fl)
data = file_like_object.read()


问:
What is the best pattern for two way communication between classes?
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

```<code>public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }
</code>```

答:
This is an example, also can be done using Interfaces.</p>

```<code>public abstract class Attachable
{
    public void Attach(Attachable attachable)
    {
        Attached = attachable;
        attachable.Attach(this);
    }

    public Attachable Attached { get; private set; }
    public abstract void DoSomethingUseful(object argument);
}

public class A : Attachable
{
    #region Overrides of Attachable

    public override void DoSomethingUseful(object argument)
    {
        // do something useful
    }

    #endregion
}

public class B : Attachable
{
    #region Overrides of Attachable

    public override void DoSomethingUseful(object argument)
    {
        // do something useful

    }

    #endregion
}

// Usage
A a = new A();
B b = new B();
a.Attach(b);
</code>```

Body:
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }

Body:
This is an example, also can be done using Interfaces.

public abstract class Attachable
{
    public void Attach(Attachable attachable)
    {
        Attached = attachable;
        attachable.Attach(this);
    }

    public Attachable Attached { get; private set; }
    public abstract void DoSomethingUseful(object argument);
}

public class A : Attachable
{
    #region Overrides of Attachable

    public override void DoSomethingUseful(object argument)
    {
        // do something useful
    }

    #endregion
}

public class B : Attachable
{
    #region Overrides of Attachable

    public override void DoSomethingUseful(object argument)
    {
        // do something useful

    }

    #endregion
}

// Usage
A a = new A();
B b = new B();
a.Attach(b);


问:
constructor on type "" not found when inheriting forms c# forms
created a form that inherits from another form, but for some reason I am getting the error constructor on type "baseForm" not found. This is the inheriting class constructor:

```<code>public partial class loadHtmlFormsDatabaseForm :      NEA_Official.createHtmlFormsForm
{
    List<field> listOfFields = new List<field>();
    static string username1;
    int originalListOfFieldsCount;
    htmlFormsProject loadedProject;

    public loadHtmlFormsDatabaseForm(htmlFormsProject loadProject, string username) : base(username1)
    {
        username1 = username;
        loadedProject = loadProject;
        InitializeComponent();
    }
</code>```

This is the constructor for the base class:

```<code>    public partial class createHtmlFormsForm : Form
{
    List<field> listOfFields = new List<field>();
    string username = "";

    public createHtmlFormsForm(string username1)
    {
        username = username1;
        InitializeComponent();
    }
</code>```

答:
You can fix it by overload the constructor with  no parameter in base class like this:

```<code>public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }
 public createHtmlFormsForm()
 {
    InitializeComponent();
 }
}
</code>```

If you don't need constructor with no parameter you can create it private :

```<code>public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }
// private contructor with no parameter
 private createHtmlFormsForm()
 {
    InitializeComponent();
 }
}
</code>```

or you can use Obsolete Attribute:

```<code>public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }

 [Obsolete("Designer only", true)]
 public createHtmlFormsForm()
 {
    InitializeComponent();
 }
}
</code>```

Body:
created a form that inherits from another form, but for some reason I am getting the error constructor on type "baseForm" not found. This is the inheriting class constructor:

public partial class loadHtmlFormsDatabaseForm :      NEA_Official.createHtmlFormsForm
{
    List<field> listOfFields = new List<field>();
    static string username1;
    int originalListOfFieldsCount;
    htmlFormsProject loadedProject;

    public loadHtmlFormsDatabaseForm(htmlFormsProject loadProject, string username) : base(username1)
    {
        username1 = username;
        loadedProject = loadProject;
        InitializeComponent();
    }

This is the constructor for the base class:

    public partial class createHtmlFormsForm : Form
{
    List<field> listOfFields = new List<field>();
    string username = "";

    public createHtmlFormsForm(string username1)
    {
        username = username1;
        InitializeComponent();
    }

Body:
You can fix it by overload the constructor with  no parameter in base class like this:

public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }
 public createHtmlFormsForm()
 {
    InitializeComponent();
 }
}

If you don't need constructor with no parameter you can create it private :

public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }
// private contructor with no parameter
 private createHtmlFormsForm()
 {
    InitializeComponent();
 }
}

or you can use Obsolete Attribute:

public partial class createHtmlFormsForm : Form
{
 List<field> listOfFields = new List<field>();
 string username = "";

 public createHtmlFormsForm(string username1)
 {
    username = username1;
    InitializeComponent();
 }

 [Obsolete("Designer only", true)]
 public createHtmlFormsForm()
 {
    InitializeComponent();
 }
}


问:
Build failed Liferay 6.2 application
I am trying to configure an existing liferay 6.2 application in my eclipse IDE but I am unable to build the application. The problem seems to be in ivy.xml file. The dependencies present there are not getting auto downloaded.
Following is the code present in ivy.xml:

```<code> <?xml version="1.0"?>
   <ivy-module version="2.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
   <info module="portlet_primefaces_tmpl" organisation="com.liferay" />

    <dependencies defaultconf="default">
        <dependency name="el-api" org="javax.el" rev="2.2" />
        <dependency name="jboss-el" org="org.jboss.el" rev="2.0.1.GA" />
        <dependency name="jsf-api" org="com.sun.faces" rev="2.1.21" />
        <dependency name="jsf-impl" org="com.sun.faces" rev="2.1.21" />
        <dependency name="liferay-faces-bridge-api" org="com.liferay.faces"    rev="3.2.4-ga5" />
        <dependency name="liferay-faces-bridge-impl" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="liferay-faces-portal" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="liferay-faces-util" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="primefaces" org="org.primefaces" rev="3.5" />
    </dependencies>
    </ivy-module>
</code>```

The error while building the application :

BUILD FAILED
  E:\Liferay_Project_Edistrict\liferay-plugins-sdk-6.2\build-common-ivy.xml:81: java.net.ConnectException: Connection refused: connect

答:
I just answered a question similar to this and while your post is also short on details you might be experiencing a common issue in some 6.2 minor releases.  Find your build.USERNAME.properties file and add the following lines, then try to build again</p>

```<code>ivy.version = 2.3.0
ivy.jar.url = http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.version}/ivy-${ivy.version}.jar
</code>```

Title: Build failed Liferay 6.2 application

Body:
I am trying to configure an existing liferay 6.2 application in my eclipse IDE but I am unable to build the application. The problem seems to be in ivy.xml file. The dependencies present there are not getting auto downloaded.
Following is the code present in ivy.xml:

 <?xml version="1.0"?>
   <ivy-module version="2.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
   <info module="portlet_primefaces_tmpl" organisation="com.liferay" />

    <dependencies defaultconf="default">
        <dependency name="el-api" org="javax.el" rev="2.2" />
        <dependency name="jboss-el" org="org.jboss.el" rev="2.0.1.GA" />
        <dependency name="jsf-api" org="com.sun.faces" rev="2.1.21" />
        <dependency name="jsf-impl" org="com.sun.faces" rev="2.1.21" />
        <dependency name="liferay-faces-bridge-api" org="com.liferay.faces"    rev="3.2.4-ga5" />
        <dependency name="liferay-faces-bridge-impl" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="liferay-faces-portal" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="liferay-faces-util" org="com.liferay.faces" rev="3.2.4-ga5" />
        <dependency name="primefaces" org="org.primefaces" rev="3.5" />
    </dependencies>
    </ivy-module>

The error while building the application :

BUILD FAILED
  E:\Liferay_Project_Edistrict\liferay-plugins-sdk-6.2\build-common-ivy.xml:81: java.net.ConnectException: Connection refused: connect

Body:
I just answered a question similar to this and while your post is also short on details you might be experiencing a common issue in some 6.2 minor releases.  Find your build.USERNAME.properties file and add the following lines, then try to build again

ivy.version = 2.3.0
ivy.jar.url = http://repo1.maven.org/maven2/org/apache/ivy/ivy/${ivy.version}/ivy-${ivy.version}.jar


问:
django admin "Key 'category' not found in 'SpecificationParameterForm'. Choices are: help_text, name, units, value_type."
When I view the change list in the admin interface I can see the 'name', 'category', 'value_type', 'help_text' fields, proving that the category field is fine. But when I click on a Parameter to get to the change form I get the above error.

Here's my admin:

```<code>@admin.register(SpecificationParameter)
class SpecificationParameterAdmin(SortableAdminMixin, admin.ModelAdmin):
    """
    For administering Specification Parameters
    """
    # Fields shown in lists
    list_display = ('name', 'category', 'value_type', 'help_text')
    list_per_page = 20
    # related field needs __ due to foreign key
    search_fields = ['name', 'category__name']
    # Change 'Save and add another' to 'Save as new' to easily create similar entries
    save_as = True
    # django 1.10 will default to staying on the page after creating a new one; redirects in 1.9 :(
    # for this purpose, show the id
    readonly_fields = ('id',)
    # Modify the layout of the form, put the optional choices last
    fieldsets = (
        (None,      {'fields': (('name', 'id'), 'category', 'units', 'help_text')}),
        (_('Type'), {'fields': ('value_type',)}),
    )
    inlines = [SpecificationValueChoiceAdminInline]

    def get_inline_instances(self, request, obj=None):
        """
        Override to dynamically display choices if multiple choice or checkbox
        """
        instances = []
        for inline in self.inlines:
            if inline == SpecificationValueChoiceAdminInline:
                if obj and obj.value_type in (tup[0] for tup in SpecificationParameter.VALUE_TYPES[1][1]):
                    # for changes and not adds
                    instances += [inline(self.model, self.admin_site)]
            else:
                instances += [inline(self.model, self.admin_site)]
        return instances
</code>```

And a relevant model snippet:

```<code>class SpecificationParameter(models.Model):
    """
    The fields required by parameters in the specification of a product.
    """
    # _() Provides the name as a translation
    name = models.CharField(_("specification parameter name (public)"), unique=True, max_length=50,
        help_text=_("Be as specific as you can, for example: Minimum DC Voltage"))
    # All parameters in a category need to be removed manually before it will allow you to delete the cetegory
    category = models.ForeignKey(SpecificationCategory, verbose_name=_("parameter category"), on_delete=models.PROTECT,
        help_text=_("Add a new or select an existing parameter section"))
    help_text = models.CharField(_("help text"), max_length=160, help_text=_("Specify any additional information useful to the staff entering values"), blank=True)
    ....
</code>```

Traceback

Could it be because it's a ForeignKey?
Any ideas much appreciated.

EDIT:

Removing fieldsets removes the error, but the default fields do not include category.

I have tried with django 1.10.7 and 1.9.9 with no difference, so removed comment above. Must be a change I made :-/ I have confirmed category does not appear in form.base_fields

答:
This was caused by SortableAdminMixin since category is in the model Meta ordering attribute which is used by this mixin.

I had accidentally overwritten a modified branch when I performed a pip install -U.

Body:
When I view the change list in the admin interface I can see the 'name', 'category', 'value_type', 'help_text' fields, proving that the category field is fine. But when I click on a Parameter to get to the change form I get the above error.

Here's my admin:

@admin.register(SpecificationParameter)
class SpecificationParameterAdmin(SortableAdminMixin, admin.ModelAdmin):
    """
    For administering Specification Parameters
    """
    # Fields shown in lists
    list_display = ('name', 'category', 'value_type', 'help_text')
    list_per_page = 20
    # related field needs __ due to foreign key
    search_fields = ['name', 'category__name']
    # Change 'Save and add another' to 'Save as new' to easily create similar entries
    save_as = True
    # django 1.10 will default to staying on the page after creating a new one; redirects in 1.9 :(
    # for this purpose, show the id
    readonly_fields = ('id',)
    # Modify the layout of the form, put the optional choices last
    fieldsets = (
        (None,      {'fields': (('name', 'id'), 'category', 'units', 'help_text')}),
        (_('Type'), {'fields': ('value_type',)}),
    )
    inlines = [SpecificationValueChoiceAdminInline]

    def get_inline_instances(self, request, obj=None):
        """
        Override to dynamically display choices if multiple choice or checkbox
        """
        instances = []
        for inline in self.inlines:
            if inline == SpecificationValueChoiceAdminInline:
                if obj and obj.value_type in (tup[0] for tup in SpecificationParameter.VALUE_TYPES[1][1]):
                    # for changes and not adds
                    instances += [inline(self.model, self.admin_site)]
            else:
                instances += [inline(self.model, self.admin_site)]
        return instances

And a relevant model snippet:

class SpecificationParameter(models.Model):
    """
    The fields required by parameters in the specification of a product.
    """
    # _() Provides the name as a translation
    name = models.CharField(_("specification parameter name (public)"), unique=True, max_length=50,
        help_text=_("Be as specific as you can, for example: Minimum DC Voltage"))
    # All parameters in a category need to be removed manually before it will allow you to delete the cetegory
    category = models.ForeignKey(SpecificationCategory, verbose_name=_("parameter category"), on_delete=models.PROTECT,
        help_text=_("Add a new or select an existing parameter section"))
    help_text = models.CharField(_("help text"), max_length=160, help_text=_("Specify any additional information useful to the staff entering values"), blank=True)
    ....

Traceback

Could it be because it's a ForeignKey?
Any ideas much appreciated.

EDIT:

Removing fieldsets removes the error, but the default fields do not include category.

I have tried with django 1.10.7 and 1.9.9 with no difference, so removed comment above. Must be a change I made :-/ I have confirmed category does not appear in form.base_fields


问:
How can modify request.data in django REST framework
I am using Django REST Framework

```<code>request.data = '{"id": "10", "user": "tom"}'
</code>```

I want to add extra attribute like "age": "30" before sending it to further like

```<code>    request.data = new_data
    response = super().post(request, *args, **kwargs)
</code>```

I have two issues

Why request.data is coming as string rather than dict

How can i update the request.data

答:
If your endpoint is implemented with a DRF (Django REST Framework) ViewSet the solution can be to implement the corresponding serializer class's to_internal_value method and modify the data there.

```<code>class MyModelViewSet(viewsets.ModelViewSet):
    authentication_classes = ...
    ...
    serializer_class = MyModelSerializer

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'user', ...)

    def to_internal_value(self, data):
        instance = super(MyModelSerializer, self).to_internal_value(data)
        if "lastModified" in data:
            # instance["id"] = 10  # That's sketchy though
            instance["user"] = "tom"
        return instance
</code>```

Body:
I am using Django REST Framework

request.data = '{"id": "10", "user": "tom"}'

I want to add extra attribute like "age": "30" before sending it to further like

    request.data = new_data
    response = super().post(request, *args, **kwargs)

I have two issues

Why request.data is coming as string rather than dict

How can i update the request.data

Body:
If your endpoint is implemented with a DRF (Django REST Framework) ViewSet the solution can be to implement the corresponding serializer class's to_internal_value method and modify the data there.

class MyModelViewSet(viewsets.ModelViewSet):
    authentication_classes = ...
    ...
    serializer_class = MyModelSerializer

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'user', ...)

    def to_internal_value(self, data):
        instance = super(MyModelSerializer, self).to_internal_value(data)
        if "lastModified" in data:
            # instance["id"] = 10  # That's sketchy though
            instance["user"] = "tom"
        return instance


问:
Powershell create file on file server and open on desktop
I want to be able to create a file on a file server and then open this file on my PC right after the file creation. I have the following script (edited to hide confident info.)

```<code>Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path E:\foo\bar\'test test'\ $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName
</code>```

This script creates the file on the file server successfully, but does not open the file anywhere. Ive tried removing the if statement and that didn't seem to be the problem.
Can anyone help me?

答:
Running what you have and assuming you actually have single quotes in the folder name, it fails because it's converting the single quotes in 'test test' to nothing. So if you add quotes around the whole path it will work</p>

```<code>Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path "E:\foo\bar\'test test'\" $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName
</code>```

Body:
I want to be able to create a file on a file server and then open this file on my PC right after the file creation. I have the following script (edited to hide confident info.)

Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path E:\foo\bar\'test test'\ $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName

This script creates the file on the file server successfully, but does not open the file anywhere. Ive tried removing the if statement and that didn't seem to be the problem.
Can anyone help me?

Body:
Running what you have and assuming you actually have single quotes in the folder name, it fails because it's converting the single quotes in 'test test' to nothing. So if you add quotes around the whole path it will work

Invoke-Command -ComputerName FileServerComputer -ScriptBlock {
$NewFile = "test.docx"
$path = Join-Path "E:\foo\bar\'test test'\" $NewFile
New-Item $path -type file
if (Test-Path $path) {Invoke-Item $path}
} -Credential userName


问:
Nodejs get request
I use the js to render the following line of code in html

```<code><p class=""><h4><a href="/users/user_profile?userp=' + this._creator._id +">+
 this._creator.username + '</a>
</code>```

Then in node.js the following get request method

```<code>router.get('/user_profile',function (req,res) {
user_id = req.query.userp;
User.getUserById(user_id,function (err,user) {
if(err) throw err;
  res.render('user_profile',{
    user : user
  })
</code>```

});
});
The code render to the selected user page but how can i just use one page for login user and selected user.

答:
You design a URL scheme that specifies a specific user's profile in a unique URL such as:

```<code> http://somedomain.com/user/jackp/profile
</code>```

And, then you create a handle for that specific URL layout in node.js.  One would usually use a framework such as Express to help you parse URLs so that you can create a single handler for http://somedomain.com/user and automatically parse the other two pieces of the above URL to give you the user name and the profile in the route handler.  But, if you aren't using such a framework, you can still make it work, you just have to do your URL parsing and matching.

There are many different possible URL schemes, for example, you could also use query parameters such as:

```<code>http://somedomain.com/profile?user=jackp
</code>```

Title: Nodejs get request

Body:
I use the js to render the following line of code in html

+
 this._creator.username + '

Then in node.js the following get request method

router.get('/user_profile',function (req,res) {
user_id = req.query.userp;
User.getUserById(user_id,function (err,user) {
if(err) throw err;
  res.render('user_profile',{
    user : user
  })

});
});
The code render to the selected user page but how can i just use one page for login user and selected user.

Body:
You design a URL scheme that specifies a specific user's profile in a unique URL such as:

 http://somedomain.com/user/jackp/profile

And, then you create a handle for that specific URL layout in node.js.  One would usually use a framework such as Express to help you parse URLs so that you can create a single handler for http://somedomain.com/user and automatically parse the other two pieces of the above URL to give you the user name and the profile in the route handler.  But, if you aren't using such a framework, you can still make it work, you just have to do your URL parsing and matching.

There are many different possible URL schemes, for example, you could also use query parameters such as:

http://somedomain.com/profile?user=jackp


问:
How to use @mixin inside sass file when loading files with webpack 2?
I cannot get my compiled css to use any of the @mixins that are inside my scss. There is no error in the console during compile so I am not even sure where to start investigating.

My setup is as follows:

main.scss:

```<code>@charset 'UTF-8';

@import 'base/mixins';
@import 'components/button';
</code>```

button.scss

```<code>#button {
  color: yellow;
  @mixin desktop-up {
    padding-top: 10px;
  }
}
</code>```

_mixins.scss

```<code>$desktop-width: 992px;

@mixin desktop-up {
  @media (min-width: #{$desktop-width + 1}) {
    @content;
  }
}
</code>```

And my webpack 2 config looks like this (the relevant parts):

```<code>module.exports = {
  context: path.join(__dirname, ''),
  devtool: debug ? 'cheap-module-eval-source-map' : 'source-map',
  entry: ['./js/app.ts', './sass/main.scss'],
  module: {
    rules: [
      // ...
      {
        test: /\.css$/,
        use: [
         'style-loader',
         {
           loader: "css-loader",
           options: {
             modules: true,
             importLoaders: 1
           }
         }
        ]
      },
      {
          test: /\.scss$/,
          exclude: /node_modules/,
          use: [
            'style-loader',
            {loader: 'css-loader',
              options: {
                importLoaders: 1
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                plugins: function () {
                  return [
                    require('postcss-smart-import'),
                    require('precss'),
                    require('autoprefixer')
                  ];
                }
              }
            },
            {
              loader: 'sass-loader',
              options: {
                includePaths: [path.resolve(__dirname, "./sass")]
              }
            }
          ]
      }
      // ....
    ]
  },
// .......
</code>```

The weird thing is that inside my button.scss file I have access to the $desktop-width variable, but the @mixin does nothing. It's never applied that I can see and it throws no error.

答:
The problem is not your configuration. You are using the mixins in a wrong way:
 @mixin is for defining the mixin. You have to use @include desktop-up;in your buttons.scss.

Look here:
http://sass-lang.com/guide#topic-6

Body:
I cannot get my compiled css to use any of the @mixins that are inside my scss. There is no error in the console during compile so I am not even sure where to start investigating.

My setup is as follows:

main.scss:

@charset 'UTF-8';

@import 'base/mixins';
@import 'components/button';

button.scss

#button {
  color: yellow;
  @mixin desktop-up {
    padding-top: 10px;
  }
}

_mixins.scss

$desktop-width: 992px;

@mixin desktop-up {
  @media (min-width: #{$desktop-width + 1}) {
    @content;
  }
}

And my webpack 2 config looks like this (the relevant parts):

module.exports = {
  context: path.join(__dirname, ''),
  devtool: debug ? 'cheap-module-eval-source-map' : 'source-map',
  entry: ['./js/app.ts', './sass/main.scss'],
  module: {
    rules: [
      // ...
      {
        test: /\.css$/,
        use: [
         'style-loader',
         {
           loader: "css-loader",
           options: {
             modules: true,
             importLoaders: 1
           }
         }
        ]
      },
      {
          test: /\.scss$/,
          exclude: /node_modules/,
          use: [
            'style-loader',
            {loader: 'css-loader',
              options: {
                importLoaders: 1
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                plugins: function () {
                  return [
                    require('postcss-smart-import'),
                    require('precss'),
                    require('autoprefixer')
                  ];
                }
              }
            },
            {
              loader: 'sass-loader',
              options: {
                includePaths: [path.resolve(__dirname, "./sass")]
              }
            }
          ]
      }
      // ....
    ]
  },
// .......

The weird thing is that inside my button.scss file I have access to the $desktop-width variable, but the @mixin does nothing. It's never applied that I can see and it throws no error.


问:
Excel - Rather complex SUM IF criteria
I have roughly the following setup:

Values:

```<code>MONTH | DURATION | VALUE |
  5   |     3    |  120  |
  6   |     1    |  100  |
</code>```

Expected outcome for totals:

```<code>MONTH | TOTAL
  5   |  120
  6   |  220
  7   |  120
</code>```

What I would like to do, is to be able to sum in another table the total values for each month. The logic would be to SUM every value where the total table's month is equal or higher than that of the values, but lower than the value's month + duration.

Does that make any sense? Is that possible? I'm cracking my head and I can't seem to find a way to solve it.

Thank you very much.

答: DSUM is the best candidate for this, I believe.  See Microsft's documentation and this site for help understanding function, and what it is doing.  I have made very complex calculations possible in Excel by using the "database" methods (DSUM, DCOUNT, etc).

Title: Excel - Rather complex SUM IF criteria

Body:
I have roughly the following setup:

Values:

MONTH | DURATION | VALUE |
  5   |     3    |  120  |
  6   |     1    |  100  |

Expected outcome for totals:

MONTH | TOTAL
  5   |  120
  6   |  220
  7   |  120

What I would like to do, is to be able to sum in another table the total values for each month. The logic would be to SUM every value where the total table's month is equal or higher than that of the values, but lower than the value's month + duration.

Does that make any sense? Is that possible? I'm cracking my head and I can't seem to find a way to solve it.

Thank you very much.


问:
Use parLapply in parallel in a loop R
I ran parLapply in a parallel in a loop in R, but I got an error:

```<code>library(doSNOW)
library(foreach)
cl<-makeCluster(4) #change the 2 to your number of CPU cores
registerDoSNOW(cl)
foreach(1:2) %dopar% {
    clusterExport(cl, "parLapply")
    parLapply(cl, 1:2,function(exponent)2^exponent)
}
</code>```

when launching this code, I got the following error:

```<code>> Error in { : task 1 failed - "object 'c1' not found"
</code>```

Could anyone help me to explain why? Is it possible to use parLapply in parallel in a loop?

Thanks a lot!

答:
Cluster objects can't be exported because they can't be safely serialized and sent to the workers since they contain socketConnection objects. Instead, you should create them on each of the workers as part of the worker initialization. Cluster creation can take significant time, so it can be important to create only one cluster object per worker regardless of the number of iterations in your foreach loop.

Here's an example that uses the clusterEvalQ function to initialize and clean up the workers so you can execute parLapply inside a foreach loop:

```<code>library(doSNOW)

# Start cluster on master and register it for use with doSNOW
cl <- makeCluster(4)
registerDoSNOW(cl)

# Start cluster on workers
clusterEvalQ(cl, {
  library(parallel)
  cl <- makeCluster(2)
})

# Execute nested parallel loop
r <-
  foreach(1:2, .noexport='cl', .packages='parallel') %dopar% {
      parLapply(cl, 1:2, function(exponent)2^exponent)
  }

# Stop clusters on workers
clusterEvalQ(cl, {
  stopCluster(cl)
})

# Stop cluster on master
stopCluster(cl)
</code>```

Title: Use parLapply in parallel in a loop R

Body:
I ran parLapply in a parallel in a loop in R, but I got an error:

library(doSNOW)
library(foreach)
cl<-makeCluster(4) #change the 2 to your number of CPU cores
registerDoSNOW(cl)
foreach(1:2) %dopar% {
    clusterExport(cl, "parLapply")
    parLapply(cl, 1:2,function(exponent)2^exponent)
}

when launching this code, I got the following error:

> Error in { : task 1 failed - "object 'c1' not found"

Could anyone help me to explain why? Is it possible to use parLapply in parallel in a loop?

Thanks a lot!

Body:
Cluster objects can't be exported because they can't be safely serialized and sent to the workers since they contain socketConnection objects. Instead, you should create them on each of the workers as part of the worker initialization. Cluster creation can take significant time, so it can be important to create only one cluster object per worker regardless of the number of iterations in your foreach loop.

Here's an example that uses the clusterEvalQ function to initialize and clean up the workers so you can execute parLapply inside a foreach loop:

library(doSNOW)

# Start cluster on master and register it for use with doSNOW
cl <- makeCluster(4)
registerDoSNOW(cl)

# Start cluster on workers
clusterEvalQ(cl, {
  library(parallel)
  cl <- makeCluster(2)
})

# Execute nested parallel loop
r <-
  foreach(1:2, .noexport='cl', .packages='parallel') %dopar% {
      parLapply(cl, 1:2, function(exponent)2^exponent)
  }

# Stop clusters on workers
clusterEvalQ(cl, {
  stopCluster(cl)
})

# Stop cluster on master
stopCluster(cl)


问:
SQL Server Update Queries Taking Too Long
I have a SQL query that builds analysis tables using SELECT INTO statements from populated staging tables. This part goes pretty smooth, but when I try to append fields to the analysis tables, from each other or from the original staging tables, the UPDATE queries run for HOURS.

I feel this run time is unwarranted because the most records per table is 200K. I have a feeling that this is an issue with my log file management or the fact that I have no indexes on any of these tables. I have been reluctant to build indexes because I know if hastily done, they can actually cause more problems. There are no triggers on any of these tables.

I am trying to find an approach so that this query runs consistently. In the past, it has run under 1 hour (which is still probably too long) but today for instance it has taken 3+ hours.

I've already modified the log file to autogrow by 50% rather than 10%, to have an unlimited MAXSIZE, I've set the DB recovery mode to SIMPLE and I have shrunk the log file manually. None of this is helping.

I know that TABLE SCANS are a source of lag in large queries, so is the solution here to create indexes for all of the fields I use in my LEFT JOINs depicted below? These snippets are exact examples of where the query is lagging. I have transparency into this because I am following the execution of the script in the LIVE QUERY STATISTICS window.

```<code>UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;

-- Link by website2
UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.url2 = b.Website2
WHERE a.[Account ID] IS NULL;
--
UPDATE a
SET a.[SFDC Account Name] = b.[Account Name]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on
a.[Account ID] = b.[Account ID]
WHERE a.[Account ID] IS NOT NULL;

UPDATE a
SET a.ConvertedFlag = b.[Lead ID]
FROM SFAX.dbo.WhoAnalysis1 as a
LEFT JOIN SFAX.dbo.Contacts as b ON a.WhoId = b.[Contact ID];
</code>```

答:
Note: In the comments above you express doubt. This is easy to test -- break your script in half prior to updates -- run part one -- then run one update and time it. Then make indexes for that one update. Run it again. How many orders of magnitude faster is it?

Don't be scared of indexes if you work with SQL -- love your indexes. Create indexes for

```<code>SFAX.dbo.Leads.[Company   Account], [Account ID]
SFAX.dbo.Accts.[Account Name]

SFAX.dbo.Leads.url2, [Account ID]
SFAX.dbo.Accts.Website2

SFAX.dbo.Leads.[Account ID]
SFAX.dbo.Accts.[Account ID]

SFAX.dbo.WhoAnalysis1.WhoID
SFAX.dbo.Contacts.[Contact ID]
</code>```

But remember -- if you are changing a lot of records in your database this could be constrained by the speed of your I/O

Body:
I have a SQL query that builds analysis tables using SELECT INTO statements from populated staging tables. This part goes pretty smooth, but when I try to append fields to the analysis tables, from each other or from the original staging tables, the UPDATE queries run for HOURS.

I feel this run time is unwarranted because the most records per table is 200K. I have a feeling that this is an issue with my log file management or the fact that I have no indexes on any of these tables. I have been reluctant to build indexes because I know if hastily done, they can actually cause more problems. There are no triggers on any of these tables.

I am trying to find an approach so that this query runs consistently. In the past, it has run under 1 hour (which is still probably too long) but today for instance it has taken 3+ hours.

I've already modified the log file to autogrow by 50% rather than 10%, to have an unlimited MAXSIZE, I've set the DB recovery mode to SIMPLE and I have shrunk the log file manually. None of this is helping.

I know that TABLE SCANS are a source of lag in large queries, so is the solution here to create indexes for all of the fields I use in my LEFT JOINs depicted below? These snippets are exact examples of where the query is lagging. I have transparency into this because I am following the execution of the script in the LIVE QUERY STATISTICS window.

UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.[Company   Account] = b.[Account Name]
WHERE a.[Account ID] IS NULL;

-- Link by website2
UPDATE a
SET a.[Account ID] = b.[Account ID]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on a.url2 = b.Website2
WHERE a.[Account ID] IS NULL;
--
UPDATE a
SET a.[SFDC Account Name] = b.[Account Name]
FROM SFAX.dbo.Leads as a
left join SFAX.dbo.Accts as b on
a.[Account ID] = b.[Account ID]
WHERE a.[Account ID] IS NOT NULL;

UPDATE a
SET a.ConvertedFlag = b.[Lead ID]
FROM SFAX.dbo.WhoAnalysis1 as a
LEFT JOIN SFAX.dbo.Contacts as b ON a.WhoId = b.[Contact ID];

Body:
Note: In the comments above you express doubt. This is easy to test -- break your script in half prior to updates -- run part one -- then run one update and time it. Then make indexes for that one update. Run it again. How many orders of magnitude faster is it?

Don't be scared of indexes if you work with SQL -- love your indexes. Create indexes for

SFAX.dbo.Leads.[Company   Account], [Account ID]
SFAX.dbo.Accts.[Account Name]

SFAX.dbo.Leads.url2, [Account ID]
SFAX.dbo.Accts.Website2

SFAX.dbo.Leads.[Account ID]
SFAX.dbo.Accts.[Account ID]

SFAX.dbo.WhoAnalysis1.WhoID
SFAX.dbo.Contacts.[Contact ID]

But remember -- if you are changing a lot of records in your database this could be constrained by the speed of your I/O


问:
How to implement tuple unpacking for function parameters in Java?
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

```<code>package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}
</code>```

答:
I can't really tell if this is too "dirty" or not, but why not provide getters for T1 and T2 inside Tuple2 and do:

```<code>.map(x -> tuple(x, x + 1)) // map long to tuple2
.map(a -> a.getT1() + a.getT2()) // map tuple2 to long
</code>```

Body:
I have created some tuple classes, and put them into Java collection. But I don't want to use tuple as function parameters directly when iterating collection.So I implemented tuple unpacking as the following code.

Basically it works, but the problem is that a type casting is needed:

map((Func2<Long, Long, Long>) (a, b) -> a + b)

Is there any way to remove the type casting here?

edit:

Maybe I didn't make it clear, not only tuple2, but also tuple3, tuple4... should be supported. @Flown's answer works greatly for Tuple2, but doesn't work for tuple2, tuple3, tuple4 in the meantime

package test;

import com.google.common.collect.Iterables;

import java.util.Arrays;
import java.util.function.Function;

import static test.TupleIterable.Tuple.tuple;

public interface TupleIterable<T> {

    Iterable<T> apply();

    static <E> TupleIterable<E> from(Iterable<E> iterable) {
        return () -> iterable;
    }

    default <E> TupleIterable<E> map(Function<? super T, ? extends E> op) {
        return () -> Iterables.transform(TupleIterable.this.apply(), op::apply);
    }

    interface Func2<T1, T2, R> extends Function<Tuple.Tuple2<T1, T2>, R> {

        R apply(T1 t1, T2 t2);

        @Override
        default R apply(Tuple.Tuple2<T1, T2> t) {
            return apply(t.t1, t.t2);
        }
    }

    interface Func3<T1, T2, T3, R> extends Function<Tuple.Tuple3<T1, T2, T3>, R> {

        R apply(T1 t1, T2 t2, T3 t3);

        @Override
        default R apply(Tuple.Tuple3<T1, T2, T3> t) {
            return apply(t.t1, t.t2, t.t3);
        }
    }

    interface Tuple {

        static <T1, T2> Tuple2<T1, T2> tuple(T1 t1, T2 t2) {
            return new Tuple2<>(t1, t2);
        }

        static <T1, T2, T3> Tuple3<T1, T2, T3> tuple(T1 t1, T2 t2, T3 t3) {
            return new Tuple3<>(t1, t2, t3);
        }

        class Tuple2<T1, T2> implements Tuple {

            public T1 t1;

            public T2 t2;

            public Tuple2(T1 t1, T2 t2) {
                this.t1 = t1;
                this.t2 = t2;
            }
        }

        class Tuple3<T1, T2, T3> implements Tuple {

            public T1 t1;

            public T2 t2;

            public T3 t3;

            public Tuple3(T1 t1, T2 t2, T3 t3) {
                this.t1 = t1;
                this.t2 = t2;
                this.t3 = t3;
            }
        }
    }

    public static void main(String[] args) {
        TupleIterable.from(Arrays.asList(1L, 2L))
                .map(x -> tuple(x, x)) // map long to tuple2
                .map((Func2<Long, Long, Tuple.Tuple3<Long, Long, Long>>) (a, b) -> tuple(a, b, a + b)) // map tuple2 to tuple3
                .map((Func3<Long, Long, Long, Long>) (a, b, c) -> a + b + c) // map tuple3 to Long
                .apply()
                .forEach(System.out::println);
    }
}

Body:
I can't really tell if this is too "dirty" or not, but why not provide getters for T1 and T2 inside Tuple2 and do:

.map(x -> tuple(x, x + 1)) // map long to tuple2
.map(a -> a.getT1() + a.getT2()) // map tuple2 to long


问:
How to check if not available methods are used if deployment target < base sdk?
I would like to know how you check that your code do not call not available methods when the deployment target is inferior to base SDK ?

It is possible to run the application on a device with the SDK equal to deployment target, but I search a way more 'automatic'. Any idea ?

Regards,
Quentin

答:
use NSClassFromString();

```<code>Class cls = NSClassFromString(@"YourClass");
if (cls == nil)
</code>```

is this you are looking for?

Body:
use NSClassFromString();

Class cls = NSClassFromString(@"YourClass");
if (cls == nil)

is this you are looking for?