问:
node.js share dynamic variables between modules
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

```<code>process.env.number_of_clusters = 1;
</code>```

is it a good practice?

答:
Try reading/writing in a file?</p>

```<code>var fs = require('fs');
fs.writeFile("/path/to/file", "whatever", function(err) {
    console.log("The file was saved!");
});
fs.readFile('/path/to/file', 'utf8', function(err, contents) {
    console.log(contents); // -> whatever
});
</code>```

Body:
I have a variable named number_of_clusters which must be updated periodically. number_of_clusters must also be shared with other modules to read it. how can I assure that reading modules will read a fresh copy of this variable each time they access that?
I dont want to use database to share this variable so I thought I could share it via process.env

process.env.number_of_clusters = 1;

is it a good practice?

Body:
Try reading/writing in a file?

var fs = require('fs');
fs.writeFile("/path/to/file", "whatever", function(err) {
    console.log("The file was saved!");
});
fs.readFile('/path/to/file', 'utf8', function(err, contents) {
    console.log(contents); // -> whatever
});


来源: stackexchange

问:
Vanilla JS .style working but jQuery .css is not?
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated. </p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="css/index.css" type="text/css">
</head>
<body>

  <div id="header">

    <div id="navimg-holder">
        <img src="images/navimg.jpg" alt="">
    </div>

    <div id="navlist">

        <div class="navelm">
            <a href=""> <p> Home </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Contant </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Experience </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Interests </p> </a>
        </div>

    </div>

    <div id="logo-holder">

    </div>
    <div id="socialmedia-div">

        <div class="socialmedia-holder">
            <a href="https://facebook.com"> <img src="images/social1.jpg" alt="" > </a>
        </div>

        <div class="socialmedia-holder" id="second-socialmedia">
            <a href="https://twitter.com"> <img src="images/social2.jpg" alt="" id="twitter"> </a>
        </div>

        <div class="socialmedia-holder" id="third-socialmedia">
            <a href="https://www.instagram.com"> <img src="images/social3.jpg" alt="" id="insta"> </a>
        </div>

    </div>

  </div>

  <div id="content1">

  </div>

<script src="js/jquery-3.2.1.js"></script>
<script src="js/index.js"></script>
<script>document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script>
</body>
</html>

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}
</code>```

答:
You don't even need an each , can simply do:

```<code>function showMenu(){
    $('.navelm').css("background-color","white");
}
</code>```

jQuery will internally loop over all matching elements and apply the style to all

ContentLicense: CC BY-SA 3.0

Body:
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated.

<!DOCTYPE html>

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

 Home

 Contant

 Experience

 Interests

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}

Body:
You don't even need an each , can simply do:

function showMenu(){
    $('.navelm').css("background-color","white");
}

jQuery will internally loop over all matching elements and apply the style to all


问:
:hover effect on p:after in specific div
I cant seem to properly activate the :hover state for p elements inside a parent div

For all p elements in the parent div there is an :after with 0 width to create an underlining when hovered. I want the width to go from "0" to "2em" when the p is hovered.

I'm not sure how to properly target the p and the :after when hovered.

I though it should look something like below.

HTML

```<code><div class="parent">
    <p>Menu Option A</p>
    <p>Menu Option B</p>
</div>
</code>```

CSS

```<code>.top_menu_wrapper p:after {
  content: "";
  display: block;
  height: 3px;
  width: 0em;
  background: white;
  margin: auto;
  transition: all 0.4s ease;
}
.parent p:hover p:after {
  width: 2em;
}
</code>```

答:
Combine :after with :hover
this would work:</p>

```<code>.parent p:hover:after {
    width: 2em;
}
</code>```

Body:
I cant seem to properly activate the :hover state for p elements inside a parent div

For all p elements in the parent div there is an :after with 0 width to create an underlining when hovered. I want the width to go from "0" to "2em" when the p is hovered.

I'm not sure how to properly target the p and the :after when hovered.

I though it should look something like below.

HTML

Menu Option A

Menu Option B

CSS

.top_menu_wrapper p:after {
  content: "";
  display: block;
  height: 3px;
  width: 0em;
  background: white;
  margin: auto;
  transition: all 0.4s ease;
}
.parent p:hover p:after {
  width: 2em;
}

Body:
Combine :after with :hover
this would work:

.parent p:hover:after {
    width: 2em;
}


问:
books to recommend to study WPF

Possible Duplicate:

  What WPF books would you recommend?

Is there any good book to recommend for learning WPF?

答: I would highly recommend Matthew A. Stoecker's MCTS Self-Paced Training Kit (Exam 70-502): Microsoft® .NET Framework 3.5—Windows® Presentation Foundation (search for 70-502 on O Reilly) and the WPF courses from Pluralsight. The labs in the 1st reference are well-designed and I had no problems that it is based on .NET FW 3.5.</p>

ContentLicense: CC BY-SA 2.5

Title: books to recommend to study WPF


答:
If i understand correctly - it's the same p you hover you want to manipulate.

So. It's the .parent p:hover p:after it's wrong with.

:hover and :after should be appended onto each other

like this:

```<code> .parent p:hover:after {
   width: 2em;
 }
</code>```

Title: :hover effect on p:after in specific div

Body:
If i understand correctly - it's the same p you hover you want to manipulate.

So. It's the .parent p:hover p:after it's wrong with.

:hover and :after should be appended onto each other

like this:

 .parent p:hover:after {
   width: 2em;
 }


问:
Unable to make collaborative editing work using Prosemirror
I am using prosemirror to build a collaborative editor, where multiple people can edit one document. I wrote the following code, based on the example given here - http://prosemirror.net/docs/guides/collab/

Here is the code-

```<code>const { EditorState } = require('prosemirror-state');
const { EditorView } = require('prosemirror-view');
const { DOMParser } = require("prosemirror-model");
const {schema} = require("./schema");
var collab = require("prosemirror-collab");

function Authority(doc) {
  this.doc = doc
  this.steps = []
  this.stepClientIDs = []
  this.onNewSteps = []
}

Authority.prototype.receiveSteps = function(version, steps, clientID) {
  if (version != this.steps.length) return

  var self = this
  // Apply and accumulate new steps
  steps.forEach(function(step) {
    self.doc = step.apply(self.doc).doc
    self.steps.push(step)
    self.stepClientIDs.push(clientID)
  })
  // Signal listeners
  this.onNewSteps.forEach(function(f) { f() })
}

Authority.prototype.stepsSince = function(version) {
  return {
    steps: this.steps.slice(version),
    clientIDs: this.stepClientIDs.slice(version)
  }
}

var auth = new Authority('');
collabEditor(auth)

function collabEditor(authority) {
  var view = new EditorView(document.querySelector("#editor"), {
    state: EditorState.create({schema: schema, plugins: [collab.collab()]}),
    dispatchTransaction: function(transaction) {
      var newState = view.state.apply(transaction)
      view.updateState(newState)
      var sendable = collab.sendableSteps(newState)
      if (sendable)
        authority.receiveSteps(sendable.version, sendable.steps,
                               sendable.clientID)
    }
  })
   authority.onNewSteps.push(function() {
    var newData = authority.stepsSince(collab.getVersion(view.state))
    view.dispatch(
      collab.receiveTransaction(view.state, newData.steps, newData.clientIDs))
  })

  return view
}
</code>```

When i run this code (after installing all the dependencies and setting up a simple server in nodejs) I am basically able to edit a text box but I am not able to open two tabs in chrome and see the collaboration happen. What am i doing wrong?

Will love some feedback.

答: This is the example code for a simple, single-page, no-external-communication setup. As such, no, it won't communicate to other tabs. For that, you'd have to move the authority somewhere else and set up pages to actually communicate with it over HTTP or websockets. (See for example this demo.)</p>

Body:
I am using prosemirror to build a collaborative editor, where multiple people can edit one document. I wrote the following code, based on the example given here - http://prosemirror.net/docs/guides/collab/

Here is the code-

const { EditorState } = require('prosemirror-state');
const { EditorView } = require('prosemirror-view');
const { DOMParser } = require("prosemirror-model");
const {schema} = require("./schema");
var collab = require("prosemirror-collab");

function Authority(doc) {
  this.doc = doc
  this.steps = []
  this.stepClientIDs = []
  this.onNewSteps = []
}

Authority.prototype.receiveSteps = function(version, steps, clientID) {
  if (version != this.steps.length) return

  var self = this
  // Apply and accumulate new steps
  steps.forEach(function(step) {
    self.doc = step.apply(self.doc).doc
    self.steps.push(step)
    self.stepClientIDs.push(clientID)
  })
  // Signal listeners
  this.onNewSteps.forEach(function(f) { f() })
}

Authority.prototype.stepsSince = function(version) {
  return {
    steps: this.steps.slice(version),
    clientIDs: this.stepClientIDs.slice(version)
  }
}

var auth = new Authority('');
collabEditor(auth)

function collabEditor(authority) {
  var view = new EditorView(document.querySelector("#editor"), {
    state: EditorState.create({schema: schema, plugins: [collab.collab()]}),
    dispatchTransaction: function(transaction) {
      var newState = view.state.apply(transaction)
      view.updateState(newState)
      var sendable = collab.sendableSteps(newState)
      if (sendable)
        authority.receiveSteps(sendable.version, sendable.steps,
                               sendable.clientID)
    }
  })
   authority.onNewSteps.push(function() {
    var newData = authority.stepsSince(collab.getVersion(view.state))
    view.dispatch(
      collab.receiveTransaction(view.state, newData.steps, newData.clientIDs))
  })

  return view
}

When i run this code (after installing all the dependencies and setting up a simple server in nodejs) I am basically able to edit a text box but I am not able to open two tabs in chrome and see the collaboration happen. What am i doing wrong?

Will love some feedback.


问:
How to delete a file whose name is given by a character array?
I want to delete a file with variables in the file name. But MATLAB doesn't seem to recognize the file name when using delete. Can anyone help me?

```<code>ratio=1;
a=2;
nameoffile3=['r' num2str(ratio) '_a' num2str(a) '.txt'];
delete nameoffile3
</code>```

答:
To delete a file whose name is given by a character array, use delete with parenthesis () i.e.

```<code>delete(nameoffile3)
</code>```

Body:
I want to delete a file with variables in the file name. But MATLAB doesn't seem to recognize the file name when using delete. Can anyone help me?

ratio=1;
a=2;
nameoffile3=['r' num2str(ratio) '_a' num2str(a) '.txt'];
delete nameoffile3

Body:
To delete a file whose name is given by a character array, use delete with parenthesis () i.e.

delete(nameoffile3)


问:
How to create an attribute that can inspect method parameters and return value?
I want to be able to put an attribute on a method and have that method inspect the method parameters and the return value.  Pseudo code.

```<code>[AttributeUsage(AttributeTargets.Method)]
class MyAttribute: Attribute {
   public void MethodEnter(MethodInfo info) {
      foreach (var param in info.MethodParameters {
        Console.WriteLine(param.ToString());
      }
   }

   public void MethodLeave(MethodInfo info) {
      Console.WriteLine(info.ReturnValue);
   }
}

public class MyClass {
  [MyAttribute]
  public SomeType foo(Order order, List<OrderLine> orderLines) {
     ...
  }
}
</code>```

Is this possible?

Basically, I want to be able to log everything that comes in and leaves the function.  I've done this previously with PostSharp, but it seems like an overkill to use it for logging.

答:
You could create an aspect by making your class derive from ContextBoundObject and your attribute from ContextAttribute. By reading this article I made the following sample that meet your requirements:

First, our Foo class derived from ContextBoundObject, decorated with our custom class attribute:

```<code> [Inpectable]
    internal class Foo : ContextBoundObject
    {
        [InspectableProperty]
        public int DoSomething(int a)
        {
            Console.WriteLine("I am doing something");
            a += 1;
            return a;
        }

        public void IamNotLogged()
        {
            Console.WriteLine("Lol");
        }

        [InspectableProperty]
        public string IamLoggedToo()
        {
            var msg = "Lol too";
            Console.WriteLine(msg);
            return msg;
        }
    }
</code>```

Now the Inspectable attribute

```<code>[AttributeUsage(AttributeTargets.Class)]
    public class Inpectable : ContextAttribute
    {
        public Inpectable() : base("Inspectable")
        {
        }

        public override void GetPropertiesForNewContext(IConstructionCallMessage ccm)
        {
            ccm.ContextProperties.Add(new InspectorProperty());
        }
    }
</code>```

The InspectablePropertyAttribute which will only be used to identify those methods that should be logged:

```<code>[AttributeUsage(AttributeTargets.Method)]
    public class InspectableProperty : Attribute
    {
    }
</code>```

The InspectorProperty, which will capture the context of the instance and intercept the messages passing them to our aspect

```<code>public class InspectorProperty : IContextProperty,
    IContributeObjectSink
{
    public bool IsNewContextOK(Context newCtx) => true;

    public void Freeze(Context newContext)
    {
    }

    public string Name { get; } = "LOL";

    public IMessageSink GetObjectSink(MarshalByRefObject o,IMessageSink next) => new InspectorAspect(next);
}
</code>```

And where the magic works, the implementation of our InspectorAspect:

```<code>internal class InspectorAspect : IMessageSink
    {
        internal InspectorAspect(IMessageSink next)
        {
            NextSink = next;
        }

        public IMessageSink NextSink { get; }

        public IMessage SyncProcessMessage(IMessage msg)
        {
            if (!(msg is IMethodMessage)) return NextSink.SyncProcessMessage(msg);

            var call = (IMethodMessage) msg;
            var type = Type.GetType(call.TypeName);
            if (type == null) return NextSink.SyncProcessMessage(msg);

            var methodInfo = type.GetMethod(call.MethodName);
            if (!Attribute.IsDefined(methodInfo, typeof (InspectableProperty)))
                return NextSink.SyncProcessMessage(msg);
            Console.WriteLine($"Entering method: {call.MethodName}. Args being:");
            foreach (var arg in call.Args)
                Console.WriteLine(arg);
            var returnMethod = NextSink.SyncProcessMessage(msg) as IMethodReturnMessage;

            Console.WriteLine($"Method {call.MethodName} returned: {returnMethod?.ReturnValue}");
            Console.WriteLine();
            return returnMethod;
        }

        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            throw new InvalidOperationException();
        }
    }
</code>```

Inside the SyncProcessMessage theInspectorAspect receives all the messages regarding the context (Foo), so we just filter those that are instances of IMethodMessage and then only those belonging to methods decorated with InspectableProperty attribute.

This may not be a ready-to-production solution, but I think that puts you in the right path to research for more info.

Finally testing:

```<code> private static void Main(string[] args)
        {
            var foo = new Foo();
            foo.DoSomething(1);
            foo.IamNotLogged();
            foo.IamLoggedToo();
            Console.ReadLine();
        }
</code>```

The output:

EDIT>>>

These are the namespaces needed:

using System.Runtime.Remoting.Activation;

using System.Runtime.Remoting.Contexts;

using System.Runtime.Remoting.Messaging;

Body:
I want to be able to put an attribute on a method and have that method inspect the method parameters and the return value.  Pseudo code.

[AttributeUsage(AttributeTargets.Method)]
class MyAttribute: Attribute {
   public void MethodEnter(MethodInfo info) {
      foreach (var param in info.MethodParameters {
        Console.WriteLine(param.ToString());
      }
   }

   public void MethodLeave(MethodInfo info) {
      Console.WriteLine(info.ReturnValue);
   }
}

public class MyClass {
  [MyAttribute]
  public SomeType foo(Order order, List<OrderLine> orderLines) {
     ...
  }
}

Is this possible?

Basically, I want to be able to log everything that comes in and leaves the function.  I've done this previously with PostSharp, but it seems like an overkill to use it for logging.

Body:
You could create an aspect by making your class derive from ContextBoundObject and your attribute from ContextAttribute. By reading this article I made the following sample that meet your requirements:

First, our Foo class derived from ContextBoundObject, decorated with our custom class attribute:

 [Inpectable]
    internal class Foo : ContextBoundObject
    {
        [InspectableProperty]
        public int DoSomething(int a)
        {
            Console.WriteLine("I am doing something");
            a += 1;
            return a;
        }

        public void IamNotLogged()
        {
            Console.WriteLine("Lol");
        }

        [InspectableProperty]
        public string IamLoggedToo()
        {
            var msg = "Lol too";
            Console.WriteLine(msg);
            return msg;
        }
    }

Now the Inspectable attribute

[AttributeUsage(AttributeTargets.Class)]
    public class Inpectable : ContextAttribute
    {
        public Inpectable() : base("Inspectable")
        {
        }

        public override void GetPropertiesForNewContext(IConstructionCallMessage ccm)
        {
            ccm.ContextProperties.Add(new InspectorProperty());
        }
    }

The InspectablePropertyAttribute which will only be used to identify those methods that should be logged:

[AttributeUsage(AttributeTargets.Method)]
    public class InspectableProperty : Attribute
    {
    }

The InspectorProperty, which will capture the context of the instance and intercept the messages passing them to our aspect

public class InspectorProperty : IContextProperty,
    IContributeObjectSink
{
    public bool IsNewContextOK(Context newCtx) => true;

    public void Freeze(Context newContext)
    {
    }

    public string Name { get; } = "LOL";

    public IMessageSink GetObjectSink(MarshalByRefObject o,IMessageSink next) => new InspectorAspect(next);
}

And where the magic works, the implementation of our InspectorAspect:

internal class InspectorAspect : IMessageSink
    {
        internal InspectorAspect(IMessageSink next)
        {
            NextSink = next;
        }

        public IMessageSink NextSink { get; }

        public IMessage SyncProcessMessage(IMessage msg)
        {
            if (!(msg is IMethodMessage)) return NextSink.SyncProcessMessage(msg);

            var call = (IMethodMessage) msg;
            var type = Type.GetType(call.TypeName);
            if (type == null) return NextSink.SyncProcessMessage(msg);

            var methodInfo = type.GetMethod(call.MethodName);
            if (!Attribute.IsDefined(methodInfo, typeof (InspectableProperty)))
                return NextSink.SyncProcessMessage(msg);
            Console.WriteLine($"Entering method: {call.MethodName}. Args being:");
            foreach (var arg in call.Args)
                Console.WriteLine(arg);
            var returnMethod = NextSink.SyncProcessMessage(msg) as IMethodReturnMessage;

            Console.WriteLine($"Method {call.MethodName} returned: {returnMethod?.ReturnValue}");
            Console.WriteLine();
            return returnMethod;
        }

        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            throw new InvalidOperationException();
        }
    }

Inside the SyncProcessMessage theInspectorAspect receives all the messages regarding the context (Foo), so we just filter those that are instances of IMethodMessage and then only those belonging to methods decorated with InspectableProperty attribute.

This may not be a ready-to-production solution, but I think that puts you in the right path to research for more info.

Finally testing:

 private static void Main(string[] args)
        {
            var foo = new Foo();
            foo.DoSomething(1);
            foo.IamNotLogged();
            foo.IamLoggedToo();
            Console.ReadLine();
        }

The output:

EDIT>>>

These are the namespaces needed:

using System.Runtime.Remoting.Activation;

using System.Runtime.Remoting.Contexts;

using System.Runtime.Remoting.Messaging;


问:
Android:-Video player
I made a video player app that will pick a video at runtime to play. After picking a video it gives an error of Can't play video.

```<code>public class MainActivity extends AppCompatActivity {
VideoView videoView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button= (Button) findViewById(R.id.button);
    videoView= (VideoView) findViewById(R.id.videoView);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent galleryIntent=new Intent();
            galleryIntent.setType("video/*");
            galleryIntent.setAction(galleryIntent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,"Select
Video"),9);
}
    });}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==9 && resultCode==RESULT_OK)
    {
        Uri videoUri=data.getData();
        videoView.setVideoURI(videoUri);
        videoView.start();}}}
</code>```

`

答:
1) Try to add OnPreparedListener via calling this setOnPreparedListener, and start playing from onPrepared callback.

2) Replace VideoView and MediaPlayer with ExoPlayer. It is more stable than default player, also based on default android components, so it is lightweight.

Title: Android:-Video player

Body:
I made a video player app that will pick a video at runtime to play. After picking a video it gives an error of Can't play video.

public class MainActivity extends AppCompatActivity {
VideoView videoView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button= (Button) findViewById(R.id.button);
    videoView= (VideoView) findViewById(R.id.videoView);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent galleryIntent=new Intent();
            galleryIntent.setType("video/*");
            galleryIntent.setAction(galleryIntent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,"Select
Video"),9);
}
    });}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==9 && resultCode==RESULT_OK)
    {
        Uri videoUri=data.getData();
        videoView.setVideoURI(videoUri);
        videoView.start();}}}

`


问:
Boto3 - Describe Redshift
I have the following code, but it throws error:

```<code>import boto3
import json
import string

client = boto3.client('redshift', 'us-east-1')
cluster_list = client.describe_clusters()

result = [{"{#REDSHIFT}": row['Clusters'][0]['Endpoint']['Address']} for row in client.describe_clusters()]
result = {"data": result}
json_pre = json.dumps(result)
json_pos = json_pre.translate(None, string.whitespace)
print json_pos
</code>```

But I have the following error:

line 8, in

```<code>result = [{"{#REDSHIFT}": row['Clusters'][0]['Endpoint']['Address']} for row in client.describe_clusters()]
TypeError: string indices must be integers
</code>```

I would like to return the values of ['Clusters'][0]['Endpoint']['Address'] to generate a Json.

答:
The correct code is here:</p>

```<code>import boto3
import json
import string

client = boto3.client('redshift', 'us-east-1')
cluster_list = client.describe_clusters()

result = [{"{#REDSHIFT}": red['Endpoint']['Address']} for red in cluster_list['Clusters']]
result = {"data": result}
json_pre = json.dumps(result)
json_pos = json_pre.translate(None, string.whitespace)
print json_pos
</code>```

ContentLicense: CC BY-SA 4.0

Title: Boto3 - Describe Redshift

Body:
I have the following code, but it throws error:

import boto3
import json
import string

client = boto3.client('redshift', 'us-east-1')
cluster_list = client.describe_clusters()

result = [{"{#REDSHIFT}": row['Clusters'][0]['Endpoint']['Address']} for row in client.describe_clusters()]
result = {"data": result}
json_pre = json.dumps(result)
json_pos = json_pre.translate(None, string.whitespace)
print json_pos

But I have the following error:

line 8, in

result = [{"{#REDSHIFT}": row['Clusters'][0]['Endpoint']['Address']} for row in client.describe_clusters()]
TypeError: string indices must be integers

I would like to return the values of ['Clusters'][0]['Endpoint']['Address'] to generate a Json.

Body:
The correct code is here:

import boto3
import json
import string

client = boto3.client('redshift', 'us-east-1')
cluster_list = client.describe_clusters()

result = [{"{#REDSHIFT}": red['Endpoint']['Address']} for red in cluster_list['Clusters']]
result = {"data": result}
json_pre = json.dumps(result)
json_pos = json_pre.translate(None, string.whitespace)
print json_pos


问:
Verification e-mail not sent
Hey, I have set up the piece of code below to send a verification e-mail to the subscriber. But it doesn't seem to reach them(Testing it on my own) I'm using http://localhost/ to test the site, don't know if that's the problem. Also I'm receiving the message that the verification e-mail has been sent so it should be sent. Here's the code:</p>

```<code>if(mysql_query("insert into users(username,password,email,fname,lname,hash) values('$username','$password','$email','$fname','$lname','$hash')")or die (mysql_error ())){
 echo "Welcome, You have successfully signed up. Please check the verification e-mail sent to you.";
 $to = $email;
   $subject = 'Signup | Verification';
   $message = '

     Thanks for signing up!
      Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.

      ------------------------
      Username: '.$username.'
     Password: '.$password.'
     ------------------------

     Please click this link to activate your account:

     http://www.JMtoday.com/verify.php?email='.$email.'&hash='.$hash.'

   ';

    $headers = 'From:noreply@JMtoday.com' . "\r\n";
    mail($to, $subject, $message, $headers);
 }
</code>```

答: Unless you have a mail server running on localhost too, the mail function won't know where to send the email.

Title: Verification e-mail not sent

Body:
Hey, I have set up the piece of code below to send a verification e-mail to the subscriber. But it doesn't seem to reach them(Testing it on my own) I'm using http://localhost/ to test the site, don't know if that's the problem. Also I'm receiving the message that the verification e-mail has been sent so it should be sent. Here's the code:

if(mysql_query("insert into users(username,password,email,fname,lname,hash) values('$username','$password','$email','$fname','$lname','$hash')")or die (mysql_error ())){
 echo "Welcome, You have successfully signed up. Please check the verification e-mail sent to you.";
 $to = $email;
   $subject = 'Signup | Verification';
   $message = '

     Thanks for signing up!
      Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below.

      ------------------------
      Username: '.$username.'
     Password: '.$password.'
     ------------------------

     Please click this link to activate your account:

     http://www.JMtoday.com/verify.php?email='.$email.'&hash='.$hash.'

   ';

    $headers = 'From:noreply@JMtoday.com' . "\r\n";
    mail($to, $subject, $message, $headers);
 }


问:
Methods defined in class Object are instance and class one at the same time
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

```<code>class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method
</code>```

答:
Perhaps forwarding the method to self is an option?

```<code>require 'forwardable'

class Foo
  extend Forwardable

  def self.boo
    'boo method'
  end

  def_delegator self, :boo
end

Foo.boo
#=> "boo method"

Foo.new.boo
#=> "boo method"
</code>```

Body:
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method

Body:
Perhaps forwarding the method to self is an option?

require 'forwardable'

class Foo
  extend Forwardable

  def self.boo
    'boo method'
  end

  def_delegator self, :boo
end

Foo.boo
#=> "boo method"

Foo.new.boo
#=> "boo method"


问:
R - How pass the environment of a data.table to a function?
I'd like to do this:

for example, i have one data.table as:

```<code>dt <- data.table(a=1:3, b=5:7, c=10:8)
#   a b  c
#1: 1 5 10
#2: 2 6  9
#3: 3 7  8
</code>```

and i want to pass the environment of one row per time to a function, for example:

```<code>f <- function(a,b,c){
    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
</code>```

I know i could use in this case mapply to solve this multivariate function, but in my real need i have a function that manipulate almost 150 variables of a data.table, and i don't want to assign the variable's names one by one. I also tried some .SD manipulatations, but it didn't work either.

I would like something that i pass the number of data.table row, and inside the function they get the objects a, b and c in the data.table environment.

Something similar to this:

```<code>f <- function(row_id){
    # set function parent env as data.table[row_id]
    # and *a = data.table[row_id, a]* and successively to b and c...

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
</code>```

答:
One way would be to adapt the function to take in a given data.table and a row and output your x + y + z:

```<code>f <- function(dataTable,row_id){
    a <- dataTable[row_id,a]
    b <- dataTable[row_id,b]
    c <- dataTable[row_id,c]

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
</code>```

If you input f(dt) it'll give youall of the x+y+z values, or if you give it f(dt,1), it'll return values for the first row only.

EDIT:
Assuming that you're column names are the variable names you want to assign, you could try this:

```<code>f <- function(dataTable,row_id){

    for(i in colnames(dataTable)){
        assign(paste(i,"",sep=""), dataTable[row_id,..i])
    }

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
</code>```

Body:
I'd like to do this:

for example, i have one data.table as:

dt <- data.table(a=1:3, b=5:7, c=10:8)
#   a b  c
#1: 1 5 10
#2: 2 6  9
#3: 3 7  8

and i want to pass the environment of one row per time to a function, for example:

f <- function(a,b,c){
    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}

I know i could use in this case mapply to solve this multivariate function, but in my real need i have a function that manipulate almost 150 variables of a data.table, and i don't want to assign the variable's names one by one. I also tried some .SD manipulatations, but it didn't work either.

I would like something that i pass the number of data.table row, and inside the function they get the objects a, b and c in the data.table environment.

Something similar to this:

f <- function(row_id){
    # set function parent env as data.table[row_id]
    # and *a = data.table[row_id, a]* and successively to b and c...

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}

Body:
One way would be to adapt the function to take in a given data.table and a row and output your x + y + z:

f <- function(dataTable,row_id){
    a <- dataTable[row_id,a]
    b <- dataTable[row_id,b]
    c <- dataTable[row_id,c]

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}

If you input f(dt) it'll give youall of the x+y+z values, or if you give it f(dt,1), it'll return values for the first row only.

EDIT:
Assuming that you're column names are the variable names you want to assign, you could try this:

f <- function(dataTable,row_id){

    for(i in colnames(dataTable)){
        assign(paste(i,"",sep=""), dataTable[row_id,..i])
    }

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}


问:
Automating a histogram for varying excel files
I was writing some code with which I need some help with. The code I have written (posted below) has to do a couple of things, first and foremost it should be able to create a histogram (which it does) from a file which it reads and bin it accordingly. So here is where I need some help, 1) I need to find a way to change the bin width to any arbitrary width I would need (deltaT), without having to hard code it every time, 2) the I need some help being able to run the code for different excel files imported into python and have them exported as different excel files. I believe, I'm not so sure I'm pretty new to coding, that what I'm dealing with is a Dataframe. Code:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter

data = pd.read_excel('/Users/user/Desktop/Data/Book1.xlsx')
counts, bins, patches = plt.hist(data.values, bins=range(0,
int(max(data.values)+5), 5))
df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
plt.title('Data')
plt.xlabel('Neuron')
plt.ylabel('# of Spikes')
plt.show()

writer = pd.ExcelWriter('/Users/user/Desktop/Data/output.xlsx')
df.to_excel(writer,'Sheet2')
writer.save()
</code>```

I tried having another excel file read as in:

```<code>data2 = pd.read_excel('/Users/user/Desktop/Data/Book2.xlsx')
</code>```

and then putting it into the code and having it run, but it only gives out the results for the first excel file (outputs it into another excel file). What am I doing wrong? Please any help would be greatly appreciated.

Update:

So I was able to get it to read the multiple files and run the code on them, now the only thing I still can't figure out is how to get them to export as the different excel files they are (plus the bin width change) with the code applied to them. I changed the code a bit to:

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

for file in os.listdir('/Users/user/Desktop/Data'):
    data = pd.read_excel('/Users/user/Desktop/Data/{0}'.format(file))
    counts, bins, patches = plt.hist(data.values, bins=range(0,
    int(max(data.values)+5), 5))
    df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
    plt.title('Data')
    plt.xlabel('Neuron')
    plt.ylabel('# of Spikes')
    plt.show()

    writer = pd.ExcelWriter('/Users/user/Desktop/Data/ouput.xlsx')
    df.to_excel(writer)
    writer.save()
</code>```

Again any help is greatly appreciated. Thanks in advance.

答:
Only one file is exported because the named output.xlsx Excel file in the loop never changes, so it overwrites with each iteration. Consider below that adds a _bins suffix to the original Excel file.

```<code>datadir = '/Users/user/Desktop/Data/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))

       #...data processing and graph output...

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()
</code>```

Body:
I was writing some code with which I need some help with. The code I have written (posted below) has to do a couple of things, first and foremost it should be able to create a histogram (which it does) from a file which it reads and bin it accordingly. So here is where I need some help, 1) I need to find a way to change the bin width to any arbitrary width I would need (deltaT), without having to hard code it every time, 2) the I need some help being able to run the code for different excel files imported into python and have them exported as different excel files. I believe, I'm not so sure I'm pretty new to coding, that what I'm dealing with is a Dataframe. Code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter

data = pd.read_excel('/Users/user/Desktop/Data/Book1.xlsx')
counts, bins, patches = plt.hist(data.values, bins=range(0,
int(max(data.values)+5), 5))
df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
plt.title('Data')
plt.xlabel('Neuron')
plt.ylabel('# of Spikes')
plt.show()

writer = pd.ExcelWriter('/Users/user/Desktop/Data/output.xlsx')
df.to_excel(writer,'Sheet2')
writer.save()

I tried having another excel file read as in:

data2 = pd.read_excel('/Users/user/Desktop/Data/Book2.xlsx')

and then putting it into the code and having it run, but it only gives out the results for the first excel file (outputs it into another excel file). What am I doing wrong? Please any help would be greatly appreciated.

Update:

So I was able to get it to read the multiple files and run the code on them, now the only thing I still can't figure out is how to get them to export as the different excel files they are (plus the bin width change) with the code applied to them. I changed the code a bit to:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import openpyxl
from pandas import ExcelWriter
import os

for file in os.listdir('/Users/user/Desktop/Data'):
    data = pd.read_excel('/Users/user/Desktop/Data/{0}'.format(file))
    counts, bins, patches = plt.hist(data.values, bins=range(0,
    int(max(data.values)+5), 5))
    df = pd.DataFrame({'bin_leftedge': bins[:-1], 'count': counts})
    plt.title('Data')
    plt.xlabel('Neuron')
    plt.ylabel('# of Spikes')
    plt.show()

    writer = pd.ExcelWriter('/Users/user/Desktop/Data/ouput.xlsx')
    df.to_excel(writer)
    writer.save()

Again any help is greatly appreciated. Thanks in advance.

Body:
Only one file is exported because the named output.xlsx Excel file in the loop never changes, so it overwrites with each iteration. Consider below that adds a _bins suffix to the original Excel file.

datadir = '/Users/user/Desktop/Data/'

for file in os.listdir(datadir):
    if file.endswith('.xlsx'):
       data = pd.read_excel(os.path.join(datadir, file))

       #...data processing and graph output...

       outfile = os.path.join(datadir, file.replace('.xlsx', '_bins.xlsx'))
       writer = pd.ExcelWriter(outfile)
       df.to_excel(writer)
       writer.save()


问:
line chart not working using react-d3-components in create-react-app
I'm new to react and I'm trying to put react-d3-component in the create-react-app boilerplate.

App.js looks like :

```<code>import ReactD3 from 'react-d3-components';
import React from 'react';

var LineChart = ReactD3.LineChart;
var Brush = ReactD3.Brush;
var d3 = ReactD3.d3;

var App = React.createClass({
    getInitialState: function() {
        return {
            data: {label: '', values: [
                {x: new Date(2015, 2, 5), y: 1},
                {x: new Date(2015, 2, 6), y: 2},
                {x: new Date(2015, 2, 7), y: 0},
                {x: new Date(2015, 2, 8), y: 3},
                {x: new Date(2015, 2, 9), y: 2},
                {x: new Date(2015, 2, 10), y: 3},
                {x: new Date(2015, 2, 11), y: 4},
                {x: new Date(2015, 2, 12), y: 4},
                {x: new Date(2015, 2, 13), y: 1},
                {x: new Date(2015, 2, 14), y: 5},
                {x: new Date(2015, 2, 15), y: 0},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 18), y: 4},
                {x: new Date(2015, 2, 19), y: 4},
                {x: new Date(2015, 2, 20), y: 5},
                {x: new Date(2015, 2, 21), y: 5},
                {x: new Date(2015, 2, 22), y: 5},
                {x: new Date(2015, 2, 23), y: 1},
                {x: new Date(2015, 2, 24), y: 0},
                {x: new Date(2015, 2, 25), y: 1},
                {x: new Date(2015, 2, 26), y: 1}
            ]},
            xScale: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70]),
            xScaleBrush: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70])
        };
    },

    render: function() {
        return (
            <div>
                <LineChart
                    data={this.state.data}
                    width={400}
                    height={400}
                    margin={{top: 10, bottom: 50, left: 50, right: 20}}
                    xScale={this.state.xScale}
                    xAxis={{tickValues: this.state.xScale.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                />
                <div className="brush" style={{float: 'none'}}>
                    <Brush
                        width={400}
                        height={50}
                        margin={{top: 0, bottom: 30, left: 50, right: 20}}
                        xScale={this.state.xScaleBrush}
                        extent={[new Date(2015, 2, 10), new Date(2015, 2, 12)]}
                        onChange={this._onChange}
                        xAxis={{tickValues: this.state.xScaleBrush.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                    />
                </div>
            </div>
        );
    },

    _onChange: function(extent) {
        this.setState({xScale: d3.time.scale().domain([extent[0], extent[1]]).range([0, 400 - 70])});
    }
});
export default App;
</code>```

index.js looks like :

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

i have already installed react-d3-components also it's there in package.json ; still I get errors like :

TypeError: Cannot read property 'LineChart' of undefined

Also, where ever there is d3.time.day there it says unresolved function. I also tried importing d3 the other way using :

import * as d3 from 'd3'.

But still I get some different errors.

Please suggest what I'm doing wrong, so that I can set up my initial code to work.

Thanks

答:
You might not be importing d3 properly, which might be causing reactd3 to be imported improperly as well. Try importing d3 like this at the top:</p>

```<code>import d3 from 'd3';
</code>```

Body:
I'm new to react and I'm trying to put react-d3-component in the create-react-app boilerplate.

App.js looks like :

import ReactD3 from 'react-d3-components';
import React from 'react';

var LineChart = ReactD3.LineChart;
var Brush = ReactD3.Brush;
var d3 = ReactD3.d3;

var App = React.createClass({
    getInitialState: function() {
        return {
            data: {label: '', values: [
                {x: new Date(2015, 2, 5), y: 1},
                {x: new Date(2015, 2, 6), y: 2},
                {x: new Date(2015, 2, 7), y: 0},
                {x: new Date(2015, 2, 8), y: 3},
                {x: new Date(2015, 2, 9), y: 2},
                {x: new Date(2015, 2, 10), y: 3},
                {x: new Date(2015, 2, 11), y: 4},
                {x: new Date(2015, 2, 12), y: 4},
                {x: new Date(2015, 2, 13), y: 1},
                {x: new Date(2015, 2, 14), y: 5},
                {x: new Date(2015, 2, 15), y: 0},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 16), y: 1},
                {x: new Date(2015, 2, 18), y: 4},
                {x: new Date(2015, 2, 19), y: 4},
                {x: new Date(2015, 2, 20), y: 5},
                {x: new Date(2015, 2, 21), y: 5},
                {x: new Date(2015, 2, 22), y: 5},
                {x: new Date(2015, 2, 23), y: 1},
                {x: new Date(2015, 2, 24), y: 0},
                {x: new Date(2015, 2, 25), y: 1},
                {x: new Date(2015, 2, 26), y: 1}
            ]},
            xScale: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70]),
            xScaleBrush: d3.time.scale().domain([new Date(2015, 2, 5), new Date(2015, 2, 26)]).range([0, 400 - 70])
        };
    },

    render: function() {
        return (

                <LineChart
                    data={this.state.data}
                    width={400}
                    height={400}
                    margin={{top: 10, bottom: 50, left: 50, right: 20}}
                    xScale={this.state.xScale}
                    xAxis={{tickValues: this.state.xScale.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                />

                    <Brush
                        width={400}
                        height={50}
                        margin={{top: 0, bottom: 30, left: 50, right: 20}}
                        xScale={this.state.xScaleBrush}
                        extent={[new Date(2015, 2, 10), new Date(2015, 2, 12)]}
                        onChange={this._onChange}
                        xAxis={{tickValues: this.state.xScaleBrush.ticks(d3.time.day, 2), tickFormat: d3.time.format("%m/%d")}}
                    />

        );
    },

    _onChange: function(extent) {
        this.setState({xScale: d3.time.scale().domain([extent[0], extent[1]]).range([0, 400 - 70])});
    }
});
export default App;

index.js looks like :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

i have already installed react-d3-components also it's there in package.json ; still I get errors like :

TypeError: Cannot read property 'LineChart' of undefined

Also, where ever there is d3.time.day there it says unresolved function. I also tried importing d3 the other way using :

import * as d3 from 'd3'.

But still I get some different errors.

Please suggest what I'm doing wrong, so that I can set up my initial code to work.

Thanks

Body:
You might not be importing d3 properly, which might be causing reactd3 to be imported improperly as well. Try importing d3 like this at the top:

import d3 from 'd3';


问:
WPF Set user control dependency properties
Below a piece of my user control:

```<code><UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent"
             Height="{Binding ControlHeightProperty}"
             Width="{Binding ControlWidthProperty}">

  <UserControl.Resources>
    <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
  </UserControl.Resources>

    <Viewbox Width="{Binding ControlWidthProperty}" Height="{Binding ControlHeightProperty}" HorizontalAlignment="Center" VerticalAlignment="Center">
    <!-- other objects -->
    </Viewbox>
</UserControl>
</code>```

and its code-behind with my dependency properties:

```<code>public partial class CircularProgressBar
{
    public static readonly DependencyProperty ControlHeightProperty =
        DependencyProperty.Register("ControlHeight", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));

    public static readonly DependencyProperty ControlWidthProperty =
        DependencyProperty.Register("ControlWidth", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));

    public int ControlHeight
    {
        get { return (int)GetValue(ControlHeightProperty); }
        set { SetValue(ControlHeightProperty, value); }
    }

    public int ControlWidth
    {
        get { return (int)GetValue(ControlWidthProperty); }
        set { SetValue(ControlWidthProperty, value); }
    }
}
</code>```

Then from my wpf main window:

```<code>    <ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
                         HorizontalAlignment="Center"
                         VerticalAlignment="Center"
                         ControlHeight="100"
                         ControlWidth="100"/>
</code>```

What I am trying to do is set width and height for my user control from my main window. In above example I am trying to set user control height and width to 100 through dependency properties ControlHeight and ControlWidth respectively.

If from my main windows ControlHeight and ControlWidth is not specified, I want user control height and width take as default value of 45.

But above example is not working for me. What am I doing wrong?

UPDATE WORKING:
As Clemens suggested, I have changed the code into the following:

```<code><UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent">

  <UserControl.Resources>
    <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
  </UserControl.Resources>

    <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center">
    <!-- other objects -->
    </Viewbox>
</UserControl>
</code>```

In code-behind dependency properties ControlHeightProperty and ControlWidthProperty are not needed.

Finally in my wpf window, setting typical height and width properties are enough:

```<code>    <ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
                         HorizontalAlignment="Center"
                         VerticalAlignment="Center"
                         Height="100"
                         Width="100"/>
</code>```

答:
You'll have to bind to the actual property, not its identifier field, i.e. ControlWidth instead of ControlWidthProperty.

Besides that, you also have to set a binding source, which in this case is the UserControl instance, referenced either by RelativeSource Self at the UserControl level, or RelativeSource AncestorType=UserControl at any level below.

```<code><UserControl Width="{Binding ControlWidth, RelativeSource={RelativeSource Self}}" ...>

<Viewbox Width="{Binding ControlWidth,
                 RelativeSource={RelativeSource AncestorType=UserControl}}" ...>
</code>```

Note however that none of these bindings really make sense. There is no point in adding a ControlWidth property when there already is a Width.

At the Viewbox it isn't necessary to bind the Width or Height because the UserControl will already resize it appropriately.

So in fact you don't need any additional property. Your UserControl's XAML should look like shown below, without explicitly setting any Width or Height.

```<code><UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent">
    <UserControl.Resources>
        <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
    </UserControl.Resources>
    <Viewbox>
        <!-- other objects -->
    </Viewbox>
</UserControl>
</code>```

When you use that control somewhere in your MainWindow, instead of setting ControlWidth and ControlHeight, just set Width and Height.

Body:
Below a piece of my user control:

<UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent"
             Height="{Binding ControlHeightProperty}"
             Width="{Binding ControlWidthProperty}">

  <UserControl.Resources>
    <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
  </UserControl.Resources>

    <Viewbox Width="{Binding ControlWidthProperty}" Height="{Binding ControlHeightProperty}" HorizontalAlignment="Center" VerticalAlignment="Center">

    </Viewbox>
</UserControl>

and its code-behind with my dependency properties:

public partial class CircularProgressBar
{
    public static readonly DependencyProperty ControlHeightProperty =
        DependencyProperty.Register("ControlHeight", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));

    public static readonly DependencyProperty ControlWidthProperty =
        DependencyProperty.Register("ControlWidth", typeof(int), typeof(CircularProgressBar), new UIPropertyMetadata(45));

    public int ControlHeight
    {
        get { return (int)GetValue(ControlHeightProperty); }
        set { SetValue(ControlHeightProperty, value); }
    }

    public int ControlWidth
    {
        get { return (int)GetValue(ControlWidthProperty); }
        set { SetValue(ControlWidthProperty, value); }
    }
}

Then from my wpf main window:

    <ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
                         HorizontalAlignment="Center"
                         VerticalAlignment="Center"
                         ControlHeight="100"
                         ControlWidth="100"/>

What I am trying to do is set width and height for my user control from my main window. In above example I am trying to set user control height and width to 100 through dependency properties ControlHeight and ControlWidth respectively.

If from my main windows ControlHeight and ControlWidth is not specified, I want user control height and width take as default value of 45.

But above example is not working for me. What am I doing wrong?

UPDATE WORKING:
As Clemens suggested, I have changed the code into the following:

<UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent">

  <UserControl.Resources>
    <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
  </UserControl.Resources>

    <Viewbox HorizontalAlignment="Center" VerticalAlignment="Center">

    </Viewbox>
</UserControl>

In code-behind dependency properties ControlHeightProperty and ControlWidthProperty are not needed.

Finally in my wpf window, setting typical height and width properties are enough:

    <ctr:CircularProgressBar x:Name="progressBar" Grid.ZIndex="3"
                         HorizontalAlignment="Center"
                         VerticalAlignment="Center"
                         Height="100"
                         Width="100"/>

Body:
You'll have to bind to the actual property, not its identifier field, i.e. ControlWidth instead of ControlWidthProperty.

Besides that, you also have to set a binding source, which in this case is the UserControl instance, referenced either by RelativeSource Self at the UserControl level, or RelativeSource AncestorType=UserControl at any level below.

<UserControl Width="{Binding ControlWidth, RelativeSource={RelativeSource Self}}" ...>

<Viewbox Width="{Binding ControlWidth,
                 RelativeSource={RelativeSource AncestorType=UserControl}}" ...>

Note however that none of these bindings really make sense. There is no point in adding a ControlWidth property when there already is a Width.

At the Viewbox it isn't necessary to bind the Width or Height because the UserControl will already resize it appropriately.

So in fact you don't need any additional property. Your UserControl's XAML should look like shown below, without explicitly setting any Width or Height.

<UserControl x:Class="WpfApplication1.Controls.CircularProgressBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Background="Transparent">
    <UserControl.Resources>
        <SolidColorBrush x:Key="progressCirclesColor" Color="#FF2E6187" />
    </UserControl.Resources>
    <Viewbox>
        <!-- other objects -->
    </Viewbox>
</UserControl>

When you use that control somewhere in your MainWindow, instead of setting ControlWidth and ControlHeight, just set Width and Height.


问:
Variable value becomes nil after fbsdk graph request
I am writing a project in swift and I am pretty new to the language.

I set a variable "username"'s value to the result of my request to the facebook sdk, but my variable value becomes nil after the graph request. The variable assignment works fine inside the graph request itself.

Here is my code.

```<code>import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class SecondViewController: UIViewController {

    var username : String = "X"
    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        FBSDKGraphRequest(graphPath: "/me", parameters: ["Fields" : "name"]).start {

            (connection, result, err) in

            if err != nil {
                print("Failed to start request", err)
                return
            }

            var res = result as? [String : Any]
            self.username = (res?["name"] as! String)

            print(self.username)

        }

        print(self.username)
    }

}
</code>```

The first print statement that is inside the request works just fine but the second one that is outside of the request prints an empty line.

This was also the case when I wanted to set the text of a label to the value of the username variable. It worked inside the request but didn't do anything otherwise.

答:
i think first perform login which permissions:

```<code>    loginManager.logIn(withReadPermissions: ["email","public_profile"], from: self) { (FBSDKLoginManagerLoginResult, Error) in

        if(Error == nil){
            if(FBSDKLoginManagerLoginResult?.isCancelled)!{
                SVProgressHUD.showError(withStatus: "You Cancelled To Login With Facebook, \n Try Again Later!")
            }else if(FBSDKLoginManagerLoginResult?.token != nil){
                SVProgressHUD.showSuccess(withStatus: "Login Successfull")

                SVProgressHUD.show(withStatus: loadingText)

                if((FBSDKAccessToken.current()) != nil){
                    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
                        if (error == nil){
                            let resultDic = result as! [String: Any]
                            let facebookProfileUrl : String! = "http://graph.facebook.com/\((FBSDKLoginManagerLoginResult?.token!.userID)!)/picture?type=large"
                            var fbId = (FBSDKLoginManagerLoginResult?.token!.userID)! as String
                            var name = resultDic["name"] as! String
                            var email = resultDic["email"] as! String

                        }else{
                            print(error!.localizedDescription)
                        }
                    })
                }
            }
        }
    }
</code>```

as your inside code is working which means you perform above well, i think its working in threading, which means your bottom "print(self.username)" is printed first, then above one which is inside of block,

you can LOG it after completion of Graph API response.

Body:
I am writing a project in swift and I am pretty new to the language.

I set a variable "username"'s value to the result of my request to the facebook sdk, but my variable value becomes nil after the graph request. The variable assignment works fine inside the graph request itself.

Here is my code.

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class SecondViewController: UIViewController {

    var username : String = "X"
    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        FBSDKGraphRequest(graphPath: "/me", parameters: ["Fields" : "name"]).start {

            (connection, result, err) in

            if err != nil {
                print("Failed to start request", err)
                return
            }

            var res = result as? [String : Any]
            self.username = (res?["name"] as! String)

            print(self.username)

        }

        print(self.username)
    }

}

The first print statement that is inside the request works just fine but the second one that is outside of the request prints an empty line.

This was also the case when I wanted to set the text of a label to the value of the username variable. It worked inside the request but didn't do anything otherwise.

Body:
i think first perform login which permissions:

    loginManager.logIn(withReadPermissions: ["email","public_profile"], from: self) { (FBSDKLoginManagerLoginResult, Error) in

        if(Error == nil){
            if(FBSDKLoginManagerLoginResult?.isCancelled)!{
                SVProgressHUD.showError(withStatus: "You Cancelled To Login With Facebook, \n Try Again Later!")
            }else if(FBSDKLoginManagerLoginResult?.token != nil){
                SVProgressHUD.showSuccess(withStatus: "Login Successfull")

                SVProgressHUD.show(withStatus: loadingText)

                if((FBSDKAccessToken.current()) != nil){
                    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
                        if (error == nil){
                            let resultDic = result as! [String: Any]
                            let facebookProfileUrl : String! = "http://graph.facebook.com/\((FBSDKLoginManagerLoginResult?.token!.userID)!)/picture?type=large"
                            var fbId = (FBSDKLoginManagerLoginResult?.token!.userID)! as String
                            var name = resultDic["name"] as! String
                            var email = resultDic["email"] as! String

                        }else{
                            print(error!.localizedDescription)
                        }
                    })
                }
            }
        }
    }

as your inside code is working which means you perform above well, i think its working in threading, which means your bottom "print(self.username)" is printed first, then above one which is inside of block,

you can LOG it after completion of Graph API response.


问:
How do I access the first key of an ‘associative’ array in JavaScript?
I have a js 'associative' array, with

```<code>array['serial_number'] = 'value'
</code>```

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

```<code>for (var i in sorted)
</code>```

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

答:
2021 Update

Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:

Original answer

JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:

```<code>var nameValues = [
    {name: '20910930923', value: '20101102'},
    {name: 'foo', value: 'bar'}
];
</code>```

... or as an ordered list of property names to use with your existing object:

```<code>var obj = {
   '20910930923': '20101102',
   'foo': 'bar'
};

var orderedPropertyNames = ['20910930923', 'foo'];
</code>```

Body:
I have a js 'associative' array, with

array['serial_number'] = 'value'

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

for (var i in sorted)

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

Body:
2021 Update

Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:

Original answer

JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:

var nameValues = [
    {name: '20910930923', value: '20101102'},
    {name: 'foo', value: 'bar'}
];

... or as an ordered list of property names to use with your existing object:

var obj = {
   '20910930923': '20101102',
   'foo': 'bar'
};

var orderedPropertyNames = ['20910930923', 'foo'];


问:
Extracting a Clojure vec from a Jdbc4Array
I'm very new to Clojure and I am working on creating a small web API using Clojure, Compojure and java.jdbc with a POSTGRES database.

One of my tables contains an array of integers as one of its columns and is defined as such:

```<code>                    (sql/create-table-ddl
                     :games
                     [:id :serial "PRIMARY KEY"]
                     [:active :BOOLEAN "NOT NULL"]
                     [:players "integer[]" "DEFAULT array[]::integer[]"]
                     [:player_order "integer[]" "DEFAULT array[]::integer[]"]
                     [:created_at :timestamp
                      "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"])
</code>```

I am trying to query for one of the integer[] as such:

```<code>(sql/query postgres  [(str "SELECT * FROM games WHERE id=" game-id)])
</code>```

But POSTGRES returns a Jdbc4Array (instead of a vec):

```<code>:player_order #<Jdbc4Array {1,2,3,4}
org.postgresql.jdbc4.Jdbc4Array
</code>```

I can't seem to figure out how to turn this into a Clojure vec. I've seen a few examples but they seem to be using a stream which I am not. Am I doing this query incorrectly? How would I convert this to a Clojure vec?

答:
Jdbc4Array implements java.sql.Array; I don't have a PG database or calling code to hand, but according to the docs for java.sql.Array, you should be able to call:

```<code>(into [] (.getArray your-val))
</code>```

However, you shouldn't have to do that manually throughout your code. You can have the conversion from Jdbc4Array to Vector done automatically for you everywhere by extending the clojure.java.jdbc/IResultSetReadColumn protocol to java.sql.Array.

This has already been demonstrated here on StackOverflow:

https://stackoverflow.com/a/25786990/152739

(I don't want to copy that guy's answer verbatim!)

Body:
I'm very new to Clojure and I am working on creating a small web API using Clojure, Compojure and java.jdbc with a POSTGRES database.

One of my tables contains an array of integers as one of its columns and is defined as such:

                    (sql/create-table-ddl
                     :games
                     [:id :serial "PRIMARY KEY"]
                     [:active :BOOLEAN "NOT NULL"]
                     [:players "integer[]" "DEFAULT array[]::integer[]"]
                     [:player_order "integer[]" "DEFAULT array[]::integer[]"]
                     [:created_at :timestamp
                      "NOT NULL" "DEFAULT CURRENT_TIMESTAMP"])

I am trying to query for one of the integer[] as such:

(sql/query postgres  [(str "SELECT * FROM games WHERE id=" game-id)])

But POSTGRES returns a Jdbc4Array (instead of a vec):

:player_order #<Jdbc4Array {1,2,3,4}
org.postgresql.jdbc4.Jdbc4Array

I can't seem to figure out how to turn this into a Clojure vec. I've seen a few examples but they seem to be using a stream which I am not. Am I doing this query incorrectly? How would I convert this to a Clojure vec?

Body:
Jdbc4Array implements java.sql.Array; I don't have a PG database or calling code to hand, but according to the docs for java.sql.Array, you should be able to call:

(into [] (.getArray your-val))

However, you shouldn't have to do that manually throughout your code. You can have the conversion from Jdbc4Array to Vector done automatically for you everywhere by extending the clojure.java.jdbc/IResultSetReadColumn protocol to java.sql.Array.

This has already been demonstrated here on StackOverflow:

https://stackoverflow.com/a/25786990/152739

(I don't want to copy that guy's answer verbatim!)


问:
How can I use an environment variable as a name for a docker container?
I want to name a docker container using and environment variable, something t=like:

NAME=TEST docker run --name ${NAME}

I tried several approaches for interpreting the environment variable, but I ran out of ideas.

My trials so far:

$NAME

${NAME}

`${NAME}`

`NAME`

Any idea how that is possible?

答:
As Francois Maturel said, the following is working:

```<code>NAME=TEST && docker run --name ${NAME} -it -d ubuntu bash
</code>```

And this:

```<code>export NAME=TEST
docker run --name ${NAME} -it -d ubuntu bash
</code>```

And:

```<code>NAME=TEST sh -c 'docker run --name ${NAME} -it -d ubuntu bash'
</code>```

Body:
As Francois Maturel said, the following is working:

NAME=TEST && docker run --name ${NAME} -it -d ubuntu bash

And this:

export NAME=TEST
docker run --name ${NAME} -it -d ubuntu bash

And:

NAME=TEST sh -c 'docker run --name ${NAME} -it -d ubuntu bash'


问:
Is it possible to use .exceptionCount(true) twice?
i have a problem, I want to count the different elements of bar and num associated with foo

```<code>var data = crossfilter([
{ foo: 'one', bar: 'A', num: '1' },
{ foo: 'two', bar: 'B', num: '2' },
{ foo: 'three', bar: 'A', num: '3' },
{ foo: 'one', bar: 'B', num: '3' },
{ foo: 'one', bar: 'A', num: '2' },
{ foo: 'two', bar: 'B', num: '2' },
]);
</code>```

ie, I want to get, for example:

```<code>[ { key: 'one', value: { exceptionCount: 2, exceptionCount2: 3 },    // 'bar' dimension has 2 values: 'A' and 'B', and has 3 values: '1' and '2' and '3'
{ key: 'two', value: { exceptionCount: 1, exceptionCount2: 1 },    // 'bar' dimension has 1 value: 'B', '2'
{ key: 'three', value: { exceptionCount: 1 , exceptionCount2: 1} ] // 'bar' dimension has 1 value: 'A', '3'
</code>```

I have use of the reductio library with exceptionCount to separate for num and bar, but I could not join both associated with only foo.

Can you help me, please

答:
Thank you,

I use

```<code> reducer=reductio();
 reducer.value('nbar').exception(function(d){return d['bar']}.exceptionCount(true);
 reducer.value('nnum').exception(function(d){return d['num']}.exceptionCount(true);
</code>```

and i apply to group.

```<code> reducer(my_group_name);
</code>```

Body:
i have a problem, I want to count the different elements of bar and num associated with foo

var data = crossfilter([
{ foo: 'one', bar: 'A', num: '1' },
{ foo: 'two', bar: 'B', num: '2' },
{ foo: 'three', bar: 'A', num: '3' },
{ foo: 'one', bar: 'B', num: '3' },
{ foo: 'one', bar: 'A', num: '2' },
{ foo: 'two', bar: 'B', num: '2' },
]);

ie, I want to get, for example:

[ { key: 'one', value: { exceptionCount: 2, exceptionCount2: 3 },    // 'bar' dimension has 2 values: 'A' and 'B', and has 3 values: '1' and '2' and '3'
{ key: 'two', value: { exceptionCount: 1, exceptionCount2: 1 },    // 'bar' dimension has 1 value: 'B', '2'
{ key: 'three', value: { exceptionCount: 1 , exceptionCount2: 1} ] // 'bar' dimension has 1 value: 'A', '3'

I have use of the reductio library with exceptionCount to separate for num and bar, but I could not join both associated with only foo.

Can you help me, please

Body:
Thank you,

I use

 reducer=reductio();
 reducer.value('nbar').exception(function(d){return d['bar']}.exceptionCount(true);
 reducer.value('nnum').exception(function(d){return d['num']}.exceptionCount(true);

and i apply to group.

 reducer(my_group_name);


问:
Syntax Error(missing operator) in query expression - MS-Access
This doesn't produce syntax errors but it gives wrong arguments error:

```<code>SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],",")))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON (right(FinalForgotten.aname,
 IIF(instr([aname], ",") = 0,
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],",")
  )
 )=defense_final.first_name) AND (left(FinalForgotten.aname,
IIF(instr([aname], ",") = 0,
  InStr(1,FinalForgotten.[aname]," ")-1,
  InStr(1,FinalForgotten.[aname],",")-1
    )
)=defense_final.last_name);
</code>```

So adding the extra arguments I now get syntax error "Missing ), ], or Item in query expression" :

```<code>   SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],","))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON

left(FinalForgotten.aname,
   IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
      IIF(instr([aname], ",") = 0,
        InStr(1,FinalForgotten.[aname]," ")-1,
        InStr(1,FinalForgotten.[aname],",")-1)))

 =defense_final.last_name AND

 right(FinalForgotten.aname,
      IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
       IIF(instr([aname], ",") = 0,
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],","))))

=defense_final.first_name;
</code>```

Any workaround?

Thanks for response.

答:
```<code> IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,
</code>```

on line 12 should be

```<code> IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
</code>```

Body:
This doesn't produce syntax errors but it gives wrong arguments error:

SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],",")))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON (right(FinalForgotten.aname,
 IIF(instr([aname], ",") = 0,
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],",")
  )
 )=defense_final.first_name) AND (left(FinalForgotten.aname,
IIF(instr([aname], ",") = 0,
  InStr(1,FinalForgotten.[aname]," ")-1,
  InStr(1,FinalForgotten.[aname],",")-1
    )
)=defense_final.last_name);

So adding the extra arguments I now get syntax error "Missing ), ], or Item in query expression" :

   SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],","))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON

left(FinalForgotten.aname,
   IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
      IIF(instr([aname], ",") = 0,
        InStr(1,FinalForgotten.[aname]," ")-1,
        InStr(1,FinalForgotten.[aname],",")-1)))

 =defense_final.last_name AND

 right(FinalForgotten.aname,
      IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
       IIF(instr([aname], ",") = 0,
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],","))))

=defense_final.first_name;

Any workaround?

Thanks for response.

Body:
 IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,

on line 12 should be

 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,


问:
Look up an attribute from an instance
From Python in a Nutshell

Getting an attribute from an instance

When you use the syntax  x.name  to refer to an attribute of
  instance  x  of class  C , the lookup proceeds in three steps:

When  name  is found in  C  (or in one of  C’s ancestor classes) as the name of an overriding descriptor  v  (i.e.,
  type(v)  supplies methods  __get__ and  __set__ )

• The value of  x.name  is the result of  type(v).__get__(v, x, C)

Otherwise, when  name  is a key in  x.__dict__

• x.name  fetches and returns the value at  x.__dict__['name']

Otherwise,  x.name  delegates the lookup to  x’s class (according to the same two-step lookup used for  C.name, as just
  detailed)

• When a descriptor  v  is found, the overall result of the
  attribute lookup is, again,  type(v).__get__(v, x, C)

• When  a  nondescriptor  value  v   is  found,  the  overall
  result  of  the  attribute lookup is just  v

When these lookup steps do not find an attribute, Python raises an  AttributeError exception. However, for lookups of  x.name , when  C  defines or inherits the special
  method  __getattr__ , Python calls  C.__getattr__(x,'name')  rather than raising
  the exception. It’s then up to  __getattr__  to either return a suitable value or raise
  the appropriate exception, normally  AttributeError .

Are step 1 and the first part of step 3 the same? If yes, why does the same step appear twice?

Do they both happen "when name is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor  v"?

```<code>__getattribute__(self, name)
</code>```

At every request to access attribute x.y, Python calls
  x.__getattribute__('y'), which must get and return the attribute
  value or else raise AttributeError. The normal semantics of
  attribute access (using x.__dict__, C.__slots__, C’s class
  attributes, x.__getattr__) are all due to object.__getattribute__.
  When class C overrides __getattribute__, it must implement all of
  the attribute access semantics it wants to offer. Most often, the most
  convenient way to implement attribute access semantics is by
  delegating (e.g., calling object.__getattribute__(self, ...) as part
  of the operation of your override of __getattribute__).

答:
Are step 1 and the first part of step 3 the same? If yes, why the same step appear twice?

Step 1 requires both __get__ and __set__ (although actually, either __set__ or __delete__ along with __get__ would trigger it). Step 3 happens unconditionally if the attribute isn't found through steps 1 or 2.

Do they both happen "when  name is found in  C (or in one of  C’s ancestor classes) as the name of an overriding descriptor  v"?

No. An "overriding descriptor" triggers step 1; another kind of descriptor or a non-descriptor will only be considered in step 3. (The official Python docs don't use the term "overriding descriptor"; they refer to a descriptor with __set__ or __delete__ as a "data descriptor", and if a data descriptor has __get__, the __get__ will take priority over an object found in an instance dict.)

Title: Look up an attribute from an instance

Body:
From Python in a Nutshell

Getting an attribute from an instance

When you use the syntax  x.name  to refer to an attribute of
  instance  x  of class  C , the lookup proceeds in three steps:

When  name  is found in  C  (or in one of  C’s ancestor classes) as the name of an overriding descriptor  v  (i.e.,
  type(v)  supplies methods  __get__ and  __set__ )

• The value of  x.name  is the result of  type(v).__get__(v, x, C)

Otherwise, when  name  is a key in  x.__dict__

• x.name  fetches and returns the value at  x.__dict__['name']

Otherwise,  x.name  delegates the lookup to  x’s class (according to the same two-step lookup used for  C.name, as just
  detailed)

• When a descriptor  v  is found, the overall result of the
  attribute lookup is, again,  type(v).__get__(v, x, C)

• When  a  nondescriptor  value  v   is  found,  the  overall
  result  of  the  attribute lookup is just  v

When these lookup steps do not find an attribute, Python raises an  AttributeError exception. However, for lookups of  x.name , when  C  defines or inherits the special
  method  __getattr__ , Python calls  C.__getattr__(x,'name')  rather than raising
  the exception. It’s then up to  __getattr__  to either return a suitable value or raise
  the appropriate exception, normally  AttributeError .

Are step 1 and the first part of step 3 the same? If yes, why does the same step appear twice?

Do they both happen "when name is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor  v"?

__getattribute__(self, name)

At every request to access attribute x.y, Python calls
  x.__getattribute__('y'), which must get and return the attribute
  value or else raise AttributeError. The normal semantics of
  attribute access (using x.__dict__, C.__slots__, C’s class
  attributes, x.__getattr__) are all due to object.__getattribute__.
  When class C overrides __getattribute__, it must implement all of
  the attribute access semantics it wants to offer. Most often, the most
  convenient way to implement attribute access semantics is by
  delegating (e.g., calling object.__getattribute__(self, ...) as part
  of the operation of your override of __getattribute__).


问:
What's the equivalent of Laravel queue jobs in Express?
Laravel offers a feature called Queues where you delegate long running task to a background worker using a service (beanstalkd, Amazon SQS, Rabbit MQ). A quick example would be sending an email through that queued job, instead of from the controller. Said queued job is able to identify whether the task was completed, or, if it failed, retry a certain amount of times.

What's the Express (NodeJS) equivalent of this feature (if it even exists)? I tried researching the topic by directly looking for resources on the service (like RabbitMQ) and I only found tutorial like this one, but just by reading it looks like they're implementing the thing from the ground.

Maybe my expectations are what's wrong in here, but isn't there an equivalent of just writing the business logic code for the queued job and dispatching it?

答:
In our case, when we need to implement background jobs to send email with attachments to bulk users using node and express we came across powerful npm module Kue, which provides all features which RabbitMQ provides in php

Official Documentation

Hope it helps!


问:
Downloading image doesn't work: NodeJS
I've written a little function in Node for downloading an image from a server and saving it on my server, but it doesn't work. The image file is created, but it seems to be corrupt, here's the function:

```<code>function d() {
    var data = [
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/OG_134.png",
            cardId: "yogg"
        },
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_07.png",
            cardId: "nzoth"
        }
    ];
    for(var card of data) {
        if("img" in card) {
            var img = require('fs').createWriteStream("./public/assets/pics/" + card.cardId + ".png");
            require("http").get(card.img, (res) => {
                res.pipe(img);
            });
        }
    }
}
</code>```

What am I doing wrong?

答:
Use this:</p>

```<code>var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.THE_URL.com/image.png', 'THE_NAME.png', function(){
  console.log('Image saved!');
});
</code>```

Title: Downloading image doesn't work: NodeJS

Body:
I've written a little function in Node for downloading an image from a server and saving it on my server, but it doesn't work. The image file is created, but it seems to be corrupt, here's the function:

function d() {
    var data = [
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/OG_134.png",
            cardId: "yogg"
        },
        {
            img: "http://wow.zamimg.com/images/hearthstone/cards/enus/original/HERO_07.png",
            cardId: "nzoth"
        }
    ];
    for(var card of data) {
        if("img" in card) {
            var img = require('fs').createWriteStream("./public/assets/pics/" + card.cardId + ".png");
            require("http").get(card.img, (res) => {
                res.pipe(img);
            });
        }
    }
}

What am I doing wrong?

Body:
Use this:

var fs = require('fs'),
    request = require('request');

var download = function(uri, filename, callback){
  request.head(uri, function(err, res, body){
    console.log('content-type:', res.headers['content-type']);
    console.log('content-length:', res.headers['content-length']);

    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
  });
};

download('https://www.THE_URL.com/image.png', 'THE_NAME.png', function(){
  console.log('Image saved!');
});


问:
Scala: Requiring members on companion objects of abstract classes
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

```<code>abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false
</code>```

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

答:
One possible solution is to use the type class pattern. We have our domain model (or algebra) via ADTs:

```<code>sealed trait Fruit
case class Apple() extends Fruit
case class Orange() extends Fruit
</code>```

We have our type class, which defines the structure we want to supply:

```<code>trait TastyCultivarSupplier[T <: Fruit] {
  def tastyCultivars: Set[String]
}
</code>```

And now each type which has tasty cultivars will need to implement the type class in order to provide them. One possible way to do this is to implement the typeclass inside the companion object:

```<code>object Apple {
  implicit def appleTastyCultivars = new TastyCultivarSupplier[Apple] {
    override def tastyCultivars: Set[String] = Set("Yummy stuff")
  }
}
</code>```

Inside the consumer, or the type which wants to get the tasty cultivars, we require an implicit evidence of a TastyCultivarSupplier:

```<code>class TastyCultivarConsumer {
  def isTasty[T: TastyCultivarSupplier](name: String): Boolean =
    implicitly[TastyCultivarSupplier[T]].tastyCultivars.contains(name)
}
</code>```

When isTasty is invoked, it will need to have one of the suppliers in scope, otherwise a compile time error will occur:

```<code>def main(args: Array[String]): Unit = {
  println(new TastyCultivarConsumer().isTasty("Yummy stuff"))
}
</code>```

Will give us:

```<code>Error:(33, 48) could not find implicit value for evidence parameter
of type TastyCultivarSupplier[T]
    println(new TastyCultivarConsumer().isTasty("Yummy stuff"))
</code>```

To fix this, we import the supplier we want:

```<code>def main(args: Array[String]): Unit = {
  import Apple._
  println(new TastyCultivarConsumer().isTasty("Yummy stuff"))
}
</code>```

And now our code compiles. Note that the implementer isn't forced to write the evidence inside the companion object, he is free to do so anywhere he wants, as long as it's in scope for the compiler to find.

Body:
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

Body:
One possible solution is to use the type class pattern. We have our domain model (or algebra) via ADTs:

sealed trait Fruit
case class Apple() extends Fruit
case class Orange() extends Fruit

We have our type class, which defines the structure we want to supply:

trait TastyCultivarSupplier[T <: Fruit] {
  def tastyCultivars: Set[String]
}

And now each type which has tasty cultivars will need to implement the type class in order to provide them. One possible way to do this is to implement the typeclass inside the companion object:

object Apple {
  implicit def appleTastyCultivars = new TastyCultivarSupplier[Apple] {
    override def tastyCultivars: Set[String] = Set("Yummy stuff")
  }
}

Inside the consumer, or the type which wants to get the tasty cultivars, we require an implicit evidence of a TastyCultivarSupplier:

class TastyCultivarConsumer {
  def isTasty[T: TastyCultivarSupplier](name: String): Boolean =
    implicitly[TastyCultivarSupplier[T]].tastyCultivars.contains(name)
}

When isTasty is invoked, it will need to have one of the suppliers in scope, otherwise a compile time error will occur:

def main(args: Array[String]): Unit = {
  println(new TastyCultivarConsumer().isTasty("Yummy stuff"))
}

Will give us:

Error:(33, 48) could not find implicit value for evidence parameter
of type TastyCultivarSupplier[T]
    println(new TastyCultivarConsumer().isTasty("Yummy stuff"))

To fix this, we import the supplier we want:

def main(args: Array[String]): Unit = {
  import Apple._
  println(new TastyCultivarConsumer().isTasty("Yummy stuff"))
}

And now our code compiles. Note that the implementer isn't forced to write the evidence inside the companion object, he is free to do so anywhere he wants, as long as it's in scope for the compiler to find.