问:
How to Make Player Walk Up Hills in Unity
Hey guys so im making a 2D Platformer and ran into a difficult situation. Up until now I have had rectangular landscapes for the player to jump and walk on. Now I want to start adding some hills. Picture a triangle, the left side is representing a hill at which the player can walk up. Ive made the landscape as well as copied over the Box Collider 2D from my other paths. I figured out a way to rotate the collider so that it goes up at a 45 degree angle just like the slope of the triangle. For some reason though when I walk into the triangle the player doesnt start walking up it. I have to jump onto the hill and he lands on what looks like an invisible rectangle! I make the collider .25 in thickness so I know that I have the whole collider where I want it. Any idea why? I dont really have any code for this as everything Im doing has pretty much been in scene view. Thanks everyone!

Here is the Player in Play Mode, stands on top of hill by some force:

Here is what the collider looks like in scene view. Ive moved the collider all over and it still does the same thing:

Here is my movement code:

```<code>public class Player : MonoBehaviour {

    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    void Start () {

        rb2d = gameObject.GetComponent<Rigidbody2D>();
        anim = gameObject.GetComponent<Animator>();
    }

    void Update () {

        anim.SetBool("Grounded",grounded);
        anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));

        if (Input.GetAxis("Horizontal") < -0.1)
        {
            transform.localScale = new Vector3(-1, 1, 1);

        }
        if (Input.GetAxis("Horizontal") > 0.1)
        {
            transform.localScale = new Vector3(1, 1, 1);

        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.AddForce(Vector2.up * jumpPower);

        }

    }

    void FixedUpdate() {

        Vector3 easeVelocity = rb2d.velocity;
        easeVelocity.y = rb2d.velocity.y;
        easeVelocity.z = 0.0f;
        easeVelocity.x *= 0.75f;

        float h = Input.GetAxis("Horizontal");

        //Fake friction / Easing the x speed of our player
        if (grounded)
        {

            rb2d.velocity = easeVelocity;

        }

        //Moving the Player
        rb2d.AddForce((Vector2.right * speed) * h);

        //Limiting the Speed of the Player
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);

        }
    }
}
</code>```

The Ground Material is applied to this landscape just like the other rectangular landscape. Sorry Im new but again, thanks everyone!

答: I'm new to Unity as well but a thought I had was...is it possible your collider dimensions are resetting after the first frame? Maybe you can manually set the collider to stay at a certain angle to test this. Just a thought! I'd be interested to know what you find out. </p>

Body:
Hey guys so im making a 2D Platformer and ran into a difficult situation. Up until now I have had rectangular landscapes for the player to jump and walk on. Now I want to start adding some hills. Picture a triangle, the left side is representing a hill at which the player can walk up. Ive made the landscape as well as copied over the Box Collider 2D from my other paths. I figured out a way to rotate the collider so that it goes up at a 45 degree angle just like the slope of the triangle. For some reason though when I walk into the triangle the player doesnt start walking up it. I have to jump onto the hill and he lands on what looks like an invisible rectangle! I make the collider .25 in thickness so I know that I have the whole collider where I want it. Any idea why? I dont really have any code for this as everything Im doing has pretty much been in scene view. Thanks everyone!

Here is the Player in Play Mode, stands on top of hill by some force:

Here is what the collider looks like in scene view. Ive moved the collider all over and it still does the same thing:

Here is my movement code:

public class Player : MonoBehaviour {

    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    void Start () {

        rb2d = gameObject.GetComponent<Rigidbody2D>();
        anim = gameObject.GetComponent<Animator>();
    }

    void Update () {

        anim.SetBool("Grounded",grounded);
        anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));

        if (Input.GetAxis("Horizontal") < -0.1)
        {
            transform.localScale = new Vector3(-1, 1, 1);

        }
        if (Input.GetAxis("Horizontal") > 0.1)
        {
            transform.localScale = new Vector3(1, 1, 1);

        }

        if (Input.GetButtonDown("Jump") && grounded)
        {
            rb2d.AddForce(Vector2.up * jumpPower);

        }

    }

    void FixedUpdate() {

        Vector3 easeVelocity = rb2d.velocity;
        easeVelocity.y = rb2d.velocity.y;
        easeVelocity.z = 0.0f;
        easeVelocity.x *= 0.75f;

        float h = Input.GetAxis("Horizontal");

        //Fake friction / Easing the x speed of our player
        if (grounded)
        {

            rb2d.velocity = easeVelocity;

        }

        //Moving the Player
        rb2d.AddForce((Vector2.right * speed) * h);

        //Limiting the Speed of the Player
        if (rb2d.velocity.x > maxSpeed)
        {
            rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

        }

        if (rb2d.velocity.x < -maxSpeed)
        {
            rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);

        }
    }
}

The Ground Material is applied to this landscape just like the other rectangular landscape. Sorry Im new but again, thanks everyone!


来源: stackexchange

问:
Autofac Dependency Injection in Azure Function
I am trying to implement DI using Autofac IOC in Azure function.
I need to build the container, but not sure where to put the code to build the container</p>

答:
Azure Functions doesn't support dependency injection yet. Follow this issue for the feature request
https://github.com/Azure/Azure-Functions/issues/299 </p>

ContentLicense: CC BY-SA 3.0


问:
Is it possible for Eclipse to only open one JFrame?
When run the project second time, can the previous JFrame closed before open the new one ?

So I no need to close the JFrame when trying to run the project second time.

Is it possible to open only one JFrame?

答: you may find relaunch-plugin for eclipse useful for your case. </p>


问:
Adding div after WordPress submenu items
I am trying to add a div after any submenu items in a WordPress menu. I am working on the following code in the functions.php file:

```<code>add_filter( 'nav_menu_link_attributes', 'SubMenuCheck', 10, 3 );
function SubMenuCheck( $atts, $item, $args ) {
  if (in_array('menu-item-has-children', $item->classes)) {
    $args->after = '<div class="click">+</div>';
  }
  return $atts;
}
</code>```

The code above adds the new div
+
but keeps applying it to all parent and child items after the first 'menu-item-has-children' class:

Does anyone know why this is repeating?... I only want the div to display for items with the menu-item-has-children class.

Thanks

答:
I don't use the nav_menu_link_attributes filter, to add a button (which is semantically correct) to be the hot spot for toggling the children, I use the following:

```<code>function prefix_add_button_after_menu_item_children( $item_output, $item, $depth, $args ) {

    if ( $args->theme_location == 'primary' ) {

        if ( in_array( 'menu-item-has-children', $item->classes ) || in_array( 'page_item_has_children', $item->classes ) ) {
            $item_output = str_replace( $args->link_after . '</a>', $args->link_after . '</a><button class="sub-menu-toggle" aria-expanded="false" aria-pressed="false"><span class="screen-reader-text">' . _x( 'open dropdown menu', 'verb: open the menu', 'text-domain' ) . '</span></button>', $item_output );
        }
    }

    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'prefix_add_button_after_menu_item_children', 10, 4 );
</code>```

Body:
I am trying to add a div after any submenu items in a WordPress menu. I am working on the following code in the functions.php file:

add_filter( 'nav_menu_link_attributes', 'SubMenuCheck', 10, 3 );
function SubMenuCheck( $atts, $item, $args ) {
  if (in_array('menu-item-has-children', $item->classes)) {
    $args->after = '
+
';
  }
  return $atts;
}

The code above adds the new div
+
but keeps applying it to all parent and child items after the first 'menu-item-has-children' class:

Does anyone know why this is repeating?... I only want the div to display for items with the menu-item-has-children class.

Thanks

Body:
I don't use the nav_menu_link_attributes filter, to add a button (which is semantically correct) to be the hot spot for toggling the children, I use the following:

function prefix_add_button_after_menu_item_children( $item_output, $item, $depth, $args ) {

    if ( $args->theme_location == 'primary' ) {

        if ( in_array( 'menu-item-has-children', $item->classes ) || in_array( 'page_item_has_children', $item->classes ) ) {
            $item_output = str_replace( $args->link_after . '</a>', $args->link_after . '</a><button class="sub-menu-toggle" aria-expanded="false" aria-pressed="false"><span class="screen-reader-text">' . _x( 'open dropdown menu', 'verb: open the menu', 'text-domain' ) . '</span></button>', $item_output );
        }
    }

    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'prefix_add_button_after_menu_item_children', 10, 4 );


问:
Strategy pattern with different method signatures
Using the strategy pattern, how can treat different exectute methods differently in terms of them having different parameters?

3 example strategies

```<code>public function execute(string $param1, string $param2)
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
    //
}

public function execute(string $param1)
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
    //
}

public function execute()
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
}
</code>```

The all do something very specific but require different parameters for this, then they do something generic that every strategy will do.

答:
Using the strategy pattern, how can treat different exectute methods
  differently in terms of them having different parameters?

If you make it work this way, it won't be considered a strategy pattern. The fact that your client knows different strategies require different parameters, invalidates the strategy pattern, because then client is assumed to know (at least partially) what specific strategy does internally.

Understand that strategy should not accept parameters selectively. It should instead work on the parameters selectively. So until you read further down, consider that we now have all strategies accepting all parameters. So that Strategy1 uses only param1 and param2 and ignores param3, and so on.

```<code>function execute(param1, param2, param3) { }
</code>```

However this gets ugly if you have even more parameters. You can instead have a separate Parameter class and pass this collection of parameters to every strategy. Each strategy will include a logic to get and use parameters that it requires and will ignore rest.

then they do something generic that every strategy will do

That's what you can have abstract strategy for. It will include abstract execute() method and it's own execute() method that each concrete strategy will call.

To summarize, here's how it would look like (non-compilable code):

```<code>Main()
{
    AbstractStrategy s = new ConcreteStrategy1();
    s.Execute(parameters); // parameters -> collection
}

class AbstractStrategy {
    Execute(parameters); // abstract
    Execute() {} // not public
}

class ConcreteStrategy1 : AbstractStrategy {
    override Execute(parameters) {
        string pvalue1 = parameters.GetValue("param1");
        base.Execute();
    }
}
</code>```

Body:
Using the strategy pattern, how can treat different exectute methods differently in terms of them having different parameters?

3 example strategies

public function execute(string $param1, string $param2)
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
    //
}

public function execute(string $param1)
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
    //
}

public function execute()
{
    // Do something specific to this method
    //

    // Do some generic things across all strategies
}

The all do something very specific but require different parameters for this, then they do something generic that every strategy will do.

Body:
Using the strategy pattern, how can treat different exectute methods
  differently in terms of them having different parameters?

If you make it work this way, it won't be considered a strategy pattern. The fact that your client knows different strategies require different parameters, invalidates the strategy pattern, because then client is assumed to know (at least partially) what specific strategy does internally.

Understand that strategy should not accept parameters selectively. It should instead work on the parameters selectively. So until you read further down, consider that we now have all strategies accepting all parameters. So that Strategy1 uses only param1 and param2 and ignores param3, and so on.

function execute(param1, param2, param3) { }

However this gets ugly if you have even more parameters. You can instead have a separate Parameter class and pass this collection of parameters to every strategy. Each strategy will include a logic to get and use parameters that it requires and will ignore rest.

then they do something generic that every strategy will do

That's what you can have abstract strategy for. It will include abstract execute() method and it's own execute() method that each concrete strategy will call.

To summarize, here's how it would look like (non-compilable code):

Main()
{
    AbstractStrategy s = new ConcreteStrategy1();
    s.Execute(parameters); // parameters -> collection
}

class AbstractStrategy {
    Execute(parameters); // abstract
    Execute() {} // not public
}

class ConcreteStrategy1 : AbstractStrategy {
    override Execute(parameters) {
        string pvalue1 = parameters.GetValue("param1");
        base.Execute();
    }
}


问:
innerHtml.replace replaces tags and not just text
I currently try to replace certain words from an utterance with a WORD</span element. I get the start and end indices from the words from the backend. An utterance can have several words which will be replaced. So I just iterate over the array of words to replaced and try to replace the words in the utterance.

However, I tried doing it with innerHtml.replace(word, word). The problem here is, that when for example the second word is 'sp' the sp of the tag of the first word is replaced instead of the word 'sp' in my utterance.

I then tried to replace the word my putting in the start and end index of the word (which I thought would solve the problem). But it seems like if the start and end index points on 'sp' it still replaces the part of span and not the word I wanted to replace.

So, I am looking for a way to replace only words in an utterance and not the HTML elements with the WORD.

My Code right now:

```<code>var label = document.getElementById('match-text' + index);
      label.innerHTML = label.innerHTML.replace(label.innerText.substring(entity.start, entity.end),'<span ng-click="showEntityDetailsPage($event, ' + index + ', ' + entityIndex + ')" style="background-color:'
      + color + '; border: 3px solid ' + borderColor + ';" class="highlighted-entities">' + label.innerText.substring(entity.start, entity.end) + '</span>');
      $compile(label)($scope);
</code>```

答:
Further to my comment, here is how I would implement that.  In this example the anchor tag's html attribute contains "oo" and so does the tfoot tag, and they do not get changed.

function replaceText(obj, search, wrapElement, elementClass) {
  switch (obj.nodeType) {
    case 3: // it's a text node
      if (obj.nodeValue.indexOf(search) > -1) {
        var bits = obj.nodeValue.split(search);
        var nextSib = obj.nextSibling;
        obj.nodeValue = bits[0];
        for (var i=1; i < bits.length; i++) {
          var el = document.createElement(wrapElement);
          el.className = elementClass;
          el.innerHTML = search;
          var tn = document.createTextNode(bits[i]);
          if (nextSib) {
            obj.parentNode.insertBefore(tn, nextSib);
            obj.parentNode.insertBefore(el, tn);
          } else {
            obj.parentNode.appendChild(tn);
            obj.parentNode.insertBefore(el, tn);
          }
        }
        return 2*(bits.length-1);
      }
    break;
    default: // it's not a text node
      for (var i=0; i < obj.childNodes.length; i++) {
        var j = replaceText(obj.childNodes[i], search, wrapElement, elementClass);
        if (j) i+=j;
      }
    break;
  }
}

replaceText(document.getElementById('starthere'), "oo", "span", "myspanclass");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myspanclass {
  color: red;
}</code>```

Noonhour
  Boondoggle
    Google

  The Moon is a Balloon

oops!

```

Body:
I currently try to replace certain words from an utterance with a WORD</span element. I get the start and end indices from the words from the backend. An utterance can have several words which will be replaced. So I just iterate over the array of words to replaced and try to replace the words in the utterance.

However, I tried doing it with innerHtml.replace(word, word). The problem here is, that when for example the second word is 'sp' the sp of the tag of the first word is replaced instead of the word 'sp' in my utterance.

I then tried to replace the word my putting in the start and end index of the word (which I thought would solve the problem). But it seems like if the start and end index points on 'sp' it still replaces the part of span and not the word I wanted to replace.

So, I am looking for a way to replace only words in an utterance and not the HTML elements with the WORD.

My Code right now:

var label = document.getElementById('match-text' + index);
      label.innerHTML = label.innerHTML.replace(label.innerText.substring(entity.start, entity.end),'' + label.innerText.substring(entity.start, entity.end) + '');
      $compile(label)($scope);

Body:
Further to my comment, here is how I would implement that.  In this example the anchor tag's html attribute contains "oo" and so does the tfoot tag, and they do not get changed.

function replaceText(obj, search, wrapElement, elementClass) {
  switch (obj.nodeType) {
    case 3: // it's a text node
      if (obj.nodeValue.indexOf(search) > -1) {
        var bits = obj.nodeValue.split(search);
        var nextSib = obj.nextSibling;
        obj.nodeValue = bits[0];
        for (var i=1; i < bits.length; i++) {
          var el = document.createElement(wrapElement);
          el.className = elementClass;
          el.innerHTML = search;
          var tn = document.createTextNode(bits[i]);
          if (nextSib) {
            obj.parentNode.insertBefore(tn, nextSib);
            obj.parentNode.insertBefore(el, tn);
          } else {
            obj.parentNode.appendChild(tn);
            obj.parentNode.insertBefore(el, tn);
          }
        }
        return 2*(bits.length-1);
      }
    break;
    default: // it's not a text node
      for (var i=0; i < obj.childNodes.length; i++) {
        var j = replaceText(obj.childNodes[i], search, wrapElement, elementClass);
        if (j) i+=j;
      }
    break;
  }
}

replaceText(document.getElementById('starthere'), "oo", "span", "myspanclass");

.myspanclass {
  color: red;
}

<div id='starthere'>Noonhour
  <span>Boondoggle
    <a href="http://google.com">Google</a>
  </span>
  The Moon is a Balloon
  <table><tfoot><tr><th>oops!</th></tr></tfoot></table>
</div>


问:
Node: Accessing req.db in a function where I don't have access to req
I'm trying at add facebook authentication to my app using passport - this works okay, but I need to access the database within passport.use().

Here is my code in routes/auth.js:

```<code>var express = require('express');
var router = express.Router();
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

[...]

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email']
    },
    function(accessToken, refreshToken, profile, cb) {
        var db = need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

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

In app.js, I have the following code:

```<code>// make our db accessible to the router
app.use(function(req,res,next) {
    req.db = db;
    next();
});
</code>```

How can I access req.db in auth.js in the location marked?

答:
If the db is in the req object, you can configue FacebookStrategy to pass the req object to the verify function.

See:

```<code>passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email'],
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, cb) {
        var db = req.db; // need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));
</code>```

Hope it works.

Body:
I'm trying at add facebook authentication to my app using passport - this works okay, but I need to access the database within passport.use().

Here is my code in routes/auth.js:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;

[...]

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email']
    },
    function(accessToken, refreshToken, profile, cb) {
        var db = need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

module.exports = router;

In app.js, I have the following code:

// make our db accessible to the router
app.use(function(req,res,next) {
    req.db = db;
    next();
});

How can I access req.db in auth.js in the location marked?

Body:
If the db is in the req object, you can configue FacebookStrategy to pass the req object to the verify function.

See:

passport.use(new FacebookStrategy({
        clientID: REDACTED,
        clientSecret: REDACTED,
        callbackURL: REDACTED,
        profileFields: ['id', 'displayName', 'email'],
        passReqToCallback: true
    },
    function(req, accessToken, refreshToken, profile, cb) {
        var db = req.db; // need to access db here;
        db.users.insertOne({ 'facebookId': profile.id, 'name': profile.displayName, 'email': profile.email }, function(err, user) {
            return cb(err, user);
        });
    }
));

Hope it works.


问:
Cannot center X axis label using Chartist.js
I have a simple bar chart that I cannot get the x axis labels to center on the actual column.  Link to a screen shot here. Any help will be greatly appreciated.</p>

```<code><div class="ct-chart" id="chart"></div>
    <script>
    new Chartist.Bar('#chart', {
      labels: ['Saved', 'Goal'],
      series: [
        [6000, 10000]
      ]
    }, {
      stackBars: true,
      width: 300,
      height: 250,
      axisX: {
        textAnchor: 'middle'
      },
      axisY: {
        labelInterpolationFnc: function(value) {
          return (value / 1000) + 'k';
        }
      }
    }).on('draw', function(data) {
      if(data.type === 'bar') {

        data.element.attr({
          style: 'stroke-width: 70px'
        });

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

答: This is not a problem with Chrome so unless someone knows how to get it to work in IE, I will close the question.</p>


问:
Java not using the correct timezone
My company has a web application deployed to an Oracle WebLogic server. We are working on upgrading to WebLogic 12c and upgrading the application from Java 1.5 to 1.7.0_15.

When starting the application server, we were getting the following error:

```<code><Jun 6, 2017 12:09:31 PM EDT> <Error> <Deployer> <BEA-149205> <Failed to initialize the application "SIMPLeBDataSource" due to error weblogic.application.ModuleException: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

weblogic.application.ModuleException: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

        at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:350)
        at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
        at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:175)
        at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:170)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
        Truncated. see log file for complete stacktrace
Caused By: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

        at weblogic.jdbc.common.internal.ConnectionEnvFactory.createResource(ConnectionEnvFactory.java:360)
        at weblogic.common.resourcepool.ResourcePoolImpl.makeResources(ResourcePoolImpl.java:1320)
        at weblogic.common.resourcepool.ResourcePoolImpl.makeResources(ResourcePoolImpl.java:1237)
        at weblogic.common.resourcepool.ResourcePoolImpl.start(ResourcePoolImpl.java:240)
        at weblogic.jdbc.common.internal.ConnectionPool.doStart(ConnectionPool.java:1624)
        Truncated. see log file for complete stacktrace
>
</code>```

We found that adding -Duser.timezone='Canada/Eastern' to the server start parameters fixed the problem. However, the server logs and log4j logs are not recording the correct timestamp; they are an hour behind.

I added TimeZone localTimeZone = TimeZone.getDefault(); to the code and logged localTimeZone.toString() and got sun.util.calendar.ZoneInfo[id="GMT-05:00",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null].

Eastern Standard Time is GMT-5 and we are currently in Daylight Savings, which makes it GMT-4, so it seems like it's using the specified java startup parameter but not recognizing that it's supposed to be in DST. Is there a way to specify DST in the start parameters?

答:
Setting user.timezone is the correct procedure. If its still not working, try upgrading to the latest jdk, say jdk 7 update 131 or 141. If that is not an option, try the "Timezone Updater tool". You can find more details here :
http://www.oracle.com/technetwork/java/javase/dst-faq-138158.html

Title: Java not using the correct timezone

Body:
My company has a web application deployed to an Oracle WebLogic server. We are working on upgrading to WebLogic 12c and upgrading the application from Java 1.5 to 1.7.0_15.

When starting the application server, we were getting the following error:

<Jun 6, 2017 12:09:31 PM EDT> <Error> <Deployer> <BEA-149205> <Failed to initialize the application "SIMPLeBDataSource" due to error weblogic.application.ModuleException: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

weblogic.application.ModuleException: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

        at weblogic.jdbc.module.JDBCModule.prepare(JDBCModule.java:350)
        at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100)
        at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:175)
        at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:170)
        at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
        Truncated. see log file for complete stacktrace
Caused By: weblogic.common.ResourceException: weblogic.common.ResourceException: Could not create pool connection for datasource 'SIMPLeBDataSource'. The DBMS driver exception was: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region  not found

        at weblogic.jdbc.common.internal.ConnectionEnvFactory.createResource(ConnectionEnvFactory.java:360)
        at weblogic.common.resourcepool.ResourcePoolImpl.makeResources(ResourcePoolImpl.java:1320)
        at weblogic.common.resourcepool.ResourcePoolImpl.makeResources(ResourcePoolImpl.java:1237)
        at weblogic.common.resourcepool.ResourcePoolImpl.start(ResourcePoolImpl.java:240)
        at weblogic.jdbc.common.internal.ConnectionPool.doStart(ConnectionPool.java:1624)
        Truncated. see log file for complete stacktrace
>

We found that adding -Duser.timezone='Canada/Eastern' to the server start parameters fixed the problem. However, the server logs and log4j logs are not recording the correct timestamp; they are an hour behind.

I added TimeZone localTimeZone = TimeZone.getDefault(); to the code and logged localTimeZone.toString() and got sun.util.calendar.ZoneInfo[id="GMT-05:00",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null].

Eastern Standard Time is GMT-5 and we are currently in Daylight Savings, which makes it GMT-4, so it seems like it's using the specified java startup parameter but not recognizing that it's supposed to be in DST. Is there a way to specify DST in the start parameters?


问:
CSS: resize div width according to parents width
Ok, I am basically building a fluid layout.
My HTML is like this:

```<code><div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="center">This text is long and can get longer</div>
    <div class="box" id="right">Right</div>
    <div class="clear"></div>
</div>
</code>```

Here is the css:

```<code>#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}
</code>```

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.

答:
#container also must be floated (or with overflow: auto/hidden) to achieve it.
I strongly suggest you use some of the more well known fluid solutions: http://www.noupe.com/css/9-timeless-3-column-layout-techniques.html

ContentLicense: CC BY-SA 2.5

Body:
Ok, I am basically building a fluid layout.
My HTML is like this:

Left

This text is long and can get longer

Right

Here is the css:

#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.


问:
Can't customize the appearance of EditText select handle / anchor on landscape
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}
</code>```

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>
</code>```

My styles:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="MyCustomTheme" parent="@style/AppTheme">
    <item name="android:textSelectHandle">@drawable/small_rect</item>
    <item name="android:textSelectHandleLeft">@drawable/small_rect</item>
    <item name="android:textSelectHandleRight">@drawable/small_rect</item>
</style>
</code>```

the drawable (small_rect.xml)

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>
</code>```

the result:

答: You guys code work only in Portrait (so does mine). My application is landscape only and I looked around and it looks like this an OS bug. I notified google about it. Yet, if there is workaround still using the EditText the 50 points is still up for grabs.</p>

Body:
I am having a hard time customizing the EditText select handle. I am following this thread:

How to change color / appearance of EditText select handle / anchor?

It looks like pretty straight forward. Yet, I can't get it to work on landscape. Can anyone spot what I am doing wrong? I pretty much pasted the same code on a test activity but the anchor handles' are always the same. I tried using styles as suggested and programmatically. Still I always get the same default blue anchors :(

I am on Nougat not sure if makes any difference.

Test activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyCustomTheme);
    setContentView(R.layout.activity_main);
    final EditText editText = (EditText) findViewById(R.id.edit1);
    // tried programatically too and no success
    try {
        final Field fEditor = TextView.class.getDeclaredField("mEditor");
        fEditor.setAccessible(true);
        final Object editor = fEditor.get(editText);
        final Field fSelectHandleLeft = editor.getClass().getDeclaredField("mSelectHandleLeft");
        final Field fSelectHandleRight =
                editor.getClass().getDeclaredField("mSelectHandleRight");
        final Field fSelectHandleCenter =
                editor.getClass().getDeclaredField("mSelectHandleCenter");
        fSelectHandleLeft.setAccessible(true);
        fSelectHandleRight.setAccessible(true);
        fSelectHandleCenter.setAccessible(true);
        fSelectHandleLeft.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleRight.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
        fSelectHandleCenter.set(editor, ContextCompat.getDrawable(this, R.drawable.small_rect));
    } catch (final Exception e) {
        Log.d("CUSTOM_ANCHORS", e.toString());
    }
}

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Hello World"
        android:textSize="20sp" />

</LinearLayout>

My styles:

the drawable (small_rect.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="20dp"
        android:height="20dp" />
    <gradient
        android:angle="90"
        android:centerColor="#D6D6D6"
        android:endColor="#4B6CD6"
        android:startColor="#6586F0" />
    <corners android:radius="0dp" />
</shape>

the result:


问:
function syntax // Generalizing the function
I am trying to subset duplicate observations that have a difference in a singular column. In this example I'm trying to subset observations with the same id number but difference tag numbers. I'm planning on making my own function and then using the lapply function to go through my data set.

As of now my code looks like:

```<code>test.function <- (i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
   id.tag <- subset(i)
   }
}

lapply (test.data, test.function)
</code>```

I have a few questions regarding the above statement. Most importantly, I keep receiving:

```<code>Error: unexpected '{' in "test.data <- (i) {"
</code>```

I'm really not sure why this keeps happening and any guidance would be appreciated.

Current data set looks like (999 is just a missing value indicator):

```<code>id     tag.num
1000   999
1000   A49038483
1100   999
1100   A49294883
1200   999
1200   999
</code>```

Once again, I am just trying to subset the same id with a different tag number. In this example I am trying to subset 4 observations of id 1000 and 1100.

Also, I am wondering about the syntax inside of my if statement and if it is necessary to have to specify my data set name. I'm hoping to apply this function on several different columns within my original data set. If there is a more general way in which I could set this up and then be able to run the lapply function through for all applicable columns, that would be great knowledge. Any and all help is appreciated.

答:
To define a function in R, the syntax is

```<code>fun.name <- function(args) {...}
</code>```

so you need function(i) where you have just (i) above.

I'd also suggest that if you're trying to lapply across the rows of your dataset, you probably don't need to do that.

It's not entirely clear to me what you're trying to do. Could you post a data sample and what you're hoping to get back?

Body:
I am trying to subset duplicate observations that have a difference in a singular column. In this example I'm trying to subset observations with the same id number but difference tag numbers. I'm planning on making my own function and then using the lapply function to go through my data set.

As of now my code looks like:

test.function <- (i) {
  if(test.data[i, "id"] == test.data[i-1, "id"] &
     test.data[i, "tag.num"] != test.data[i-1, "tag.num"]){
   id.tag <- subset(i)
   }
}

lapply (test.data, test.function)

I have a few questions regarding the above statement. Most importantly, I keep receiving:

Error: unexpected '{' in "test.data <- (i) {"

I'm really not sure why this keeps happening and any guidance would be appreciated.

Current data set looks like (999 is just a missing value indicator):

id     tag.num
1000   999
1000   A49038483
1100   999
1100   A49294883
1200   999
1200   999

Once again, I am just trying to subset the same id with a different tag number. In this example I am trying to subset 4 observations of id 1000 and 1100.

Also, I am wondering about the syntax inside of my if statement and if it is necessary to have to specify my data set name. I'm hoping to apply this function on several different columns within my original data set. If there is a more general way in which I could set this up and then be able to run the lapply function through for all applicable columns, that would be great knowledge. Any and all help is appreciated.

Body:
To define a function in R, the syntax is

fun.name <- function(args) {...}

so you need function(i) where you have just (i) above.

I'd also suggest that if you're trying to lapply across the rows of your dataset, you probably don't need to do that.

It's not entirely clear to me what you're trying to do. Could you post a data sample and what you're hoping to get back?


问:
Generate a csv file from a javascript array of objects
I know this is a question already answered but couldn't find the solution that works for me.

I've a HTML button that, when clicked, generate an array of objects in typescript(which basically javascript) and i want to generate a csv file that will be downloaded.

Here is the example of the javascript array of objects:

```<code>    var items = [
              { "name": "Item 1", "color": "Green", "size": "X-Large" },
              { "name": "Item 2", "color": "Green", "size": "X-Large" },
              { "name": "Item 3", "color": "Green", "size": "X-Large" }];

    // Loop the array of objects
for(let row = 0; row < items.length; row++){
    let keysAmount = Object.keys(items[row]).length
    let keysCounter = 0

    // If this is the first row, generate the headings
    if(row === 0){

       // Loop each property of the object
       for(let key in items[row]){

                           // This is to not add a comma at the last cell
                           // The '\n' adds a new line
           csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }else{
       for(let key in items[row]){
           csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }

    keysCounter = 0
}
console.log(csv)

var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'people.csv';
        hiddenElement.click();
</code>```

I tried this example code but in my case it create the csv file, but doesn't insert the csv string correctly in the csv file, the csv string is has rows of element separated by a comma and each row is determined by a new line, but here all the data of each row sits in one cell of the csv file, how can I make so that each value of each row sits in a different cell?

here is the csv string that it:

```<code>    name,color,size
Item 2,Green,X-Large
Item 3,Green,X-Large
</code>```

答:
CSV is just a file with each cell separated by a comma and each row separated by a new line. You want to name each column as the key of the object. If I understood correctly:

```<code>{ "name": "Item 1", "color": "Green", "size": "X-Large" }
</code>```

Will be:

```<code>---------------------------
| name   | color |   size  |
---------------------------
| Item 1 | Green | X-Large |
---------------------------
</code>```

UPDATE: This is the updated version.

So you can loop your array and generate the csv accordingly using the File API from HTML5:

```<code>let csv

// Loop the array of objects
for(let row = 0; row < items.length; row++){
    let keysAmount = Object.keys(items[row]).length
    let keysCounter = 0

    // If this is the first row, generate the headings
    if(row === 0){

       // Loop each property of the object
       for(let key in items[row]){

                           // This is to not add a comma at the last cell
                           // The '\r\n' adds a new line
           csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }else{
       for(let key in items[row]){
           csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }

    keysCounter = 0
}

// Once we are done looping, download the .csv by creating a link
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'yourfiletextgoeshere.csv');
document.body.appendChild(link)
document.querySelector('#download-csv').click()
</code>```

BTW If you are using TypeScript, then the last line document.querySelector('#download-csv').click() MUST be <HTMLElement>document.querySelector('#download-csv').click()
Let me know if it worked for you.

Fiddle for TypeScript and javascript (it changes just the last line):
https://jsfiddle.net/0p8revuh/4/

UPDATE: To see the file propertly formated in excel, a cell for each comma separated value, do the following:

You will see your data in several rows. Just click on the 'A' column to select all the rows:

Go to your excel and click on Data at the top:

Click on Text to columns:

Select delimited:

Click on next and active comma:

Click on next and finish. Now you should be able to see your data propertly formated.

Body:
I know this is a question already answered but couldn't find the solution that works for me.

I've a HTML button that, when clicked, generate an array of objects in typescript(which basically javascript) and i want to generate a csv file that will be downloaded.

Here is the example of the javascript array of objects:

    var items = [
              { "name": "Item 1", "color": "Green", "size": "X-Large" },
              { "name": "Item 2", "color": "Green", "size": "X-Large" },
              { "name": "Item 3", "color": "Green", "size": "X-Large" }];

    // Loop the array of objects
for(let row = 0; row < items.length; row++){
    let keysAmount = Object.keys(items[row]).length
    let keysCounter = 0

    // If this is the first row, generate the headings
    if(row === 0){

       // Loop each property of the object
       for(let key in items[row]){

                           // This is to not add a comma at the last cell
                           // The '\n' adds a new line
           csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }else{
       for(let key in items[row]){
           csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }

    keysCounter = 0
}
console.log(csv)

var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'people.csv';
        hiddenElement.click();

I tried this example code but in my case it create the csv file, but doesn't insert the csv string correctly in the csv file, the csv string is has rows of element separated by a comma and each row is determined by a new line, but here all the data of each row sits in one cell of the csv file, how can I make so that each value of each row sits in a different cell?

here is the csv string that it:

    name,color,size
Item 2,Green,X-Large
Item 3,Green,X-Large

Body:
CSV is just a file with each cell separated by a comma and each row separated by a new line. You want to name each column as the key of the object. If I understood correctly:

{ "name": "Item 1", "color": "Green", "size": "X-Large" }

Will be:

---------------------------
| name   | color |   size  |
---------------------------
| Item 1 | Green | X-Large |
---------------------------

UPDATE: This is the updated version.

So you can loop your array and generate the csv accordingly using the File API from HTML5:

let csv

// Loop the array of objects
for(let row = 0; row < items.length; row++){
    let keysAmount = Object.keys(items[row]).length
    let keysCounter = 0

    // If this is the first row, generate the headings
    if(row === 0){

       // Loop each property of the object
       for(let key in items[row]){

                           // This is to not add a comma at the last cell
                           // The '\r\n' adds a new line
           csv += key + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }else{
       for(let key in items[row]){
           csv += items[row][key] + (keysCounter+1 < keysAmount ? ',' : '\r\n' )
           keysCounter++
       }
    }

    keysCounter = 0
}

// Once we are done looping, download the .csv by creating a link
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'yourfiletextgoeshere.csv');
document.body.appendChild(link)
document.querySelector('#download-csv').click()

BTW If you are using TypeScript, then the last line document.querySelector('#download-csv').click() MUST be <HTMLElement>document.querySelector('#download-csv').click()
Let me know if it worked for you.

Fiddle for TypeScript and javascript (it changes just the last line):
https://jsfiddle.net/0p8revuh/4/

UPDATE: To see the file propertly formated in excel, a cell for each comma separated value, do the following:

You will see your data in several rows. Just click on the 'A' column to select all the rows:

Go to your excel and click on Data at the top:

Click on Text to columns:

Select delimited:

Click on next and active comma:

Click on next and finish. Now you should be able to see your data propertly formated.


问:
Check if user has Facebook Messenger installed iOS 9
Facebook has deprecated the method [FBSDKMessengerSharer messengerPlatformCapabilities]  that is used to check if the user has Messenger app installed. In the warning message, it says:

messengerPlatformCapabilities is deprecated: This is deprecated as of iOS 9. If you use this, you must configure your plist as described in https://developers.facebook.com/docs/ios/ios9

I would like to remove this method, but haven't found any other option to replace this code (that makes a button disabled if user hasn't Messenger app installed):

```<code>if (![FBSDKMessengerSharer messengerPlatformCapabilities]) {
    [self.inviteFriendsButton setEnabled:NO];
    [self.inviteFriendsButton setAlpha:0.5f];
}
</code>```

Is there any other method? Or, as new iOS requirements I should avoid using this if? Thank you in advance.

答:
In my case I needed to know whether to show a button users could press to share content on messenger.  This worked for my case, and it also checks whether the messenger app is installed.

-(BOOL) canShareViaMessenger {
    [[[FBSDKMessageDialog alloc] init] canShow]
}
```

Body:
Facebook has deprecated the method [FBSDKMessengerSharer messengerPlatformCapabilities]  that is used to check if the user has Messenger app installed. In the warning message, it says:

messengerPlatformCapabilities is deprecated: This is deprecated as of iOS 9. If you use this, you must configure your plist as described in https://developers.facebook.com/docs/ios/ios9

I would like to remove this method, but haven't found any other option to replace this code (that makes a button disabled if user hasn't Messenger app installed):

if (![FBSDKMessengerSharer messengerPlatformCapabilities]) {
    [self.inviteFriendsButton setEnabled:NO];
    [self.inviteFriendsButton setAlpha:0.5f];
}

Is there any other method? Or, as new iOS requirements I should avoid using this if? Thank you in advance.


问:
Change language of actions-on-google websimulation or test google home in German
I am using actions on google with api.ai. I am able to create a api.ai bot in a language other than English, but the web simulator of actions-on-google (https://developers.google.com/actions/tools/web-simulator) seems to work in English only? Is there any option to change the language there or a time schedule when other languages (in my case German) will be available in the simulator?

Currently testing a non English action is impossible, because the web simulator does not even forward requests if it doesnt understand their meaning on its own.

Update 09/08/2017: Google Home is now available in Germany, I just bought one. Isn't it possible to test my German actions with a google home device either?

答: Yea -- sorry, you need to set your phone to US-English to test today.  We are working on making Actions on Google work for German but that will likely not be ready until later in the year.</p>


问:
Using variable responses to form new variable
If

    x= Apple
    y = 0123

How can I create a new variable Apple0123 using x & y?

so basically:  COMBINE(x,y) = 5

and if i type in Apple0123 -> the output is 5

Body:
x = 'Apple'
y = '0123'
x+y
exec("%s = %d" % ((x+y),5))
print(Apple0123)

or

x = 'Apple'
y = '0123'
x+y
vars()[x+y]
print(Apple0123)


问:
java attach file from virtual filesystem to email
I am using a virtual filesystem and I'd like to attach a file from it to an email. However, the MimeBodyPart object only takes Files, which don't work on a default filesystem like jimfs. See my code below, where I get an UnsupportedOperation exception when I try to convert to file.</p>

```<code>public Email attach(Path file){
    MimeBodyPart attachment = new MimeBodyPart()
    attachment.attachFile(file.toFile())
    attachments.add(attachment)
    return this
}
</code>```

答:
Since jimfs files aren't really files, you can't use the File APIs.

A simple workaround is to use ByteArrayDataSource, which will copy the data.

A better approach would be to write your own PathDataSource that's similar to FileDataSource but uses Files.newInputStream instead of FileInputStream.  Then attach the file using:

```<code>MimeBodyPart mbp = new MimeBodyPart();
mbp.setDataHandler(new DataHandler(new PathDataSource(path)));
mbp.setFileName(path.getFileName().toString());
mbp.setDisposition(Part.ATTACHMENT);
</code>```

Body:
I am using a virtual filesystem and I'd like to attach a file from it to an email. However, the MimeBodyPart object only takes Files, which don't work on a default filesystem like jimfs. See my code below, where I get an UnsupportedOperation exception when I try to convert to file.

public Email attach(Path file){
    MimeBodyPart attachment = new MimeBodyPart()
    attachment.attachFile(file.toFile())
    attachments.add(attachment)
    return this
}

Body:
Since jimfs files aren't really files, you can't use the File APIs.

A simple workaround is to use ByteArrayDataSource, which will copy the data.

A better approach would be to write your own PathDataSource that's similar to FileDataSource but uses Files.newInputStream instead of FileInputStream.  Then attach the file using:

MimeBodyPart mbp = new MimeBodyPart();
mbp.setDataHandler(new DataHandler(new PathDataSource(path)));
mbp.setFileName(path.getFileName().toString());
mbp.setDisposition(Part.ATTACHMENT);


问:
Streaming Json - PushStreamContent with a Large Object
I need to stream a large object.  I'm unable to figure out how to send it in chunks.  The posted code works, however, stream.Flush() only gets called once.  So, essentially I'm buffering the object - not good.  How do I call stream.Flush() multiple times?  If I had a collection, I could stream/flush in a loop.  So how do I do that with a large object?

SERVER CODE:

```<code>   public async Task<HttpResponseMessage> ConvertToTiffAsync([FromBody] DocumentDto dto)
                {
                    // THIS IS LARGE
                    var document = await _service.ConvertToTiffAsync(dto);
                    var response = Request.CreateResponse();
                    response.Content = new PushStreamContent((stream, content, context) =>
                    {
                        var serializer = new JsonSerializer();
                        using (var writer = new StreamWriter(stream))
                        {
                            using (var jsonTextWriter = new JsonTextWriter(writer))
                            {
                                serializer.Serialize(jsonTextWriter, document);
                                stream.Flush(); // ONLY CALLED ONCE - NEED MANY CALLS
                            }
                        }
                    });
                    return response;
                }
</code>```

CLIENT CODE (streaming not happening here, but needs to):

```<code>using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
            {
                client.Timeout = new TimeSpan(0, 5, 0);
                var stringContent = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
                using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint))
                {
                    httpRequest.Content = stringContent;
                    using (HttpResponseMessage response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
                    {
                        response.EnsureSuccessStatusCode();
                        using (var streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                        using (var jsonReader = new JsonTextReader(streamReader))
                        {
                            var serializer = new JsonSerializer();
                            return await Task.Run(() => serializer.Deserialize<ConvertDocumentDto>(jsonReader)).ConfigureAwait(false);
                        }
                    }
                }
            }
</code>```

答:
Your server code seems to be fine. However, your client code doesn't seem to be able to properly interact with the server.

If you want to set DocumentDto input, you would need to write the JSON to the request, not to the response. If you want to consume the server action without having the complete JSON in memory you would need a JsonTextReader. So in general in the client-side should be:

```<code>var client = new HttpClient();
var dtoContent = new PushStreamContent((stream, content, context) => {
   var serializer = new JsonSerializer();
    using (var streamWriter = new StreamWriter(stream))
    {
       using (var jsonWriter = new JsonTextWriter(streamWriter))
       { serializer.Serialize(jsonTextWriter, dto); }
    }
});
using (var stream = await client.PostAsync(url, dtoContent).Content.ReadAsStreamAsync())
{
  using (var streamReader = new StreamReader(stream))
  {
    using (var jsonReader = new JsonTextReader(streamReader))
    {
        document = JsonSerializer().Deserialize<Document>(jsonReader);
    }
  }
}
</code>```

If your DTO is small and you don't mind having the complete JSON in memory instead of client.PostAsync(url) you could also use client.PostAsJsonAsync(url, dto) which is in the HttpClientExtensions namespace if you import System.Net.Http.Formatting.dll.

Body:
I need to stream a large object.  I'm unable to figure out how to send it in chunks.  The posted code works, however, stream.Flush() only gets called once.  So, essentially I'm buffering the object - not good.  How do I call stream.Flush() multiple times?  If I had a collection, I could stream/flush in a loop.  So how do I do that with a large object?

SERVER CODE:

   public async Task<HttpResponseMessage> ConvertToTiffAsync([FromBody] DocumentDto dto)
                {
                    // THIS IS LARGE
                    var document = await _service.ConvertToTiffAsync(dto);
                    var response = Request.CreateResponse();
                    response.Content = new PushStreamContent((stream, content, context) =>
                    {
                        var serializer = new JsonSerializer();
                        using (var writer = new StreamWriter(stream))
                        {
                            using (var jsonTextWriter = new JsonTextWriter(writer))
                            {
                                serializer.Serialize(jsonTextWriter, document);
                                stream.Flush(); // ONLY CALLED ONCE - NEED MANY CALLS
                            }
                        }
                    });
                    return response;
                }

CLIENT CODE (streaming not happening here, but needs to):

using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
            {
                client.Timeout = new TimeSpan(0, 5, 0);
                var stringContent = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
                using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint))
                {
                    httpRequest.Content = stringContent;
                    using (HttpResponseMessage response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
                    {
                        response.EnsureSuccessStatusCode();
                        using (var streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                        using (var jsonReader = new JsonTextReader(streamReader))
                        {
                            var serializer = new JsonSerializer();
                            return await Task.Run(() => serializer.Deserialize<ConvertDocumentDto>(jsonReader)).ConfigureAwait(false);
                        }
                    }
                }
            }

Body:
Your server code seems to be fine. However, your client code doesn't seem to be able to properly interact with the server.

If you want to set DocumentDto input, you would need to write the JSON to the request, not to the response. If you want to consume the server action without having the complete JSON in memory you would need a JsonTextReader. So in general in the client-side should be:

var client = new HttpClient();
var dtoContent = new PushStreamContent((stream, content, context) => {
   var serializer = new JsonSerializer();
    using (var streamWriter = new StreamWriter(stream))
    {
       using (var jsonWriter = new JsonTextWriter(streamWriter))
       { serializer.Serialize(jsonTextWriter, dto); }
    }
});
using (var stream = await client.PostAsync(url, dtoContent).Content.ReadAsStreamAsync())
{
  using (var streamReader = new StreamReader(stream))
  {
    using (var jsonReader = new JsonTextReader(streamReader))
    {
        document = JsonSerializer().Deserialize<Document>(jsonReader);
    }
  }
}

If your DTO is small and you don't mind having the complete JSON in memory instead of client.PostAsync(url) you could also use client.PostAsJsonAsync(url, dto) which is in the HttpClientExtensions namespace if you import System.Net.Http.Formatting.dll.


问:
Is JQGrid free?
Download JQGrid js file from http://www.trirand.com/blog/ . Is it free?

What is this http://www.trirand.net/demoaspnetmvc.aspx ? . I see price and license.

Someone clarify please.

答:
There are two versions of jqGrid: Free, Open Source package as pure JavaScript solution delivered with GPL & MIT licenses and commercial which is integrated in for example Visual Studio development environment. You can use any from the versions in your ASP.NET MVC Project.

jqGrid can be used to fill data from almost any web service providing data in JSON or XML format. So you can write in ASP.NET MVC a Controller method which provide pure data in the JSON format and use View with empty
 having only an id attribute defined. If you want you can implement the "data provider" as ASMX or WCF service. You can also combine any from the solutions in one site, so you will be free in the implementation.

Look at the other question where you can find some links with examples of the usage of jqGrid with ASP.NET MVC.

UPDATE: The answer is old and the licence agreement is changed now. The there exist two main forks of jqGrid: 1) free jqGrid, the fork, which I develop since the end of 2014 and which I provide under the old MIT/GPLv2 licence; 2) Guriddo jqGrid JS, available for the prices. You can read more detailed about the problem in the following more recent answers: this one, this one and this one.

Title: Is JQGrid free?

Body:
There are two versions of jqGrid: Free, Open Source package as pure JavaScript solution delivered with GPL & MIT licenses and commercial which is integrated in for example Visual Studio development environment. You can use any from the versions in your ASP.NET MVC Project.

jqGrid can be used to fill data from almost any web service providing data in JSON or XML format. So you can write in ASP.NET MVC a Controller method which provide pure data in the JSON format and use View with empty <table> having only an id attribute defined. If you want you can implement the "data provider" as ASMX or WCF service. You can also combine any from the solutions in one site, so you will be free in the implementation.

Look at the other question where you can find some links with examples of the usage of jqGrid with ASP.NET MVC.

UPDATE: The answer is old and the licence agreement is changed now. The there exist two main forks of jqGrid: 1) free jqGrid, the fork, which I develop since the end of 2014 and which I provide under the old MIT/GPLv2 licence; 2) Guriddo jqGrid JS, available for the prices. You can read more detailed about the problem in the following more recent answers: this one, this one and this one.


问:
Vectorize or optimize an loop where each iteration depends on the state of the previous iteration
I have an algorithm which I am implementing in python. The algorithm might be executed 1.000.000 times so I want to optimize it as much as possible. The base in the algorithm is three lists (energy, point and valList) and two counters p and e.

The two lists energy and point contains number between 0 and 1 on which I base decisions. p is a point-counter and e is an energy-counter. I can trade points for enery, and the cost of each energy is defined in valList (it is time dependent). I can also trade the otherway. But I have to trade all at once.

The outline of the algorithm:

Get a boolean-list where the elements in energy is above a threshold and the elements in point is below another threshold. This is a decision to trade energy for points. Get a corresponding list for point, which gives decision to trade points for energy

In each of the boolean-lists. Remove all true-values that comes after another true value (if i have trade all points for energy, i am not allowed to do that again point after)

For each item-pair (pB, point bool and eB, energy bool) from the two boolean lists: If pB is true and i have points, i want to trade all my points for enery. If eB is true and i have energy, i want to trade all my energy to points.

This is the implementation i have come up with:

```<code>start = time.time()
import numpy as np

np.random.seed(2) #Seed for deterministic result, just for debugging

topLimit = 0.55
bottomLimit = 0.45

#Generate three random arrays, will not be random in the real world
res = np.random.rand(500,3) #Will probably not be much longer than 500
energy = res[:,0]
point = res[:,1]
valList = res[:,2]

#Step 1:
#Generate two bools that (for ex. energy) is true when energy is above a threashold
#and point below another threshold). The opposite applies to point
energyListBool = ((energy > topLimit) & (point < bottomLimit))
pointListBool = ((point > topLimit) & (energy < bottomLimit))

#Step 2:
#Remove all 'true' that comes after another true since this is not valid
energyListBool[1:] &= energyListBool[1:] ^ energyListBool[:-1]
pointListBool[1:] &= pointListBool[1:] ^ pointListBool[:-1]

p = 100
e = 0

#Step 3:
#Loop through the lists, if point is true, I loose all p but gain p/valList[i] for e
#If energy is true I loose all e but gain valList[i]*e for p
for i in range(len(energyListBool)):
    if pointListBool[i] and e == 0:
        e = p/valList[i] #Trade all points to energy
        p = 0
    elif energyListBool[i] and p == 0:
        p = valList[i]*e #Trade all enery to points
        e = 0

print('p = {0} (correct for seed 2: 3.1108006690739174)'.format(p))
print('e = {0} (correct for seed 2: 0)'.format(e))

end = time.time()
print(end - start)
</code>```

What I am struggeling with is how (if it can be done) to vectorize the for-loop, so i can use that instead of the for-loop which in my mind probably would be faster.

答:
Within the current problem setting that's not possible since vectorization essentially requires that your n-th computation step shouldn't depend on previous n-1 steps. Sometimes, however, it's possible to find so-called "closed form" of a recurrence f(n) = F(f(n-1), f(n-2), ... f(n-k)), i.e. to find an explicit expression for f(n) that doesn't depend on n, but it's a separate research problem.

Moreover, from algorithmic point of view such a vectorization wouldn't give a lot, since complexity of your algorithm would still be C*n = O(n). However, since "complexity constant" C does matter in practice, there are different ways to reduce it. For example, it shouldn't be a big problem to rewrite your critical loop in C/C++.

Body:
I have an algorithm which I am implementing in python. The algorithm might be executed 1.000.000 times so I want to optimize it as much as possible. The base in the algorithm is three lists (energy, point and valList) and two counters p and e.

The two lists energy and point contains number between 0 and 1 on which I base decisions. p is a point-counter and e is an energy-counter. I can trade points for enery, and the cost of each energy is defined in valList (it is time dependent). I can also trade the otherway. But I have to trade all at once.

The outline of the algorithm:

Get a boolean-list where the elements in energy is above a threshold and the elements in point is below another threshold. This is a decision to trade energy for points. Get a corresponding list for point, which gives decision to trade points for energy

In each of the boolean-lists. Remove all true-values that comes after another true value (if i have trade all points for energy, i am not allowed to do that again point after)

For each item-pair (pB, point bool and eB, energy bool) from the two boolean lists: If pB is true and i have points, i want to trade all my points for enery. If eB is true and i have energy, i want to trade all my energy to points.

This is the implementation i have come up with:

start = time.time()
import numpy as np

np.random.seed(2) #Seed for deterministic result, just for debugging

topLimit = 0.55
bottomLimit = 0.45

#Generate three random arrays, will not be random in the real world
res = np.random.rand(500,3) #Will probably not be much longer than 500
energy = res[:,0]
point = res[:,1]
valList = res[:,2]

#Step 1:
#Generate two bools that (for ex. energy) is true when energy is above a threashold
#and point below another threshold). The opposite applies to point
energyListBool = ((energy > topLimit) & (point < bottomLimit))
pointListBool = ((point > topLimit) & (energy < bottomLimit))

#Step 2:
#Remove all 'true' that comes after another true since this is not valid
energyListBool[1:] &= energyListBool[1:] ^ energyListBool[:-1]
pointListBool[1:] &= pointListBool[1:] ^ pointListBool[:-1]

p = 100
e = 0

#Step 3:
#Loop through the lists, if point is true, I loose all p but gain p/valList[i] for e
#If energy is true I loose all e but gain valList[i]*e for p
for i in range(len(energyListBool)):
    if pointListBool[i] and e == 0:
        e = p/valList[i] #Trade all points to energy
        p = 0
    elif energyListBool[i] and p == 0:
        p = valList[i]*e #Trade all enery to points
        e = 0

print('p = {0} (correct for seed 2: 3.1108006690739174)'.format(p))
print('e = {0} (correct for seed 2: 0)'.format(e))

end = time.time()
print(end - start)

What I am struggeling with is how (if it can be done) to vectorize the for-loop, so i can use that instead of the for-loop which in my mind probably would be faster.


问:
Getting unexpectedly found nil error, but all values are there
I'm trying to add a feature to my group chat app where if an avatar is tapped on, you will be brought to a profile page which has information about that user. The framework I'm using (JSQMesssagesViewController) has a built in method for tapping the avatar, didTapAvatarImageView.

```<code>override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, at indexPath: IndexPath!) {

    let message = messages[indexPath.item]

    DispatchQueue.main.async {
        let profileVC = ProfileViewController()
        let name = message.senderDisplayName ?? ""
        let gender = self.genderDictionary.value(forKey: message.senderId) as? String ?? ""
        let status = self.statusDictionary.value(forKey: message.senderId) as? String ?? ""
        let avatarString = self.avatarDictionary.value(forKey: message.senderId) as? String ?? ""

        print("\n\nsegueTest: name: \(name), gender: \(gender), avatar: \(avatarString), status: \(status)\n\n")

        profileVC.profileImageView.loadImageUsingCacheWithUrlString(avatarString)
        profileVC.nameLabel.text = name

        switch gender {
        case "male":
            profileVC.nameLabel.textColor = UIColor(hexString: "8097E1")
        case "female":
            profileVC.nameLabel.textColor = UIColor(hexString: "E98BD5")
        default:
            profileVC.nameLabel.textColor = UIColor(hexString: "4F4F4F")
        }

        switch status {
        case "2FCB78":
            profileVC.profileGoingOutLabel.text = "\(name) wants to go out tonight!"
        case "E13F34":
            profileVC.profileGoingOutLabel.text = "\(name) is staying in tonight."
        default:
            profileVC.profileGoingOutLabel.text = "\(name) might want to go out tonight - let them know what the plans are!"
        }

        self.performSegue(withIdentifier: "chatToProfile", sender: self)
    }
}
</code>```

When I tap on an avatar, I get the unexpectedly found nil crash - but my print statement prints the values with no problem, so they do exist. I'm not sure where I'm going wrong here, as Xcode does not show me which value in nil, and as I said the values I'm trying to pass do indeed exist.

What can I do to solve this error?

答:
you need to declare string property for all label which is displayed to through previous view controller in profileVC.

```<code>var strName : String
</code>```

In viewDidLoad

```<code>nameLabel.text = strName
</code>```

In previous viewcontroller

```<code>profileVC.strName = yourstring
</code>```

If use prepareForSegue then you need to pass data in this method instead of didSelect.

If you want to pass data on didSelect without prepareForSegue then you need to create instance of viewcontroller as below.

Correct following code it is only for explanation

```<code>let profileVC = self.storyboard.initiatedwithidentifier: "yourViewcontrollerIdentifier"
profileVC.strName = yourString
self.navigationviewcontroller(profileVc, animated : true)
</code>```

Body:
I'm trying to add a feature to my group chat app where if an avatar is tapped on, you will be brought to a profile page which has information about that user. The framework I'm using (JSQMesssagesViewController) has a built in method for tapping the avatar, didTapAvatarImageView.

override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, at indexPath: IndexPath!) {

    let message = messages[indexPath.item]

    DispatchQueue.main.async {
        let profileVC = ProfileViewController()
        let name = message.senderDisplayName ?? ""
        let gender = self.genderDictionary.value(forKey: message.senderId) as? String ?? ""
        let status = self.statusDictionary.value(forKey: message.senderId) as? String ?? ""
        let avatarString = self.avatarDictionary.value(forKey: message.senderId) as? String ?? ""

        print("\n\nsegueTest: name: \(name), gender: \(gender), avatar: \(avatarString), status: \(status)\n\n")

        profileVC.profileImageView.loadImageUsingCacheWithUrlString(avatarString)
        profileVC.nameLabel.text = name

        switch gender {
        case "male":
            profileVC.nameLabel.textColor = UIColor(hexString: "8097E1")
        case "female":
            profileVC.nameLabel.textColor = UIColor(hexString: "E98BD5")
        default:
            profileVC.nameLabel.textColor = UIColor(hexString: "4F4F4F")
        }

        switch status {
        case "2FCB78":
            profileVC.profileGoingOutLabel.text = "\(name) wants to go out tonight!"
        case "E13F34":
            profileVC.profileGoingOutLabel.text = "\(name) is staying in tonight."
        default:
            profileVC.profileGoingOutLabel.text = "\(name) might want to go out tonight - let them know what the plans are!"
        }

        self.performSegue(withIdentifier: "chatToProfile", sender: self)
    }
}

When I tap on an avatar, I get the unexpectedly found nil crash - but my print statement prints the values with no problem, so they do exist. I'm not sure where I'm going wrong here, as Xcode does not show me which value in nil, and as I said the values I'm trying to pass do indeed exist.

What can I do to solve this error?

Body:
you need to declare string property for all label which is displayed to through previous view controller in profileVC.

var strName : String

In viewDidLoad

nameLabel.text = strName

In previous viewcontroller

profileVC.strName = yourstring

If use prepareForSegue then you need to pass data in this method instead of didSelect.

If you want to pass data on didSelect without prepareForSegue then you need to create instance of viewcontroller as below.

Correct following code it is only for explanation

let profileVC = self.storyboard.initiatedwithidentifier: "yourViewcontrollerIdentifier"
profileVC.strName = yourString
self.navigationviewcontroller(profileVc, animated : true)


问:
How to wait for a barcode reader input without freezing the main thread of my program?
i'm writing a program using C++ that finds an object on a video, then the user must scan, with a barcode reader, some code in a list, then if the code is correct, the information is sent to a table in MySql.

i am stuck in the part of waiting for the user to scan the barcode. if i use a loop then the program gets frezed, so maybe i must wait for some keyboard event(because the barcode behaves like it), but this function can't continue if the code hasn't been readed.

so any one can point me what is the best way to do it?..

答:
If your barcode scanner is attached as a keyboard as many of them are, then you need asynchronous IO.
Here is example how to read from keyboard without blocking.

C non-blocking keyboard input

ContentLicense: CC BY-SA 4.0


问:
z-index not working between image and text box
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

```<code><a href="#">
  <img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" />
  <div class="text">
    This is some text.
  </div>
</a>
</code>```

CSS:

```<code>a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}
</code>```

答:
use this one:

```<code><html>
<head>
<style>
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
opacity:.5
}
</style>
</head>
<body>

<h1>This is a heading</h1>

<img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" width="500" height="140">
</code>```

Because the image has a z-index of -1, it will be placed behind the text.

Body:
JSFiddle

I have an image with a text box below. I scaled the image, and it goes over the text box, i wan't the text box to be on top of the image, but it is not working with z-index.

HTML:

    This is some text.

CSS:

a {
  height:400px;
  width:200px;
  display:block;
  text-decoration:none;
  color:black;
  overflow:hidden;
}

img {
  transform: scale(1.1);
}

a:hover .text {
  color:white;
  background-color:black;
}

.text {
  text-align:center;
  height:200px;
  margin-top:-4px;
  background-color:white;
  transition:all 1s ease;
}

Body:
use this one:

<html>
<head>
<style>
img {
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
opacity:.5
}
</style>
</head>
<body>

<h1>This is a heading</h1>

<img src="http://images.meredith.com/content/dam/bhg/Images/2009/07/101422234.jpg.rendition.200sq.jpg" width="500" height="140">

Because the image has a z-index of -1, it will be placed behind the text.


问:
How to get the user who is assigned a test case in TestLink with TestLink-API-Python-client
Is there any way to get the tester/user assigned to a test case with TestLink-API-Python-client?

With this command, I am able to assign a test case to a user, but I want to check if the test case is already assigned to some other tester or not.

```<code>>>> tls.assignTestCaseExecutionTask('abc', 178775, 'TC-86',buildname='mytestbuild')
{'status': True, 'args': {'testplanid': 178775, 'buildid': '164', 'testcaseid': 187201, 'action': 'assignOne', 'user': 'abc', 'buildname': 'mytestbuild', 'testcaseexternalid': 'TC-86'}}
</code>```

If I execute this multiple times, it behaves same (ideally there should be a message that the test case is already assigned to the user). I am unable to figure out a way using which I can find the details of a user which is assigned a test case.

答:
I have resolved the issue using getTestCaseAssignedTester method.

```<code>tls.whatArgs('getTestCaseAssignedTester')
'getTestCaseAssignedTester(<testplanid>, <testcaseexternalid>, [buildid=<buildid>], [buildname=<buildname>], [platformid=<platformid>], [platformname=<platformname>], [devKey=<devKey>])\n Gets the result of LAST EXECUTION for a particular testcase on a \n        test plan.\n        \n        testplanid           test plan id\n        testcaseexternalid   format PREFIX-NUMBER\n        \n        args variations:     buildid - buildname \n                             platformid - platformname\n        build information is general mandatory\n        platform information is required, when test plan has assigned platforms\n        '
</code>```

Body:
Is there any way to get the tester/user assigned to a test case with TestLink-API-Python-client?

With this command, I am able to assign a test case to a user, but I want to check if the test case is already assigned to some other tester or not.

>>> tls.assignTestCaseExecutionTask('abc', 178775, 'TC-86',buildname='mytestbuild')
{'status': True, 'args': {'testplanid': 178775, 'buildid': '164', 'testcaseid': 187201, 'action': 'assignOne', 'user': 'abc', 'buildname': 'mytestbuild', 'testcaseexternalid': 'TC-86'}}

If I execute this multiple times, it behaves same (ideally there should be a message that the test case is already assigned to the user). I am unable to figure out a way using which I can find the details of a user which is assigned a test case.

Body:
I have resolved the issue using getTestCaseAssignedTester method.

tls.whatArgs('getTestCaseAssignedTester')
'getTestCaseAssignedTester(<testplanid>, <testcaseexternalid>, [buildid=<buildid>], [buildname=<buildname>], [platformid=<platformid>], [platformname=<platformname>], [devKey=<devKey>])\n Gets the result of LAST EXECUTION for a particular testcase on a \n        test plan.\n        \n        testplanid           test plan id\n        testcaseexternalid   format PREFIX-NUMBER\n        \n        args variations:     buildid - buildname \n                             platformid - platformname\n        build information is general mandatory\n        platform information is required, when test plan has assigned platforms\n        '


问:
System.Web.Helpers not found in VS2015
I'm trying to add some JSON parsing to the C# code in VS2015 but I can't find:

System.Web.Helpers

as the MS documentation suggests.  I've looked at other people's questions of a similar nature (almost all on earlier versions) and the answers all say to add it in the Assemblies / Framework dialog.

The problem is it doesn't appear in that dialog, nor do many of the other things I see people talking about.

I would really appreciate any help on fixing this.

Here is the list I have access to:

Edit: Added the Extensions window as well

答: This question is a bit old but here's a simple solution - Microsoft seemed to just move this library to a Nuget package called "microsoft-web-helpers". Installing that package seems to be equivalent to having the assembly. </p>

Title: System.Web.Helpers not found in VS2015


问:
Getting error message as Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd'
I am trying to deploy a Mule app on Mule standalone 3.8.1, but I am getting this error message:

```<code>Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) ~[?:?]
</code>```

It works fine when running from Anypoint Studio using Mule server 3.8.2 EE.

答: The standalone Mule runtime must also be an EE version for DataWeave to work. Is your 3.8.1 an EE version?</p>

Body:
I am trying to deploy a Mule app on Mule standalone 3.8.1, but I am getting this error message:

Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) ~[?:?]

It works fine when running from Anypoint Studio using Mule server 3.8.2 EE.


问:
Query syntax for nanoscale.io Store
Does anyone know how to use the query strings for accessing Store (collection) data in Nanoscale.io? I've tried to read their documentation but the only example is given below:

```<code>local.request = new AP.Store.Request();
local.request.select("Tasks", "priority >= $1 order numeric(priority) asc", parseInt(request.params.priority));
</code>```

I don't know where the syntax in "priority >= $1 order numeric(priority) asc" is from...

In their docs:

select(collection, query)

Selects matching objects from a collection based off of the query
  string.

collection [string] - Collection name.

query [string | number] - This can be either a query or a number. If a
  number, the operation will return the object that has a matching ID.
  To return all, use the string "true".

Apart from "true" I don't know how I can form my own queries.

答:
In the example you provided (and provided in the documentation), priority would be the field within your collection that you're interested in searching for and $1 is the next value provided in the select function, i.e. parseInt(request.params.priority). request.params.priority is the value of the query parameter "priority", which in this case is being parsed into an int for the sake of comparison.

From what I've found you can do the all the basic comparisons (=,!=,>(=),<(=)).

Title: Query syntax for nanoscale.io Store

Body:
Does anyone know how to use the query strings for accessing Store (collection) data in Nanoscale.io? I've tried to read their documentation but the only example is given below:

local.request = new AP.Store.Request();
local.request.select("Tasks", "priority >= $1 order numeric(priority) asc", parseInt(request.params.priority));

I don't know where the syntax in "priority >= $1 order numeric(priority) asc" is from...

In their docs:

select(collection, query)

Selects matching objects from a collection based off of the query
  string.

collection [string] - Collection name.

query [string | number] - This can be either a query or a number. If a
  number, the operation will return the object that has a matching ID.
  To return all, use the string "true".

Apart from "true" I don't know how I can form my own queries.


问:
Drop Duplicates and Add Values Pandas
I have a dataframe below. I would like to drop the duplicates, but add the duplicated value from the E column to the non-duplicated record

```<code>import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,6,7],
                    'B' : [1,1,3,5,0,0,np.NaN,9,0,0],
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'],
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Allign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)
</code>```

I'm grabbing all the duplicates:

```<code>df2 = dfp.loc[(dfp['A'].duplicated(keep=False))].copy()

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign
1  NaN  1.0  AA1233445    123456.0      Allign
2  3.0  3.0      rmacy   1234567.0       Hello
4  5.0  0.0   Ab123455     12345.0  Appreciate
5  5.0  0.0   TV192837     12345.0        Undo
6  3.0  NaN         RX  12345678.0     Testing
</code>```

and would like my outcome to be:

```<code>     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign Allign
2  3.0  3.0      rmacy   1234567.0      Hello Testing
4  5.0  0.0   Ab123455     12345.0      Appreciate Undo
</code>```

I know I need to use dfp.loc[(dfp['A'].duplicated(keep='last'))].copy() to grab the first occurrence, but I'm failing to set the value of the E column to include the other duplicated values.

I'm thinking I need to try something like:

```<code>df3 = dfp.loc[(dfp['A'].duplicated(keep='last'))].copy()
df3['E'] = df3['E'] + dfp.loc[(dfp['A'].duplicated(keep=False).copy()),'E']
</code>```

but my output is:

```<code>     A    B          C          D                     E
0  NaN  1.0  AA1233445   123456.0          AssignAssign
2  3.0  3.0      rmacy  1234567.0            HelloHello
4  5.0  0.0   Ab123455    12345.0  AppreciateAppreciate
</code>```

I'm stumped. Am I over complicating it? How can I get the output I'm looking for so that I can later drop all the duplicates, except the first, but 'save' the values of the dropped vlaues in the E Column?

答:
Define functions to use in agg and use within groupby.  In order to get groupby to work with NaN, I converted to strings then back to floats.

```<code>f = {c: ' '.join if c == 'E' else 'first' for c in ['B', 'C', 'D', 'E']}

dfp.groupby(
    dfp.A.astype(str), sort=False
).agg(f).reset_index().eval(
    'A = @pd.to_numeric(A, "coerce").values',
    inplace=False
)

     A    B           C            D                E
0  NaN  1.0   AA1233445     123456.0    Assign Allign
1  3.0  3.0       rmacy    1234567.0    Hello Testing
2  4.0  5.0    Idaho Rx   12345678.0             Ugly
3  5.0  0.0    Ab123455      12345.0  Appreciate Undo
4  1.0  9.0  Ohio Drugs  123456789.0         Unicycle
5  6.0  0.0     RX12345    1234567.0           Pharma
6  7.0  0.0  USA Pharma          NaN          Unicorn
</code>```

Limiting it to just the duplicated rows:

```<code>f = {c: ' '.join if c == 'E' else 'first' for c in ['B', 'C', 'D', 'E']}
d1 = dfp[dfp.duplicated('A', keep=False)]
d2 = d1.groupby(d1.A.astype(str), sort=False).agg(f).reset_index()
d2.A = d2.A.astype(float)
</code>```

d2

```<code>     A    B          C          D                E
0  NaN  1.0  AA1233445   123456.0    Assign Allign
1  3.0  3.0      rmacy  1234567.0    Hello Testing
2  5.0  0.0   Ab123455    12345.0  Appreciate Undo
</code>```

Title: Drop Duplicates and Add Values Pandas

Body:
I have a dataframe below. I would like to drop the duplicates, but add the duplicated value from the E column to the non-duplicated record

import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,6,7],
                    'B' : [1,1,3,5,0,0,np.NaN,9,0,0],
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'],
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Allign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)

I'm grabbing all the duplicates:

df2 = dfp.loc[(dfp['A'].duplicated(keep=False))].copy()

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign
1  NaN  1.0  AA1233445    123456.0      Allign
2  3.0  3.0      rmacy   1234567.0       Hello
4  5.0  0.0   Ab123455     12345.0  Appreciate
5  5.0  0.0   TV192837     12345.0        Undo
6  3.0  NaN         RX  12345678.0     Testing

and would like my outcome to be:

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign Allign
2  3.0  3.0      rmacy   1234567.0      Hello Testing
4  5.0  0.0   Ab123455     12345.0      Appreciate Undo

I know I need to use dfp.loc[(dfp['A'].duplicated(keep='last'))].copy() to grab the first occurrence, but I'm failing to set the value of the E column to include the other duplicated values.

I'm thinking I need to try something like:

df3 = dfp.loc[(dfp['A'].duplicated(keep='last'))].copy()
df3['E'] = df3['E'] + dfp.loc[(dfp['A'].duplicated(keep=False).copy()),'E']

but my output is:

     A    B          C          D                     E
0  NaN  1.0  AA1233445   123456.0          AssignAssign
2  3.0  3.0      rmacy  1234567.0            HelloHello
4  5.0  0.0   Ab123455    12345.0  AppreciateAppreciate

I'm stumped. Am I over complicating it? How can I get the output I'm looking for so that I can later drop all the duplicates, except the first, but 'save' the values of the dropped vlaues in the E Column?

Body:
Define functions to use in agg and use within groupby.  In order to get groupby to work with NaN, I converted to strings then back to floats.

f = {c: ' '.join if c == 'E' else 'first' for c in ['B', 'C', 'D', 'E']}

dfp.groupby(
    dfp.A.astype(str), sort=False
).agg(f).reset_index().eval(
    'A = @pd.to_numeric(A, "coerce").values',
    inplace=False
)

     A    B           C            D                E
0  NaN  1.0   AA1233445     123456.0    Assign Allign
1  3.0  3.0       rmacy    1234567.0    Hello Testing
2  4.0  5.0    Idaho Rx   12345678.0             Ugly
3  5.0  0.0    Ab123455      12345.0  Appreciate Undo
4  1.0  9.0  Ohio Drugs  123456789.0         Unicycle
5  6.0  0.0     RX12345    1234567.0           Pharma
6  7.0  0.0  USA Pharma          NaN          Unicorn

Limiting it to just the duplicated rows:

f = {c: ' '.join if c == 'E' else 'first' for c in ['B', 'C', 'D', 'E']}
d1 = dfp[dfp.duplicated('A', keep=False)]
d2 = d1.groupby(d1.A.astype(str), sort=False).agg(f).reset_index()
d2.A = d2.A.astype(float)

d2

     A    B          C          D                E
0  NaN  1.0  AA1233445   123456.0    Assign Allign
1  3.0  3.0      rmacy  1234567.0    Hello Testing
2  5.0  0.0   Ab123455    12345.0  Appreciate Undo