问:
Why is class constraint not detected for generic class using an inherited type?
Phrasing the question was hard, I hope the following code snippet makes things clear:

```<code>public class DemoClass<TBase> where TBase : class
{
    public void DemoMethod<T>(T target) where T : TBase
    {
        //The following line causes a design-time error: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T'.
        WeakReference<T> demoRef = new WeakReference<T>(target);
    }
}
</code>```

The WeakReference requires a type, T, that satisfies a class constraint. So far, so good, but...

Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

答:
Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

Because that is simply not true. On top of what Poke points out in his answer, this is also illegal due to the fact that all value types inherit from object:

```<code> var dc = new DemoClass<object>();
 dc.DemoMethod(1); //woops, just attempted to create a WeakReference<int>
</code>```

Your reasoning simply falls apart when value types are involved. Contrived? Yes, but perfectly legal so the compiler doesn't have a choice and has to consider your code illegal.

UPDATE

Addressing Jon Hana's comment below that in the code above T is not really int, its object and 1 is boxed implicitly, that is absolutely not true. Consider the following variation of DemoMethod:

```<code>public T DemoMethod<T>(T target) where T : TBase
{
    return target;
}
</code>```

And the following code:

```<code>var dc = new DemoClass<object>();
var i = dc.DemoMethod(1);
</code>```

i is int, its not object. Moreover, the following will execute correctly:

```<code>long i = dc.DemoMethod(1);
</code>```

Which also proves the T can not be a boxed int because the implicit conversion would fail at runtime; you can't unbox a value type to anything but the type itself.

And of course, you can always set T explicitly, which also compiles just fine:

```<code>dc.DemoMethod<int>(1);
</code>```

Body:
Phrasing the question was hard, I hope the following code snippet makes things clear:

public class DemoClass<TBase> where TBase : class
{
    public void DemoMethod<T>(T target) where T : TBase
    {
        //The following line causes a design-time error: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T'.
        WeakReference<T> demoRef = new WeakReference<T>(target);
    }
}

The WeakReference requires a type, T, that satisfies a class constraint. So far, so good, but...

Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

Body:
Why can the compiler not detect that T actually does, because (practically) T : TBase : class?

Because that is simply not true. On top of what Poke points out in his answer, this is also illegal due to the fact that all value types inherit from object:

 var dc = new DemoClass<object>();
 dc.DemoMethod(1); //woops, just attempted to create a WeakReference<int>

Your reasoning simply falls apart when value types are involved. Contrived? Yes, but perfectly legal so the compiler doesn't have a choice and has to consider your code illegal.

UPDATE

Addressing Jon Hana's comment below that in the code above T is not really int, its object and 1 is boxed implicitly, that is absolutely not true. Consider the following variation of DemoMethod:

public T DemoMethod<T>(T target) where T : TBase
{
    return target;
}

And the following code:

var dc = new DemoClass<object>();
var i = dc.DemoMethod(1);

i is int, its not object. Moreover, the following will execute correctly:

long i = dc.DemoMethod(1);

Which also proves the T can not be a boxed int because the implicit conversion would fail at runtime; you can't unbox a value type to anything but the type itself.

And of course, you can always set T explicitly, which also compiles just fine:

dc.DemoMethod<int>(1);


来源: stackexchange

问:
UIScrollView: single tap scrolls it to top
I have the UIScrollView with pagingEnabled set to YES, and programmatically scroll its content to bottom:

```<code>CGPoint contentOffset = scrollView.contentOffset;
contentOffset.y = scrollView.contentSize.height - scrollView.frame.size.height;
[scrollView setContentOffset:contentOffset animated:YES];
</code>```

it scrolls successfully, but after that, on single tap its content scrolls up to offset that it has just before it scrolls down. That happens only when I programmaticaly scroll scrollView's content to bottom and then tap. When I scroll to any other offset and then tap, nothing is happened.

That's definitely not what I'd like to get. How that should be fixed?

Much thanks in advance!

Timur.

答:
The following workaround did help (assume that one extends UIScrollView with a category, so 'self' refers to its instance):

```<code>-(BOOL) scrolledToBottom
{
    return (self.contentSize.height <= self.frame.size.height) ||
           (self.contentOffset.y == self.contentSize.height - self.frame.size.height);
}
</code>```

Then, one should sometimes turn pagingEnabled off, just at the position where scroll view reaches its bottom. In the delegate (pagingEnabled is initialy on of course, since the problem occurs only when it is enabled):

```<code>-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.pagingEnabled == YES)
    {
        if ([scrollView scrolledToBottom] == YES)
            scrollView.pagingEnabled = NO;
    }
    else
    {
        if ([scrollView scrolledToBottom] == NO)
            scrollView.pagingEnabled = YES;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the UIScrollView with pagingEnabled set to YES, and programmatically scroll its content to bottom:

CGPoint contentOffset = scrollView.contentOffset;
contentOffset.y = scrollView.contentSize.height - scrollView.frame.size.height;
[scrollView setContentOffset:contentOffset animated:YES];

it scrolls successfully, but after that, on single tap its content scrolls up to offset that it has just before it scrolls down. That happens only when I programmaticaly scroll scrollView's content to bottom and then tap. When I scroll to any other offset and then tap, nothing is happened.

That's definitely not what I'd like to get. How that should be fixed?

Much thanks in advance!

Timur.

Body:
The following workaround did help (assume that one extends UIScrollView with a category, so 'self' refers to its instance):

-(BOOL) scrolledToBottom
{
    return (self.contentSize.height <= self.frame.size.height) ||
           (self.contentOffset.y == self.contentSize.height - self.frame.size.height);
}

Then, one should sometimes turn pagingEnabled off, just at the position where scroll view reaches its bottom. In the delegate (pagingEnabled is initialy on of course, since the problem occurs only when it is enabled):

-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.pagingEnabled == YES)
    {
        if ([scrollView scrolledToBottom] == YES)
            scrollView.pagingEnabled = NO;
    }
    else
    {
        if ([scrollView scrolledToBottom] == NO)
            scrollView.pagingEnabled = YES;
    }
}


问:
In Java, how do I test if an object's monitor is locked using traditional low-level locking mechanisms?
In Java, how do I test if an object's monitor is locked? In other words, given a object obj, does any thread own obj's monitor?

I do not care which thread owns the monitor. All I need to test is if ANY thread owns a given object's monitor. Since a thread other than the current thread could own the monitor, Thread.holdsLock( obj ) is not enough as it only checks the current thread.

I am trying to figure the simplest solution possible.

This is not a duplicate because:

I cannot use higher-level/newer concurrency/locking mechanisms. I cannot use Lock, etc. I must use low-level/old/traditional currency/locking mechanisms such as synchronized, wait(), etc.

I am not trying to find a time to execute code when has monitor has become unlocked. I am trying to execute code when a monitor is locked.
In fact, to give a little bit of background, this part of a unit test where I am trying to start run two threads which both need to lock the same object.

I cannot call internal private JVM dependent methods such as sun.* .

As a result, in order to test for correct handling of concurrency. I need to

Create the two threads.

Start thread 1 .

As soon as thread 1 owns the monitor, suspend thread 1 .

Start thread 2 .

As soon as thread 2 is blocked by thread 1, suspend thread 2 .

Resume thread 1 .

Join thread 1 .

Run some assertions.

Resume thread 2 .

Join thread 2 .

Run some assertions.

What I am trying to figure out is the best way to do #3, primarily, determining when thread 1 owns the monitor.

答:
Your original question was how to check if any thread owns a lock. The ThreadMxBean should help you out. You can obtain an instance by calling

```<code>ManagementFactory.getThreadMXBean()
</code>```

You should first check if you platform supports monitoring of object monitor usage by calling isObjectMonitorUsageSupported. If that is the case you can get information about all threads including lock info by calling

```<code>ManagementFactory.getThreadMXBean().dumpAllThreads(true,true)
</code>```

This returns an array of ThreadInfo objects on which you can call the getLockedMonitors method which will give you hints on the locked objects, namely the result of calling System.identityHashCode on that object which should uniquely identify that object. Pretty clunky alltogether but at least a way to go.

Apart from the virtual answer to your question I don't think your approach is a sensible one. Your original goal is still not clear to me why I can't give you conrete advise. Maybe you should investigate best practices on testing multithreading?

ContentLicense: CC BY-SA 3.0

Body:
Your original question was how to check if any thread owns a lock. The ThreadMxBean should help you out. You can obtain an instance by calling

ManagementFactory.getThreadMXBean()

You should first check if you platform supports monitoring of object monitor usage by calling isObjectMonitorUsageSupported. If that is the case you can get information about all threads including lock info by calling

ManagementFactory.getThreadMXBean().dumpAllThreads(true,true)

This returns an array of ThreadInfo objects on which you can call the getLockedMonitors method which will give you hints on the locked objects, namely the result of calling System.identityHashCode on that object which should uniquely identify that object. Pretty clunky alltogether but at least a way to go.

Apart from the virtual answer to your question I don't think your approach is a sensible one. Your original goal is still not clear to me why I can't give you conrete advise. Maybe you should investigate best practices on testing multithreading?


问:
Not getting the object values or formcollection values
I'm trying to verify user's login verification in MVC. I used a pop-up where it displays two forms as 1 for login and one for Register. I'm unable to get the object values or text box values of user inputs(username & password) even though its hitting the controller.

```<code>        [HttpPost]
    public ActionResult CheckUser(UserInfo obj)
    {

        int res = udaObj.CheckUser(obj.UserName, obj.Password);
        if (res >= 1)
        {
            return RedirectToAction("Appointment", "Home");
        }
        else
        {
            //For testing purpose
            return RedirectToAction("Appointment", "Home");
        }

    }
</code>```

My cshtml is as follows :

```<code>                    @using (Html.BeginForm("RegisterUser", "Home", FormMethod.Post, new { id = "regForm" }))
                {

                    <div class="tab-pane fade" id="signup">
                        <fieldset>
                            <!-- Sign Up Form -->
                            <!-- Text input-->
                            <div class="control-group">
                                <label class="control-label" for="Email">Email:</label>
                                <div class="controls">
                                    @Html.TextBoxFor(x => x.Email, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })
                                </div>
                            </div>

                            <!-- Text input-->
                            <div class="control-group">
                                <label class="control-label" for="userid">Alias:</label>
                                <div class="controls">
                                    @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })
                                </div>
                            </div>

                            <!-- Password input-->
                            <div class="control-group">
                                <label class="control-label" for="password">Password:</label>
                                <div class="controls">
                                    @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password" })

                                    <em>1-8 Characters</em>
                                </div>
                            </div>

                            <!-- Text input-->
                            <div class="control-group">
                                <label class="control-label" for="reenterpassword">Re-Enter Password:</label>
                                <div class="controls">
                                    <input id="reenterpassword" class="form-control" name="reenterpassword" type="password" placeholder="********" class="input-large" required="">
                                </div>
                            </div>

                            <!-- Button -->
                            <div class="control-group">
                                <label class="control-label" for="confirmsignup"></label>
                                <div class="controls">
                                    <button id="btnconfirmsignup" type="submit" name="signin" class="btn btn-success">Sign Up</button>
                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                                </div>
                            </div>
                        </fieldset>
                    </div>

                }

                @using (Html.BeginForm("CheckUser", "Home", FormMethod.Post, new { id = "loginForm" }))
                {
                    <div class="tab-pane fade active in" id="signin">
                        <fieldset>
                            <!-- Sign In Form -->
                            <!-- Text input-->
                            <div class="control-group">
                                <label class="control-label" for="userid">Alias:</label>
                                <div class="controls">
                                   @* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*@
                                     @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })
                                </div>
                            </div>

                            <!-- Password input-->
                            <div class="control-group">
                                <label class="control-label" for="passwordinput">Password:</label>
                                <div class="controls">
                                    @*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*@
                                     @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password"  })
                                </div>
                            </div>

                            <!-- Multiple Checkboxes (inline) -->
                            <div class="control-group">
                                <label class="control-label" for="rememberme"></label>
                                <div class="controls">
                                    <label class="checkbox inline" for="rememberme-0">
                                        <input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
                                        Remember me
                                    </label>
                                </div>
                            </div>

                          <div class="control-group">
                                <label class="control-label" for="confirmsignup"></label>
                                <div class="controls">
                                    <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>
                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                                </div>
                            </div>
                        </fieldset>
                    </div>
                }
</code>```

UserInfo.cs

```<code>    public class UserInfo
{

    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool Gender { get; set; }
    public DateTime? Dob { get; set; }
    public string PhNumber { get; set; }
    public string ImagePath { get; set; }
    public DateTime? RegDate { get; set; }
    public string Email { get; set; }
}
</code>```

答:
I do not see anything wrong with your code.

But what I can guess is that your controller does not follow the naming convention of controllers. Your controller name should have a "Controller" suffix.

In your case it should be

```<code>public class HomeController : Controller
{
....
}
</code>```

Let me know if that helps

Body:
I'm trying to verify user's login verification in MVC. I used a pop-up where it displays two forms as 1 for login and one for Register. I'm unable to get the object values or text box values of user inputs(username & password) even though its hitting the controller.

        [HttpPost]
    public ActionResult CheckUser(UserInfo obj)
    {

        int res = udaObj.CheckUser(obj.UserName, obj.Password);
        if (res >= 1)
        {
            return RedirectToAction("Appointment", "Home");
        }
        else
        {
            //For testing purpose
            return RedirectToAction("Appointment", "Home");
        }

    }

My cshtml is as follows :

                    @using (Html.BeginForm("RegisterUser", "Home", FormMethod.Post, new { id = "regForm" }))
                {

                        <fieldset>

                                Email:

                                    @Html.TextBoxFor(x => x.Email, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })

                                Alias:

                                    @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })

                                Password:

                                    @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password" })

                                    1-8 Characters

                                Re-Enter Password:

                                    <input id="reenterpassword" class="form-control" name="reenterpassword" type="password" placeholder="********" class="input-large" required="">

                                    <button id="btnconfirmsignup" type="submit" name="signin" class="btn btn-success">Sign Up</button>
                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                        </fieldset>

                }

                @using (Html.BeginForm("CheckUser", "Home", FormMethod.Post, new { id = "loginForm" }))
                {

                        <fieldset>

                                Alias:

                                   @* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*@
                                     @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" })

                                Password:

                                    @*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*@
                                     @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password"  })

                                        <input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
                                        Remember me

                                    <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>
                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                        </fieldset>

                }

UserInfo.cs

    public class UserInfo
{

    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool Gender { get; set; }
    public DateTime? Dob { get; set; }
    public string PhNumber { get; set; }
    public string ImagePath { get; set; }
    public DateTime? RegDate { get; set; }
    public string Email { get; set; }
}

Body:
I do not see anything wrong with your code.

But what I can guess is that your controller does not follow the naming convention of controllers. Your controller name should have a "Controller" suffix.

In your case it should be

public class HomeController : Controller
{
....
}

Let me know if that helps


问:
Is there a way to pick a certain colour from another image source and use it without a 3rd party program?
A lot of my work in XML has many colors to choose from and I cannot seem to find an extension or plugin for Android Studio that can choose a pick a color from an image source of my own choosing and apply it within my code. I am currently using Photoshop but unfortunately, it slows down my computer.

I have been using native colors and not my own. Eg:

```<code><< ? xml version = "1.0"
encoding = "utf-8" ? >
  <
  RelativeLayout xmlns : android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/color_bg"
tools: context = "com.transcendencetech.juliospizzaprototype.SignInActivity" >

  <
  include
android: id = "@+id/header"
layout = "@layout/header"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentTop = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  RelativeLayout
android: id = "@+id/my_tabs"
android: layout_width = "match_parent"
android: layout_height = "40dp"
android: layout_below = "@id/header"
android: background = "@android:color/black" >

  <
  View
android: id = "@+id/divider_view"
android: layout_width = "1dp"
android: layout_height = "match_parent"
android: layout_centerInParent = "true"
android: layout_margin = "2dp"
android: background = "@android:color/white" / >

  <
  Button
android: id = "@+id/pizza_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true"
android: layout_toLeftOf = "@id/divider_view"
android: layout_toStartOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "textPersonName"
android: text = "List of Pizzas"
android: textColor = "@android:color/white" / >

  <
  Button
android: id = "@+id/deals_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentEnd = "true"
android: layout_alignParentRight = "true"
android: layout_toEndOf = "@id/divider_view"
android: layout_toRightOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "text"
android: text = "List of Deals"
android: textColor = "@android:color/white" / >
  <
  /RelativeLayout>

  <
  ImageView
android: id = "@+id/pizza_list_iv"
android: layout_width = "match_parent"
android: layout_height = "150dp"
android: layout_below = "@id/my_tabs"
android: scaleType = "fitXY"
android: src = "@drawable/list_pizza_header" / >

  <
  ListView
android: id = "@+id/list_view"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_below = "@id/pizza_list_iv"
android: divider = "@color/color_divider"
android: focusable = "true"
android: dividerHeight = "2dp"
android: layout_margin = "15dp" / >

  <
  include
layout = "@layout/footer"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentBottom = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  /RelativeLayout>
</code>```

答:
If you mean that you want to use an eyedropper tool to measure the hex value (e.g. #ff0000) or the RGB value (e.g. rgb(255, 0, 0)) of a specific pixel, there are many websites that allow you to do this.

For example, if you search for 'online color picker from image' on the web, many good sites come up. I use the first one that comes up on Google, Image Color Picker (you can find your own) which lets you either pick an image URL from the web or upload an image from your computer.

Hopes this helps!

Body:
A lot of my work in XML has many colors to choose from and I cannot seem to find an extension or plugin for Android Studio that can choose a pick a color from an image source of my own choosing and apply it within my code. I am currently using Photoshop but unfortunately, it slows down my computer.

I have been using native colors and not my own. Eg:

<< ? xml version = "1.0"
encoding = "utf-8" ? >
  <
  RelativeLayout xmlns : android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/color_bg"
tools: context = "com.transcendencetech.juliospizzaprototype.SignInActivity" >

  <
  include
android: id = "@+id/header"
layout = "@layout/header"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentTop = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  RelativeLayout
android: id = "@+id/my_tabs"
android: layout_width = "match_parent"
android: layout_height = "40dp"
android: layout_below = "@id/header"
android: background = "@android:color/black" >

  <
  View
android: id = "@+id/divider_view"
android: layout_width = "1dp"
android: layout_height = "match_parent"
android: layout_centerInParent = "true"
android: layout_margin = "2dp"
android: background = "@android:color/white" / >

  <
  Button
android: id = "@+id/pizza_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true"
android: layout_toLeftOf = "@id/divider_view"
android: layout_toStartOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "textPersonName"
android: text = "List of Pizzas"
android: textColor = "@android:color/white" / >

  <
  Button
android: id = "@+id/deals_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentEnd = "true"
android: layout_alignParentRight = "true"
android: layout_toEndOf = "@id/divider_view"
android: layout_toRightOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "text"
android: text = "List of Deals"
android: textColor = "@android:color/white" / >
  <
  /RelativeLayout>

  <
  ImageView
android: id = "@+id/pizza_list_iv"
android: layout_width = "match_parent"
android: layout_height = "150dp"
android: layout_below = "@id/my_tabs"
android: scaleType = "fitXY"
android: src = "@drawable/list_pizza_header" / >

  <
  ListView
android: id = "@+id/list_view"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_below = "@id/pizza_list_iv"
android: divider = "@color/color_divider"
android: focusable = "true"
android: dividerHeight = "2dp"
android: layout_margin = "15dp" / >

  <
  include
layout = "@layout/footer"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentBottom = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  /RelativeLayout>


问:
nested query doesnt work in SailsJs
I would like to make a query for retrieve "All projects, that have a specific member".

Project.js:

```<code>module.exports = {

  attributes: {

    name: {
        type: "string"
    },

    topics: {
        collection: "topic",
        via: "projects"
    },

    profesor: {
      type: 'string'
    },

    creator: {
      type: 'string'
    },

    members: {
        collection: "user",
      via: "projects"
    },

    content: {
        collection: "content",
        via: "projectData"
    }

  }
};
</code>```

User.js:

```<code>module.exports = {

  attributes: {

    projects: {
      collection:"project",
      via: "members",
      dominant: true
    },

    email: {
        type: 'email',
        required: true,
        unique: true
    },

    mat: {
      type: 'integer',
      required: true,
      unique: true
    },

    name: {
        type: 'string',
        required: true,
    },

    lastname: {
        type: 'string',
        required: true,
    },

    admin: {
      type: 'boolean'
    },

    encryptedPassword : {
        type: 'string'
    },

     toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      delete obj.encryptedPassword;
      delete obj.confirmation;
      delete obj._csrf;
      return obj;
    }

  },

  beforeValidate: function (values, next) {
    console.log(values);
    if (typeof values.admin !== 'undefined') {
      if (values.admin === 'unchecked') {
        values.admin = false;
      } else  if (values.admin[1] === 'on') {
        values.admin = true;
      }
    }
     next();
  },

  beforeCreate: function (values, next) {

    User.count().exec(function countCB(error, found) {
      if (found == 0) {
      values.admin = true;
      }
   });

    // This checks to make sure the password and password confirmation match before creating record
    if (!values.password || values.password != values.confirmation) {
      return next({err: ["Password doesn't match password confirmation."]});
    }

    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {
      if (err) return next(err);
      values.encryptedPassword = encryptedPassword;
      // values.online= true;
      next();
    });
  }

};
</code>```

and this is my query:

```<code>index: function(req,res){
        Project.find().populate('members', {name: 'Hugo'}).exec(function(err, prj){
                if (err) res.negotiate(err);
                console.log("funciona esto?");
                console.log(prj);

                res.view({
                project: prj
                });
        });
    },
</code>```

Why doesnt work? It retrives all project, anybody can help me? I am not sure if waterline allows that.

答:
Try to get the user, then populate the projects:</p>

```<code>index: function(req,res){
        User
        .find({name: 'Hugo'})
        .populate('projects')
        .exec(function(err, user){
                if (err) res.negotiate(err);
                console.log("funciona esto?");
                console.log(user.projects);

                res.view({
                project: user.projects[0] // first project
                });
        });
    },
</code>```

Title: nested query doesnt work in SailsJs

Body:
I would like to make a query for retrieve "All projects, that have a specific member".

Project.js:

module.exports = {

  attributes: {

    name: {
        type: "string"
    },

    topics: {
        collection: "topic",
        via: "projects"
    },

    profesor: {
      type: 'string'
    },

    creator: {
      type: 'string'
    },

    members: {
        collection: "user",
      via: "projects"
    },

    content: {
        collection: "content",
        via: "projectData"
    }

  }
};

User.js:

module.exports = {

  attributes: {

    projects: {
      collection:"project",
      via: "members",
      dominant: true
    },

    email: {
        type: 'email',
        required: true,
        unique: true
    },

    mat: {
      type: 'integer',
      required: true,
      unique: true
    },

    name: {
        type: 'string',
        required: true,
    },

    lastname: {
        type: 'string',
        required: true,
    },

    admin: {
      type: 'boolean'
    },

    encryptedPassword : {
        type: 'string'
    },

     toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      delete obj.encryptedPassword;
      delete obj.confirmation;
      delete obj._csrf;
      return obj;
    }

  },

  beforeValidate: function (values, next) {
    console.log(values);
    if (typeof values.admin !== 'undefined') {
      if (values.admin === 'unchecked') {
        values.admin = false;
      } else  if (values.admin[1] === 'on') {
        values.admin = true;
      }
    }
     next();
  },

  beforeCreate: function (values, next) {

    User.count().exec(function countCB(error, found) {
      if (found == 0) {
      values.admin = true;
      }
   });

    // This checks to make sure the password and password confirmation match before creating record
    if (!values.password || values.password != values.confirmation) {
      return next({err: ["Password doesn't match password confirmation."]});
    }

    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {
      if (err) return next(err);
      values.encryptedPassword = encryptedPassword;
      // values.online= true;
      next();
    });
  }

};

and this is my query:

index: function(req,res){
        Project.find().populate('members', {name: 'Hugo'}).exec(function(err, prj){
                if (err) res.negotiate(err);
                console.log("funciona esto?");
                console.log(prj);

                res.view({
                project: prj
                });
        });
    },

Why doesnt work? It retrives all project, anybody can help me? I am not sure if waterline allows that.

Body:
Try to get the user, then populate the projects:

index: function(req,res){
        User
        .find({name: 'Hugo'})
        .populate('projects')
        .exec(function(err, user){
                if (err) res.negotiate(err);
                console.log("funciona esto?");
                console.log(user.projects);

                res.view({
                project: user.projects[0] // first project
                });
        });
    },


问:
Spark: Get top N by key
Say I have a PairRDD as such (Obviously much more data in real life, assume millions of records):

```<code>val scores = sc.parallelize(Array(
      ("a", 1),
      ("a", 2),
      ("a", 3),
      ("b", 3),
      ("b", 1),
      ("a", 4),
      ("b", 4),
      ("b", 2)
))
</code>```

What is the most efficient way to generate a RDD with the top 2 scores per key?

```<code>val top2ByKey = ...
res3: Array[(String, Int)] = Array((a,4), (a,3), (b,4), (b,3))
</code>```

答:
Slightly modified your input data.

```<code>val scores = sc.parallelize(Array(
      ("a", 1),
      ("a", 2),
      ("a", 3),
      ("b", 3),
      ("b", 1),
      ("a", 4),
      ("b", 4),
      ("b", 2),
      ("a", 6),
      ("b", 8)
    ))
</code>```

I explain how to do it step by step:

1.Group by key to create array

```<code>scores.groupByKey().foreach(println)
</code>```

Result:

```<code>(b,CompactBuffer(3, 1, 4, 2, 8))
(a,CompactBuffer(1, 2, 3, 4, 6))
</code>```

As you see, each value itself is a array of numbers. CompactBuffer is just optimised array.

2.For each key, reverse sort list of numbers that value contains

```<code>scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse)} ).foreach(println)
</code>```

Result:

```<code>(b,List(8, 4, 3, 2, 1))
(a,List(6, 4, 3, 2, 1))
</code>```

3.Keep only first 2 elements from the 2nd step, they will be top 2 scores in the list

```<code>scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).foreach(println)
</code>```

Result:

```<code>(a,List(6, 4))
(b,List(8, 4))
</code>```

4.Flat map to create new Paired RDD for each key and top score

```<code>scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).flatMap({case (k, numbers) => numbers.map(k -> _)}).foreach(println)
</code>```

Result:

```<code>(b,8)
(b,4)
(a,6)
(a,4)
</code>```

5.Optional step - sort by key if you want

```<code>scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).flatMap({case (k, numbers) => numbers.map(k -> _)}).sortByKey(false).foreach(println)
</code>```

Result:

```<code>(a,6)
(a,4)
(b,8)
(b,4)
</code>```

Hope, this explanation helped to understand the logic.

Title: Spark: Get top N by key

Body:
Say I have a PairRDD as such (Obviously much more data in real life, assume millions of records):

val scores = sc.parallelize(Array(
      ("a", 1),
      ("a", 2),
      ("a", 3),
      ("b", 3),
      ("b", 1),
      ("a", 4),
      ("b", 4),
      ("b", 2)
))

What is the most efficient way to generate a RDD with the top 2 scores per key?

val top2ByKey = ...
res3: Array[(String, Int)] = Array((a,4), (a,3), (b,4), (b,3))

Body:
Slightly modified your input data.

val scores = sc.parallelize(Array(
      ("a", 1),
      ("a", 2),
      ("a", 3),
      ("b", 3),
      ("b", 1),
      ("a", 4),
      ("b", 4),
      ("b", 2),
      ("a", 6),
      ("b", 8)
    ))

I explain how to do it step by step:

1.Group by key to create array

scores.groupByKey().foreach(println)

Result:

(b,CompactBuffer(3, 1, 4, 2, 8))
(a,CompactBuffer(1, 2, 3, 4, 6))

As you see, each value itself is a array of numbers. CompactBuffer is just optimised array.

2.For each key, reverse sort list of numbers that value contains

scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse)} ).foreach(println)

Result:

(b,List(8, 4, 3, 2, 1))
(a,List(6, 4, 3, 2, 1))

3.Keep only first 2 elements from the 2nd step, they will be top 2 scores in the list

scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).foreach(println)

Result:

(a,List(6, 4))
(b,List(8, 4))

4.Flat map to create new Paired RDD for each key and top score

scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).flatMap({case (k, numbers) => numbers.map(k -> _)}).foreach(println)

Result:

(b,8)
(b,4)
(a,6)
(a,4)

5.Optional step - sort by key if you want

scores.groupByKey().map({ case (k, numbers) => k -> numbers.toList.sorted(Ordering[Int].reverse).take(2)} ).flatMap({case (k, numbers) => numbers.map(k -> _)}).sortByKey(false).foreach(println)

Result:

(a,6)
(a,4)
(b,8)
(b,4)

Hope, this explanation helped to understand the logic.


问:
Facebook Ads API error: must be a valid custom audience id
Unlike targeting a custom audience, it seems impossible to create an ad targeting a saved audience using Facebook Ads API. Can someone confirm that is the case? What would be a workaround? This is the error I'm getting:

```<code>Error #100: Param targeting[custom_audiences][id] must be a valid custom audience id
</code>```

There is a difference between a saved audience and a custom audience. A saved audience is an audience you manually create specifying age range, geographic region and interests. While a custom audience is a list of customers you gathered (uploaded or visitors or your site etc). You can create these audiences manually through the Ads Manager interface:

Using Graph API Explorer, one can retrieve saved audiences as follow:

```<code>act_1234567890/saved_audiences
</code>```

Using Graph API Explorer, one can retrieve custom audiences as follow:

```<code>act_123456789/customaudiences
</code>```

Note that 123456789 is not my real account number. I changed it for security reasons.

So, I can retrieve IDs for both custom audiences and saved audiences and creating an ad targeting a custom audience works fine, unlike targeting a saved audience which gives the above error message.

A cumbersome workaround could be to save the flexible_spec of each saved audience locally and use that spec when creating ads. The problem with that is that some targeting segments become invalid (Facebook decides to discontinue some segments at random times) which causes Facebook Ads API to hickup. Additionally, this means I constantly need to keep saved audiences in sync with my local copy. Unless of course I retrieve the targeting of a saved audience on the fly and re-use it, each time I create an ad resulting in yet another API request.

答:
I figured it out myself. It seems impossible to directly target a saved audience unlike a custom audience, which is odd. What I did is retrieve the targeting from the saved audience first and reuse that targeting when creating the ad.

Here you see a screenshot of the official documentation showing only custom audiences and lookalike audiences can be targeted.

Retrieving targeting from saved audience (with Facebook PHP SDK):

```<code>$api = Api::instance();

use FacebookAds\Http\Request;

$response = $api->call(
  "/987654321", 'GET',
  array('fields'=>'targeting')
);
$audience = $response->getContent();
</code>```

With 987654321 as the saved audience ID.

Then copy that targeting to the ad (with Facebook PHP SDK):

```<code>use FacebookAds\Object\Targeting;
use FacebookAds\Object\Fields\TargetingFields;

$targeting = new Targeting();
$targeting->setData($audience['targeting']);
</code>```

The disadvantage of this technique is that the ad won't be updated when the saved audience is updated and that it requires an extra API call which slows down the creation of the ad.

Body:
Unlike targeting a custom audience, it seems impossible to create an ad targeting a saved audience using Facebook Ads API. Can someone confirm that is the case? What would be a workaround? This is the error I'm getting:

Error #100: Param targeting[custom_audiences][id] must be a valid custom audience id

There is a difference between a saved audience and a custom audience. A saved audience is an audience you manually create specifying age range, geographic region and interests. While a custom audience is a list of customers you gathered (uploaded or visitors or your site etc). You can create these audiences manually through the Ads Manager interface:

Using Graph API Explorer, one can retrieve saved audiences as follow:

act_1234567890/saved_audiences

Using Graph API Explorer, one can retrieve custom audiences as follow:

act_123456789/customaudiences

Note that 123456789 is not my real account number. I changed it for security reasons.

So, I can retrieve IDs for both custom audiences and saved audiences and creating an ad targeting a custom audience works fine, unlike targeting a saved audience which gives the above error message.

A cumbersome workaround could be to save the flexible_spec of each saved audience locally and use that spec when creating ads. The problem with that is that some targeting segments become invalid (Facebook decides to discontinue some segments at random times) which causes Facebook Ads API to hickup. Additionally, this means I constantly need to keep saved audiences in sync with my local copy. Unless of course I retrieve the targeting of a saved audience on the fly and re-use it, each time I create an ad resulting in yet another API request.

Body:
I figured it out myself. It seems impossible to directly target a saved audience unlike a custom audience, which is odd. What I did is retrieve the targeting from the saved audience first and reuse that targeting when creating the ad.

Here you see a screenshot of the official documentation showing only custom audiences and lookalike audiences can be targeted.

Retrieving targeting from saved audience (with Facebook PHP SDK):

$api = Api::instance();

use FacebookAds\Http\Request;

$response = $api->call(
  "/987654321", 'GET',
  array('fields'=>'targeting')
);
$audience = $response->getContent();

With 987654321 as the saved audience ID.

Then copy that targeting to the ad (with Facebook PHP SDK):

use FacebookAds\Object\Targeting;
use FacebookAds\Object\Fields\TargetingFields;

$targeting = new Targeting();
$targeting->setData($audience['targeting']);

The disadvantage of this technique is that the ad won't be updated when the saved audience is updated and that it requires an extra API call which slows down the creation of the ad.


问:
Cannot read property 'tokenizers' of undefined using Typeahead
I am using Twitter's "typeahead.js 0.11.1", but I got this error "Cannot read property 'tokenizers' of undefined".  Put my code below, please help me check what I did wrong.

```<code>paths: {
    'jquery'                : 'assets/lib/jquery.min',
    'underscore'            : 'assets/lib/underscore-min',
    'backbone'              : 'assets/lib/backbone.min',
    'marionette'            : 'assets/lib/backbone.marionette.min',
    'bootstrap'             : 'assets/lib/bootstrap.min',
    'typeahead'             : 'assets/lib/typeahead.bundle.min',
},

shim: {
    typeahead:{
        deps: ['jquery'],
        exports:'Bloodhound',
        init: function ($) {
            return require.s.contexts._.registry['typeahead.js'].factory( $                          );
        }
    }

}
</code>```

Marionette's view code as below:

```<code>    define(['jquery',   'marionette','templates', 'underscore','typeahead'],
    function $,Marionette, templates, _,Bloodhound) {
              'use strict';
          ..................
        onShow:function(){
           var tours = new Bloodhound({
              datumTokenizer: function (datum) {
                  return Bloodhound.tokenizers.whitespace(datum.value);
              },
              queryTokenizer: Bloodhound.tokenizers.whitespace,
              remote: {
                  url: '/api/infos?t=ALL',
              }
          });

          // Initialize the Bloodhound suggestion engine
          tours.initialize();
          // Instantiate the Typeahead UI
          $('.typeahead').typeahead(null, {
              displayKey: 'value',
              source: tours.ttAdapter()
          });

    },
</code>```

答: I had a similar issue with Backbone/Marionette and a RequireJS configuration. The important point to get right, is to require typeahead.jquery.js and bloodhound.js using separate files. I was using typeahead.bundle.js and it would just not work. Posting this after not a few hours of frustration.</p>

Body:
I am using Twitter's "typeahead.js 0.11.1", but I got this error "Cannot read property 'tokenizers' of undefined".  Put my code below, please help me check what I did wrong.

paths: {
    'jquery'                : 'assets/lib/jquery.min',
    'underscore'            : 'assets/lib/underscore-min',
    'backbone'              : 'assets/lib/backbone.min',
    'marionette'            : 'assets/lib/backbone.marionette.min',
    'bootstrap'             : 'assets/lib/bootstrap.min',
    'typeahead'             : 'assets/lib/typeahead.bundle.min',
},

shim: {
    typeahead:{
        deps: ['jquery'],
        exports:'Bloodhound',
        init: function ($) {
            return require.s.contexts._.registry['typeahead.js'].factory( $                          );
        }
    }

}

Marionette's view code as below:

    define(['jquery',   'marionette','templates', 'underscore','typeahead'],
    function $,Marionette, templates, _,Bloodhound) {
              'use strict';
          ..................
        onShow:function(){
           var tours = new Bloodhound({
              datumTokenizer: function (datum) {
                  return Bloodhound.tokenizers.whitespace(datum.value);
              },
              queryTokenizer: Bloodhound.tokenizers.whitespace,
              remote: {
                  url: '/api/infos?t=ALL',
              }
          });

          // Initialize the Bloodhound suggestion engine
          tours.initialize();
          // Instantiate the Typeahead UI
          $('.typeahead').typeahead(null, {
              displayKey: 'value',
              source: tours.ttAdapter()
          });

    },


问:
method to print a Credit Card Table
Can someone explain to me how works this method, I know it print a table and works well but I don't understand how it works :(
help!

```<code>class CreditCard
  attr_reader :name, :number, :expiration, :cvc
  attr_accessor :status

    def initialize(name,number,expiration,cvc,status)
      @name = name
      @number = number
      @expiration = expiration
      @cvc = cvc
      @status = status
    end

    def information
      card_information = "#{@name}", "#{@number}", "#{@expiration}", "#{@cvc}", "#{@status}"
    end

end

card_array = []
credit_card.each do |x|
  card_array << x.information
end
</code>```

THIS METHOD!!!

```<code>print "Name".center(20)," Number".center(25)," Expiration".center(20)," Cvc".center(22)," Status".center(25),"\n"
puts "___________________________________________________________________________________________________________________"
card_array.each do |x|
  x.each do |card|
    print "|",card.center(20),"|"
  end
   print "\n"
end
print "\n"
</code>```

答:
Not sure what part specifically is confusing, so apologies if this comes across as a little condescending. Let's step through this line by line:

```<code>print "Name".center(20)," Number".center(25)," Expiration".center(20)," Cvc".center(22)," Status".center(25),"\n"
</code>```

this first line calls print passing it a variable number of string arguments to print out, one after another. These string arguments are all be centered as column headers. After all the headers are output, a line break is printed beginning a new line in the output.

```<code>puts "___________________________________________________________________________________________________________________"
</code>```

This line is just for formatting, outputting a divider between the table header and contents. Since they use puts instead of print here, a new line is automatically output after the string.

```<code>card_array.each do |x|
...
end
</code>```

This block is a for each construct, so for each credit card in the card_array we will assign the card to the local variable x and then execute the code inside this block.

```<code> x.each do |card|
 ...
 end
</code>```

Again, this is a foreach construct where x is the credit card as an array of strings (see the information method). We assign each string, one at a time to card and then execute the block within.

```<code>print "|",card.center(20),"|"
</code>```

Here's another print call, where we use the variable length arguments to pass 3 parameters, the current string in card and what I assume to be table cell borders.

```<code>print "\n"
</code>```

Then we just have 2 more calls to print, at the end of each of the blocks, printing out new lines so that each credit card is on it's own row.

Having explained the block in question, I feel a source of confusion for this code possibly comes from the information method, where, it might not be immediately obvious that

```<code>card_information = "#{@name}", "#{@number}", "#{@expiration}", "#{@cvc}", "#{@status}"
</code>```

is actually creating an array of strings that are then being added to the card_array so card_array is an array of arrays that would end up looking something like

```<code>[ ["card holder name", "card number", ...], ["second card hold name", "second card number", ...], ...]
</code>```

It took me a second reading to catch that they were doing that, so figure this might be what got skipped over to make the block in question unclear (if you were thinking it was an array of CreditCard objects instead of an array of strings.)

Title: method to print a Credit Card Table

Body:
Can someone explain to me how works this method, I know it print a table and works well but I don't understand how it works :(
help!

class CreditCard
  attr_reader :name, :number, :expiration, :cvc
  attr_accessor :status

    def initialize(name,number,expiration,cvc,status)
      @name = name
      @number = number
      @expiration = expiration
      @cvc = cvc
      @status = status
    end

    def information
      card_information = "#{@name}", "#{@number}", "#{@expiration}", "#{@cvc}", "#{@status}"
    end

end

card_array = []
credit_card.each do |x|
  card_array << x.information
end

THIS METHOD!!!

print "Name".center(20)," Number".center(25)," Expiration".center(20)," Cvc".center(22)," Status".center(25),"\n"
puts "___________________________________________________________________________________________________________________"
card_array.each do |x|
  x.each do |card|
    print "|",card.center(20),"|"
  end
   print "\n"
end
print "\n"

Body:
Not sure what part specifically is confusing, so apologies if this comes across as a little condescending. Let's step through this line by line:

print "Name".center(20)," Number".center(25)," Expiration".center(20)," Cvc".center(22)," Status".center(25),"\n"

this first line calls print passing it a variable number of string arguments to print out, one after another. These string arguments are all be centered as column headers. After all the headers are output, a line break is printed beginning a new line in the output.

puts "___________________________________________________________________________________________________________________"

This line is just for formatting, outputting a divider between the table header and contents. Since they use puts instead of print here, a new line is automatically output after the string.

card_array.each do |x|
...
end

This block is a for each construct, so for each credit card in the card_array we will assign the card to the local variable x and then execute the code inside this block.

 x.each do |card|
 ...
 end

Again, this is a foreach construct where x is the credit card as an array of strings (see the information method). We assign each string, one at a time to card and then execute the block within.

print "|",card.center(20),"|"

Here's another print call, where we use the variable length arguments to pass 3 parameters, the current string in card and what I assume to be table cell borders.

print "\n"

Then we just have 2 more calls to print, at the end of each of the blocks, printing out new lines so that each credit card is on it's own row.

Having explained the block in question, I feel a source of confusion for this code possibly comes from the information method, where, it might not be immediately obvious that

card_information = "#{@name}", "#{@number}", "#{@expiration}", "#{@cvc}", "#{@status}"

is actually creating an array of strings that are then being added to the card_array so card_array is an array of arrays that would end up looking something like

[ ["card holder name", "card number", ...], ["second card hold name", "second card number", ...], ...]

It took me a second reading to catch that they were doing that, so figure this might be what got skipped over to make the block in question unclear (if you were thinking it was an array of CreditCard objects instead of an array of strings.)


问:
Axios request within /POST request on Express
As you can see below, in my server.js file I have a /POST Info request that gets called on a form submittal.

I started to get confused on reading about the different between app.post and express routes and if in anyway using routes would benefit my code here.

Within the /POST Info I have two axios requests to 2 different APIs and I think it would be wise to move the code elsewhere to make it cleaner.

Would knowing how routes work here benefit me anyway?And if you can explain the difference here that would be great.

```<code>app.post('/Info', function (req, res) {
   var State = req.body.State;
   var income = Number(req.body.income);
   var zip = req.body.ZIP;
   axios.post('https://taxee.io/api/v2/calculate/2017', {
      //data sent to Taxee.io
      "exemptions": 1
      , "filing_status": "single"
      , "pay_periods": 1
      , "pay_rate": income || 100000
      , "state": State || "NY"
   }, {
         headers: {
            'Authorization': "Bearer <API_KEY>"
            //headers
         }
   }).then(function (response) {
      var obj = {
        income: '$' + income
        , fica: response.data.annual.fica.amount
        , federal: response.data.annual.federal.amount
        , residence: State + ", " + zip
        , state: response.data.annual.state.amount
      }
      axios.get("https://www.quandl.com/api/v3/datasets/ZILL/Z" + zip + "_RMP.json?api_key=<API_KEY>").then(function (response) {
         var monthRent = response.data.dataset.data[0][1]
         obj.rent = monthRent
         obj.yearlyRent = Number(monthRent) * 12;
      }).then(function (response) {
         res.send(obj);
      });
  }).catch(function (error) {
      alert('error');
  });
}
</code>```

答:
There are two ways to define routes in an Express application:

Use the Express application (app) object directly:

```<code>const express = require('express')
const app = express()

app.post(...)
app.get(...)
app.put(...)
// and so on
</code>```

Or use the router object:

```<code>const express = require('express')
const app = express()
const router = express.Router()

router.post(...)
router.get(...)
router.put(...)
// and so on

app.use(router)
</code>```

My guess is that you've been reading about the latter snippet of code with the router object. Using Express' Router object can indeed make code cleaner to read as there more of a separation of concerns.

There's nothing wrong with calling an external API from your own API. For example, in a project of mine, I call the Google Calendar API on this line. The only difference between mine is yours is that I used the Google APIs Node.js Client while you used standard HTTP requests. I could have certainly used HTTP requests as shown here.

Your code is fine, but can be improved. For example, instead of:

```<code>axios.post('...', {
  exemptions: 1,
  filing_status: 'single',
  pay_periods: 1,
  pay_rate: income || 100000,
  state: State || 'NY'
})
</code>```

You could call an helper function that prepares the options object:

```<code>function prepareOptions (state = 'NY', income = 100000) {
  return {
    exemptions: 1,
    filing_status: 'single',
    pay_periods: 1,
    pay_rate: income,
    state: State
  }
}
</code>```

Then call it like so:

```<code>axios.post('...', prepareOptions(State, income))
</code>```

This makes for more readable code.

Finally, there is no reason to use axios on the server side. Simply use Node's built in HTTP module.

Body:
As you can see below, in my server.js file I have a /POST Info request that gets called on a form submittal.

I started to get confused on reading about the different between app.post and express routes and if in anyway using routes would benefit my code here.

Within the /POST Info I have two axios requests to 2 different APIs and I think it would be wise to move the code elsewhere to make it cleaner.

Would knowing how routes work here benefit me anyway?And if you can explain the difference here that would be great.

app.post('/Info', function (req, res) {
   var State = req.body.State;
   var income = Number(req.body.income);
   var zip = req.body.ZIP;
   axios.post('https://taxee.io/api/v2/calculate/2017', {
      //data sent to Taxee.io
      "exemptions": 1
      , "filing_status": "single"
      , "pay_periods": 1
      , "pay_rate": income || 100000
      , "state": State || "NY"
   }, {
         headers: {
            'Authorization': "Bearer <API_KEY>"
            //headers
         }
   }).then(function (response) {
      var obj = {
        income: '$' + income
        , fica: response.data.annual.fica.amount
        , federal: response.data.annual.federal.amount
        , residence: State + ", " + zip
        , state: response.data.annual.state.amount
      }
      axios.get("https://www.quandl.com/api/v3/datasets/ZILL/Z" + zip + "_RMP.json?api_key=<API_KEY>").then(function (response) {
         var monthRent = response.data.dataset.data[0][1]
         obj.rent = monthRent
         obj.yearlyRent = Number(monthRent) * 12;
      }).then(function (response) {
         res.send(obj);
      });
  }).catch(function (error) {
      alert('error');
  });
}

Body:
There are two ways to define routes in an Express application:

Use the Express application (app) object directly:

const express = require('express')
const app = express()

app.post(...)
app.get(...)
app.put(...)
// and so on

Or use the router object:

const express = require('express')
const app = express()
const router = express.Router()

router.post(...)
router.get(...)
router.put(...)
// and so on

app.use(router)

My guess is that you've been reading about the latter snippet of code with the router object. Using Express' Router object can indeed make code cleaner to read as there more of a separation of concerns.

There's nothing wrong with calling an external API from your own API. For example, in a project of mine, I call the Google Calendar API on this line. The only difference between mine is yours is that I used the Google APIs Node.js Client while you used standard HTTP requests. I could have certainly used HTTP requests as shown here.

Your code is fine, but can be improved. For example, instead of:

axios.post('...', {
  exemptions: 1,
  filing_status: 'single',
  pay_periods: 1,
  pay_rate: income || 100000,
  state: State || 'NY'
})

You could call an helper function that prepares the options object:

function prepareOptions (state = 'NY', income = 100000) {
  return {
    exemptions: 1,
    filing_status: 'single',
    pay_periods: 1,
    pay_rate: income,
    state: State
  }
}

Then call it like so:

axios.post('...', prepareOptions(State, income))

This makes for more readable code.

Finally, there is no reason to use axios on the server side. Simply use Node's built in HTTP module.


问:
Place frame when taking photo Android Studio
I want to develop an application that takes a photograph and allows you to select a frame for photography.

I already have developed the interfaces, like taking the photo and storing it.

But I put a frame to the photo taken I could not.

Any recommendation?

答:
In what format do you store taken photos and your frame images? If you plan to insert your picture into a simple frame, I'd suggest to first draw your taken picture on a Canvas, and then draw your frame over it. Keep in mind the sizing - you don't want your picture be too small or too big.

I'm providing an example snippet here:

```<code>public Bitmap Output(Bitmap takenPhoto, Bitmap frameImage)
{
    int width, height, x, y;
    height = ### // your desired height of the whole output image
    width = ### // your desired width of the whole output image
    x = ### // specify indentation for the picture
    y = ###

    Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(result);
    Paint paint = new Paint();

    c.drawBitmap(takenPhoto, x, y, paint); // draw your photo over canvas, keep indentation in mind (x and y)
    c.drawBitmap(frameImage, 0, 0, paint); // now draw your frame on top of the image

    return result;
}
</code>```

Keep in mind that I have not tested the code and you might (actually, you'll have to) apply corrections.

Body:
In what format do you store taken photos and your frame images? If you plan to insert your picture into a simple frame, I'd suggest to first draw your taken picture on a Canvas, and then draw your frame over it. Keep in mind the sizing - you don't want your picture be too small or too big.

I'm providing an example snippet here:

public Bitmap Output(Bitmap takenPhoto, Bitmap frameImage)
{
    int width, height, x, y;
    height = ### // your desired height of the whole output image
    width = ### // your desired width of the whole output image
    x = ### // specify indentation for the picture
    y = ###

    Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(result);
    Paint paint = new Paint();

    c.drawBitmap(takenPhoto, x, y, paint); // draw your photo over canvas, keep indentation in mind (x and y)
    c.drawBitmap(frameImage, 0, 0, paint); // now draw your frame on top of the image

    return result;
}

Keep in mind that I have not tested the code and you might (actually, you'll have to) apply corrections.


答:
Step #1: Define one or more color resources, such as in res/values/colors.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="primary">#3f51b5</color>
  <color name="primary_dark">#1a237e</color>
  <color name="accent">#ffee58</color>
</resources>
</code>```

Step #2: Click the color swatch that appears in the resource editor gutter, to the left of the resource:

Clicking that swatch will bring up a color-picker dialog:

Step #3: Click the eyedropper tool, to the left of the color swatch bar in that dialog. This will bring up your typical sort of eyedropper view that follows your mouse pointer. Hover over the color you want to pick up, then click the left mouse button. Back in the dialog, click Choose to update the color resource to use that picked color.

Step #4: In your layout, use @color/whatever_name_you_give_it to reference the color, where whatever_name_you_give_it is whatever name you give it.

Title: Is there a way to pick a certain colour from another image source and use it without a 3rd party program?

Body:
Step #1: Define one or more color resources, such as in res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="primary">#3f51b5</color>
  <color name="primary_dark">#1a237e</color>
  <color name="accent">#ffee58</color>
</resources>

Step #2: Click the color swatch that appears in the resource editor gutter, to the left of the resource:

Clicking that swatch will bring up a color-picker dialog:

Step #3: Click the eyedropper tool, to the left of the color swatch bar in that dialog. This will bring up your typical sort of eyedropper view that follows your mouse pointer. Hover over the color you want to pick up, then click the left mouse button. Back in the dialog, click Choose to update the color resource to use that picked color.

Step #4: In your layout, use @color/whatever_name_you_give_it to reference the color, where whatever_name_you_give_it is whatever name you give it.


问:
jQuery autocomplete list not showing up
I have the following code but and its return data but the problem is ui-list is not showing/populating up I don't know what I am doing wrong?

javascript

```<code>$("input#ProdDesc").autocomplete({
  autoFocus: true,
  source: "includes/modProducts/search-products.php",
  minLength: 1,
  select: function(event, ui) {
    var item = ui.item;
    if (item) {
      $(this).closest('.row').find('input#ProdDesc').val(item.prod_name);
      $(this).closest('.row').find('input#prodctCode').val(item.prod_code);

    }
  }
});
</code>```

Returning Data from PHP

```<code>[{
  "prod_code": "SPC-00001",
  "prod_name": "Testing Product Name1"
}, {
  "prod_code": "SPC-00002",
  "prod_name": "Product Name Again "
}]
</code>```

ui-list items are showing like this:

答:
According to Terry's comment, your url should respond with the appropriate format:

```<code>[{label: "Testing Product Name1", value: "SPC-00001"}]
</code>```

In case you can't modify the response of your URL, you can try this:

$(function() {
  $("input#ProdDesc").on("keypress", function() {
    $.ajax({
      url: "https://gist.githubusercontent.com/dannyjhonston/f4ffea60e7dc86a2d8dadfe477870294/raw/aec441e65a6e9e535feef16b9e970b4276baf346/products.json",
      type: "GET"
    }).done(function(response) {
      // response = [{"prod_code":"SPC-00001","prod_name":"Testing Product Name1"},{"prod_code":"SPC-00002","prod_name":"Product Name Again"}].
      var result = [],
        i, data = JSON.parse(response),
        len = data.length;
      for (i = 0; i < len; i++) {
        result.push({
          label: data[i].prod_name,
          value: data[i].prod_code
        });
      }

      // result = [{"label":"Testing Product Name1","value":"SPC-00001"},{"label":"Product Name Again","value":"SPC-00002"}].
      $("input#ProdDesc").autocomplete({
        autoFocus: true,
        source: result,
        minLength: 1,
        select: function(event, ui) {
          var item = ui.item;
          if (item) {
            console.log(item);
          }
        }
      });
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper .as-console {
  background: linear-gradient(#fff, #818eb3);
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<input id="ProdDesc" type="text" />```

Title: jQuery autocomplete list not showing up

Body:
I have the following code but and its return data but the problem is ui-list is not showing/populating up I don't know what I am doing wrong?

javascript

$("input#ProdDesc").autocomplete({
  autoFocus: true,
  source: "includes/modProducts/search-products.php",
  minLength: 1,
  select: function(event, ui) {
    var item = ui.item;
    if (item) {
      $(this).closest('.row').find('input#ProdDesc').val(item.prod_name);
      $(this).closest('.row').find('input#prodctCode').val(item.prod_code);

    }
  }
});

Returning Data from PHP

[{
  "prod_code": "SPC-00001",
  "prod_name": "Testing Product Name1"
}, {
  "prod_code": "SPC-00002",
  "prod_name": "Product Name Again "
}]

ui-list items are showing like this:

Body:
According to Terry's comment, your url should respond with the appropriate format:

[{label: "Testing Product Name1", value: "SPC-00001"}]

In case you can't modify the response of your URL, you can try this:

$(function() {
  $("input#ProdDesc").on("keypress", function() {
    $.ajax({
      url: "https://gist.githubusercontent.com/dannyjhonston/f4ffea60e7dc86a2d8dadfe477870294/raw/aec441e65a6e9e535feef16b9e970b4276baf346/products.json",
      type: "GET"
    }).done(function(response) {
      // response = [{"prod_code":"SPC-00001","prod_name":"Testing Product Name1"},{"prod_code":"SPC-00002","prod_name":"Product Name Again"}].
      var result = [],
        i, data = JSON.parse(response),
        len = data.length;
      for (i = 0; i < len; i++) {
        result.push({
          label: data[i].prod_name,
          value: data[i].prod_code
        });
      }

      // result = [{"label":"Testing Product Name1","value":"SPC-00001"},{"label":"Product Name Again","value":"SPC-00002"}].
      $("input#ProdDesc").autocomplete({
        autoFocus: true,
        source: result,
        minLength: 1,
        select: function(event, ui) {
          var item = ui.item;
          if (item) {
            console.log(item);
          }
        }
      });
    });
  });
});

.as-console-wrapper .as-console {
  background: linear-gradient(#fff, #818eb3);
}

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<input id="ProdDesc" type="text" />


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答: You might be writing a web-based application for a large company that could involve hundreds of thousands of objects of many different classes. You want to write all the business logic in object-oriented code, but these objects need persisting to an SQL database. Using ORM means you don't have to worry about how to convert to and from SQL, but can instead concentrate on implementing the actual application.</p>


问:
WF4 re-hosted in WPF : Loading saved workflows does not work with the published application
I downloaded this  Workfloff project by Ron Jacobs. It is a simple solution with three (Activity, ActivityDesigner and a WPF Rehosted) projects.

In debug mode, everything runs perfectly. But after I publish the project with ClickOnce, I can not load any saved XAML workflow files with the published application!? The message "Could not generate view" appears in the designer and I get the error message "The component 'MyActivityLibrary.Designer' does not have a resource identified by the URI '/MyActivityLibrary.Design;component/myactivitydesigner.xaml'". But actually the URI is in theere <sap:ActivityDesigner x:Class="MyActivityLibrary.Design.MyActivityDesigner". I must mention that this error only occurs with workflows which has their own custom designer.

答: The solution Ive found was to merge both Activity libraries into one library class. Now I have one Activity library with all the activities together with the  designers. And one WPF application library. </p>


问:
Unexpected output of pandas df.corr method
I am working on an exercise where I need to define with the Pearson's method (df.corr) of the panda's 0.18.1 library the correlation between two columns in a dataframe.

The problem is that I was continuously not getting the answer and after some basic debugging I came up with the below paradox.

As you can see, I try to correlate the Energy Supply per Capita with itself that must give 1.0 as the answer but instead it outputs what you can see below. I tried then to determine whether it is indeed empty and it is not. I don't know what to do and any help would be kindly accepted!

答:
The problem is that something is off with your Energy Supply per Capita data; perhaps you have non-numeric data in the column or an empty column. It's hard to know without seeing how you built the Top15 DataFrame.

(Incidentally, I took the same course as the one you are doing, so I'll give you unrelated advice: That question can be answered in as few as four lines!)


问:
Express Router GET request console.log shows undefined request parameters
I've looked on SO for an identical questions, since I feel this is a pretty simple error on my part, but the closest thing I've found is this link. I'm learning Node.JS, and am writing a relatively simple endpoint to receive get requests for a certain artist:

```<code>router.get("/:artistID", (req, res) => {
  console.log(req.params);
  console.log(req.params.artistId);
  res.send(req.params);
})
</code>```

What I expect to see is 1), a JSON object with { artistID: "whatIsent"}, 2) a "whatIsent", and then 3) the same JSON object as a response when I use an API testing utility such as Postman.

Results 1) and 3) occur as expected, but here's what I see in my console:

```<code>{ artistID: 'whatIsent' }
undefined
</code>```

Here is the GET request I send:
http://localhost:8080/artists/whatIsent.

What exactly is going on? Is Express translating artistId into some intermediate object that is not a string?

Edit: I used typeof req.params.artistId, and it also returns undefined...

答: You are defining the variable as artistID and trying to get artistId. Parameters are case sensitive.

Body:
I've looked on SO for an identical questions, since I feel this is a pretty simple error on my part, but the closest thing I've found is this link. I'm learning Node.JS, and am writing a relatively simple endpoint to receive get requests for a certain artist:

router.get("/:artistID", (req, res) => {
  console.log(req.params);
  console.log(req.params.artistId);
  res.send(req.params);
})

What I expect to see is 1), a JSON object with { artistID: "whatIsent"}, 2) a "whatIsent", and then 3) the same JSON object as a response when I use an API testing utility such as Postman.

Results 1) and 3) occur as expected, but here's what I see in my console:

{ artistID: 'whatIsent' }
undefined

Here is the GET request I send:
http://localhost:8080/artists/whatIsent.

What exactly is going on? Is Express translating artistId into some intermediate object that is not a string?

Edit: I used typeof req.params.artistId, and it also returns undefined...


问:
Python Regex : substring date from string
Can someone help me providing correct regex. I want to remove date from a string.

Ex string : IO_SE_SOURCE_2015-01-30T19_14_59 I want to remove the date part in the string and fetch only IO_SE_SOURCE as the result

I am doing this in python using re.sub() def.

So, when I do the below command

```<code>var=re.sub(regexpattern,repl,"POC_LN_SOURCE_2015-01-30T19_14_59.something")
</code>```

var should contain the value POC_LN_SOURCE

-Thanks

答:
There's no need for re.sub, just capture a group from a match:

```<code>>>> re.match(r'(.+)_\d{4}-\d{2}-\d{2}', 'POC_LN_SOURCE_2015-01-30T19_14_59.something').group(1)
'POC_LN_SOURCE'
</code>```

Body:
Can someone help me providing correct regex. I want to remove date from a string.

Ex string : IO_SE_SOURCE_2015-01-30T19_14_59 I want to remove the date part in the string and fetch only IO_SE_SOURCE as the result

I am doing this in python using re.sub() def.

So, when I do the below command

var=re.sub(regexpattern,repl,"POC_LN_SOURCE_2015-01-30T19_14_59.something")

var should contain the value POC_LN_SOURCE

-Thanks

Body:
There's no need for re.sub, just capture a group from a match:

>>> re.match(r'(.+)_\d{4}-\d{2}-\d{2}', 'POC_LN_SOURCE_2015-01-30T19_14_59.something').group(1)
'POC_LN_SOURCE'


问:
Angular 2 shared service to pass data to component-to-component
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

```<code><ol>
  <li (click)="selectShow(list.show)" [routerLink]="['/details', list.id]" *ngFor="let list of shows">{{list.show}}
  </li>
</ol>
</code>```

landingpage.component.ts

```<code>import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}
</code>```

The above sends the list.show value to my:

title.service.ts

```<code>// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}
</code>```

And here is how I manage the routing in my:

app-routing.module.ts

```<code>import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})
</code>```

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

答:
Make the title a public property of the service like this:

```<code>// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  selectedTitle: string;

  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    this.selectedTitle = title;
    return title;   // No need to return it.
  }
}
</code>```

Then any other component can inject this service and access this.titleService.selectedTitle

Body:
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

{{list.show}}

landingpage.component.ts

import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}

The above sends the list.show value to my:

title.service.ts

// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}

And here is how I manage the routing in my:

app-routing.module.ts

import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

Body:
Make the title a public property of the service like this:

// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  selectedTitle: string;

  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    this.selectedTitle = title;
    return title;   // No need to return it.
  }
}

Then any other component can inject this service and access this.titleService.selectedTitle


问:
In Python, have json not escape a string
I am caching some JSON data, and in storage it is represented as a JSON-encode string. No work is performed on the JSON by the server before sending it to the client, other than collation of multiple cached objects, like this:

```<code>def get_cached_items():
  item1 = cache.get(1)
  item2 = cache.get(2)
  return json.dumps(item1=item1, item2=item2, msg="123")
</code>```

There may be other items included with the return value, in this case represented by msg="123".

The issue is that the cached items are double-escaped. It would behoove the library to allow a pass-through of the string without escaping it.

I have looked at the documentation for json.dumps default argument, as it seems to be the place where one would address this, and searched on google/SO but found no useful results.

It would be unfortunate, from a performance perspective, if I had to decode the JSON of each cached items to send it to the browser. It would be unfortunate from a complexity perspective to not be able to use json.dumps.

My inclination is to write a class that stores the cached string and when the default handler encounters an instance of this class it uses the string without perform escaping. I have yet to figure out how to achieve this though, and I would be grateful for thoughts and assistance.

EDIT For clarity, here is an example of the proposed default technique:

```<code>class RawJSON(object):
   def __init__(self, str):
       self.str = str

class JSONEncoderWithRaw(json.JSONEncoder):
   def default(self, o):
       if isinstance(o, RawJSON):
          return o.str # but avoid call to `encode_basestring` (or ASCII equiv.)
       return super(JSONEncoderWithRaw, self).default(o)
</code>```

Here is a degenerate example of the above:

```<code>>>> class M():
       str = ''
>>> m = M()
>>> m.str = json.dumps(dict(x=123))
>>> json.dumps(dict(a=m), default=lambda (o): o.str)
'{"a": "{\\"x\\": 123}"}'
</code>```

The desired output would include the unescaped string m.str, being:

```<code>'{"a": {"x": 123}}'
</code>```

It would be good if the json module did not encode/escape the return of the default parameter, or if same could be avoided. In the absence of a method via the default parameter, one may have to achieve the objective here by overloading the encode and iterencode method of JSONEncoder, which brings challenges in terms of complexity, interoperability, and performance.

答:
You can use the better maintained simplejson instead of json which provides this functionality.

```<code>import simplejson as json
from simplejson.encoder import RawJSON

print(json.dumps([1, RawJSON(u'["abc", 2]'), u'["def", 3]']))
# -> [1, ["abc", 2], "[\"def\", 3]"]
</code>```

You get simplicity of code, plus all the C optimisations of simplejson.

Body:
I am caching some JSON data, and in storage it is represented as a JSON-encode string. No work is performed on the JSON by the server before sending it to the client, other than collation of multiple cached objects, like this:

def get_cached_items():
  item1 = cache.get(1)
  item2 = cache.get(2)
  return json.dumps(item1=item1, item2=item2, msg="123")

There may be other items included with the return value, in this case represented by msg="123".

The issue is that the cached items are double-escaped. It would behoove the library to allow a pass-through of the string without escaping it.

I have looked at the documentation for json.dumps default argument, as it seems to be the place where one would address this, and searched on google/SO but found no useful results.

It would be unfortunate, from a performance perspective, if I had to decode the JSON of each cached items to send it to the browser. It would be unfortunate from a complexity perspective to not be able to use json.dumps.

My inclination is to write a class that stores the cached string and when the default handler encounters an instance of this class it uses the string without perform escaping. I have yet to figure out how to achieve this though, and I would be grateful for thoughts and assistance.

EDIT For clarity, here is an example of the proposed default technique:

class RawJSON(object):
   def __init__(self, str):
       self.str = str

class JSONEncoderWithRaw(json.JSONEncoder):
   def default(self, o):
       if isinstance(o, RawJSON):
          return o.str # but avoid call to `encode_basestring` (or ASCII equiv.)
       return super(JSONEncoderWithRaw, self).default(o)

Here is a degenerate example of the above:

>>> class M():
       str = ''
>>> m = M()
>>> m.str = json.dumps(dict(x=123))
>>> json.dumps(dict(a=m), default=lambda (o): o.str)
'{"a": "{\\"x\\": 123}"}'

The desired output would include the unescaped string m.str, being:

'{"a": {"x": 123}}'

It would be good if the json module did not encode/escape the return of the default parameter, or if same could be avoided. In the absence of a method via the default parameter, one may have to achieve the objective here by overloading the encode and iterencode method of JSONEncoder, which brings challenges in terms of complexity, interoperability, and performance.

Body:
You can use the better maintained simplejson instead of json which provides this functionality.

import simplejson as json
from simplejson.encoder import RawJSON

print(json.dumps([1, RawJSON(u'["abc", 2]'), u'["def", 3]']))
# -> [1, ["abc", 2], "[\"def\", 3]"]

You get simplicity of code, plus all the C optimisations of simplejson.


问:
Setting windows wallpaper with python not working
The following bit of python code is supposed to download an BMP image from the web and save it to disk, then change the wallpaper to the downloaded image. The wallpaper change is supposed to be permanent ie not revert back after restart. This function is part of a larger script that I am compiling into a binary exe using pyinstaller. The problem is that when I run the program the bit that is supposed to change the wallpaper is not working and I am at wits end trying to figure out why. The funny thing is if I run this exact code in the python interpreter it works as expected. Also, in a previous version of the compiled script, the wallpaper change worked without a hitch. Any comments, help, insights would be greatly appreciated!</p>

```<code>def wallpaper():
    try:
        os.chdir(launch_directory)
        urllib.urlretrieve('http://www.imagehost.com/image.bmp', 'image.bmp')
        ctypes.windll.user32.SystemParametersInfoA(20, 0, os.path.join(launch_directory, "image.bmp"), 1)
    except:
        pass
</code>```

答:
Yes, I am aware that I'm digging this thread from the 2014 (wow!), but having encountered the same problem, I've spent hours figuring out the solution and here it is:
As .SystemParametersInfoW was leaving me with a black desktop, I've decided to stick with .SystemParametersInfoA but encode the path variable to us-ascii with a use of the cgi module. I wrote the following function which finally worked like a charm:

```<code>import ctypes as c
import cgi
def set_as_wallpaper(path):
    SPI = 20
    SPIF = 2
    return c.windll.user32.SystemParametersInfoA(SPI, 0, path.encode("us-ascii"), SPIF)
</code>```

Hope it helps!

Body:
The following bit of python code is supposed to download an BMP image from the web and save it to disk, then change the wallpaper to the downloaded image. The wallpaper change is supposed to be permanent ie not revert back after restart. This function is part of a larger script that I am compiling into a binary exe using pyinstaller. The problem is that when I run the program the bit that is supposed to change the wallpaper is not working and I am at wits end trying to figure out why. The funny thing is if I run this exact code in the python interpreter it works as expected. Also, in a previous version of the compiled script, the wallpaper change worked without a hitch. Any comments, help, insights would be greatly appreciated!

def wallpaper():
    try:
        os.chdir(launch_directory)
        urllib.urlretrieve('http://www.imagehost.com/image.bmp', 'image.bmp')
        ctypes.windll.user32.SystemParametersInfoA(20, 0, os.path.join(launch_directory, "image.bmp"), 1)
    except:
        pass

Body:
Yes, I am aware that I'm digging this thread from the 2014 (wow!), but having encountered the same problem, I've spent hours figuring out the solution and here it is:
As .SystemParametersInfoW was leaving me with a black desktop, I've decided to stick with .SystemParametersInfoA but encode the path variable to us-ascii with a use of the cgi module. I wrote the following function which finally worked like a charm:

import ctypes as c
import cgi
def set_as_wallpaper(path):
    SPI = 20
    SPIF = 2
    return c.windll.user32.SystemParametersInfoA(SPI, 0, path.encode("us-ascii"), SPIF)

Hope it helps!


问:
Angular 2 Router: Navigating to other components
Given the root routing module

```<code>const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

and the users routing module

```<code>const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);
</code>```

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent.

But, instead of using

```<code>this._router.navigate(['admittance', id]); // ERROR
</code>```

i rather have to use

```<code>this._router.navigate(['users/admittance', id]); // WORKS
</code>```

Can somebody explain why the first example is not working and why the second one fixes it?

答:
It's pretty simple
The appRoutes is the main route , the users route is a child of your Main Route .
Since you defined the name of the path in your appRoutes as 'users'  , that's going to be your first url parameter so  domain.com/users/childRoutes ...

Now as you have defined the child called admitance thats going to be prefixed by your parent Route  users /  so domain.com/users/admitance

It would have worked the first statement if you would have defined the route 'admitance' in your appRoutes

Body:
Given the root routing module

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

and the users routing module

const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent.

But, instead of using

this._router.navigate(['admittance', id]); // ERROR

i rather have to use

this._router.navigate(['users/admittance', id]); // WORKS

Can somebody explain why the first example is not working and why the second one fixes it?