问:
Facebook SDK dependency conflict
I am having this error:

On getting dependency tree, I found that there is nothing wrong with animated vector drawables but facebook's latest sdk has previous version of support-v4 custom tab. I tried excluding with exclude group command but its not working. Here is my dependency tree:

```<code> +--- com.facebook.android:facebook-android-sdk:4.26.0@aar
|    +--- com.android.support:support-v4:26.0.1@aar
|    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-media-compat:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-core-utils:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:support-fragment:26.0.1@aar
|    |         +--- com.android.support:support-compat:26.0.1@aar
|    |         |    \--- com.android.support:support-annotations:26.0.1@jar
|    |         +--- com.android.support:support-core-ui:26.0.1@aar
|    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |         \--- com.android.support:support-core-utils:26.0.1@aar
|    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |              \--- com.android.support:support-compat:26.0.1@aar
|    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:appcompat-v7:26.0.1@aar
|    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-v4:26.0.1@aar
|    |    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-media-compat:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-core-utils:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-fragment:26.0.1@aar
|    |    |         +--- com.android.support:support-compat:26.0.1@aar
|    |    |         |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    |         +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |         \--- com.android.support:support-core-utils:26.0.1@aar
|    |    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |    |              \--- com.android.support:support-compat:26.0.1@aar
|    |    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-vector-drawable:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:animated-vector-drawable:26.0.1@aar
|    |         +--- com.android.support:support-vector-drawable:26.0.1@aar
|    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |         \--- com.android.support:support-core-ui:26.0.1@aar
|    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |              \--- com.android.support:support-compat:26.0.1@aar
|    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:cardview-v7:26.0.1@aar
|    |    \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:customtabs:25.3.1@aar
|    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.parse.bolts:bolts-android:1.4.0@jar
|    |    +--- com.parse.bolts:bolts-tasks:1.4.0@jar
|    |    \--- com.parse.bolts:bolts-applinks:1.4.0@jar
|    |         \--- com.parse.bolts:bolts-tasks:1.4.0@jar
|    \--- com.google.zxing:core:3.3.0@jar
</code>```

I want to use latest appcompat library as I want to support Oreo. Can someone guide me on this? Also, isn't this facebook's fault to use older dependency for custom tabs? Thank you very much for your time and assistance in this matter.

答:
For facebook-android-sdk:4.28.0 the list is a bit longer ;)

```<code>implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.android.support:customtabs:26.1.0'
implementation 'com.android.support:support-annotations:26.1.0'
implementation 'com.android.support:support-core-utils:26.1.0'
implementation('com.facebook.android:facebook-android-sdk:4.28.0') {
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'appcompat-v7'
    exclude group: 'com.android.support', module: 'cardview-v7'
    exclude group: 'com.android.support', module: 'customtabs'
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.android.support', module: 'support-core-utils'
}
</code>```

Title: Facebook SDK dependency conflict

Body:
I am having this error:

On getting dependency tree, I found that there is nothing wrong with animated vector drawables but facebook's latest sdk has previous version of support-v4 custom tab. I tried excluding with exclude group command but its not working. Here is my dependency tree:

 +--- com.facebook.android:facebook-android-sdk:4.26.0@aar
|    +--- com.android.support:support-v4:26.0.1@aar
|    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-media-compat:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-core-utils:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:support-fragment:26.0.1@aar
|    |         +--- com.android.support:support-compat:26.0.1@aar
|    |         |    \--- com.android.support:support-annotations:26.0.1@jar
|    |         +--- com.android.support:support-core-ui:26.0.1@aar
|    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |         \--- com.android.support:support-core-utils:26.0.1@aar
|    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |              \--- com.android.support:support-compat:26.0.1@aar
|    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:appcompat-v7:26.0.1@aar
|    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-v4:26.0.1@aar
|    |    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-media-compat:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-core-utils:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-fragment:26.0.1@aar
|    |    |         +--- com.android.support:support-compat:26.0.1@aar
|    |    |         |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    |         +--- com.android.support:support-core-ui:26.0.1@aar
|    |    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    |         \--- com.android.support:support-core-utils:26.0.1@aar
|    |    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |    |              \--- com.android.support:support-compat:26.0.1@aar
|    |    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    |    +--- com.android.support:support-vector-drawable:26.0.1@aar
|    |    |    +--- com.android.support:support-annotations:26.0.1@jar
|    |    |    \--- com.android.support:support-compat:26.0.1@aar
|    |    |         \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:animated-vector-drawable:26.0.1@aar
|    |         +--- com.android.support:support-vector-drawable:26.0.1@aar
|    |         |    +--- com.android.support:support-annotations:26.0.1@jar
|    |         |    \--- com.android.support:support-compat:26.0.1@aar
|    |         |         \--- com.android.support:support-annotations:26.0.1@jar
|    |         \--- com.android.support:support-core-ui:26.0.1@aar
|    |              +--- com.android.support:support-annotations:26.0.1@jar
|    |              \--- com.android.support:support-compat:26.0.1@aar
|    |                   \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:cardview-v7:26.0.1@aar
|    |    \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.android.support:customtabs:25.3.1@aar
|    |    +--- com.android.support:support-compat:26.0.1@aar
|    |    |    \--- com.android.support:support-annotations:26.0.1@jar
|    |    \--- com.android.support:support-annotations:26.0.1@jar
|    +--- com.parse.bolts:bolts-android:1.4.0@jar
|    |    +--- com.parse.bolts:bolts-tasks:1.4.0@jar
|    |    \--- com.parse.bolts:bolts-applinks:1.4.0@jar
|    |         \--- com.parse.bolts:bolts-tasks:1.4.0@jar
|    \--- com.google.zxing:core:3.3.0@jar

I want to use latest appcompat library as I want to support Oreo. Can someone guide me on this? Also, isn't this facebook's fault to use older dependency for custom tabs? Thank you very much for your time and assistance in this matter.

Body:
For facebook-android-sdk:4.28.0 the list is a bit longer ;)

implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.android.support:customtabs:26.1.0'
implementation 'com.android.support:support-annotations:26.1.0'
implementation 'com.android.support:support-core-utils:26.1.0'
implementation('com.facebook.android:facebook-android-sdk:4.28.0') {
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'appcompat-v7'
    exclude group: 'com.android.support', module: 'cardview-v7'
    exclude group: 'com.android.support', module: 'customtabs'
    exclude group: 'com.android.support', module: 'support-annotations'
    exclude group: 'com.android.support', module: 'support-core-utils'
}


来源: stackexchange

问:
Resize windows Event
I'm creating a simple OS app but I cannot find anywhere how to take the resize event.

Let's assume that I wanna print the new width and height and I have this controller:

```<code>class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }

}
</code>```

What i have to add? Thank you.

My question is not the same as Listen for window resize event in Swift / Objective-C. Since my View have to extend NSViewController and not NSWindowController. This in his answer he did not explain what windowWillResize has to return exactly

答:
Swift 4 - macOS 10.13

```<code>class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidAppear() {
        view.window?.delegate = self
    }

    func windowDidResize(_ notification: Notification) {
        // This will print the window's size each time it is resized.
        print(view.window?.frame.size)
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Resize windows Event

Body:
I'm creating a simple OS app but I cannot find anywhere how to take the resize event.

Let's assume that I wanna print the new width and height and I have this controller:

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }

}

What i have to add? Thank you.

My question is not the same as Listen for window resize event in Swift / Objective-C. Since my View have to extend NSViewController and not NSWindowController. This in his answer he did not explain what windowWillResize has to return exactly

Body:
Swift 4 - macOS 10.13

class ViewController: NSViewController, NSWindowDelegate {

    override func viewDidAppear() {
        view.window?.delegate = self
    }

    func windowDidResize(_ notification: Notification) {
        // This will print the window's size each time it is resized.
        print(view.window?.frame.size)
    }
}


问:
Inherit jquery code when loaded with ajax
I've got some jquery code to style some checkboxes on my page. I also have a table. This table doesn't show all rows when the page is loaded sans you have to load the rest of the rows with an ajax request. The problem is that the checkboxes in that ajax loaded rows won't be styled. I want to inherit the checkboxes styling to those checkboxes that have been loaded with ajax.</p>

答:
Once the new checkboxes are loaded, you'll have to trigger your jQuery code to style those checkboxes (and only the new ones). Without seeing your code or markup it's impossible to give you a direct answer, but for instance, suppose your jQuery code adds a class to the checkboxes (presumably as part of, not all of, what it does; otherwise you'd just use CSS for styling). Then you'd simply have that code be sure to leave out those checkboxes:

```<code>var cbsToStyle = $(":checkbox:not(.foo)");
</code>```

...and then style the cbsToStyle list.

Example (live copy):

HTML (obviously not the same as yours, but indicative):

```<code><div id='container'>
  <label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
</div>
</code>```

JavaScript using jQuery:

```<code>jQuery(function($) {
  var timer = 0,
      counter = 4;

  styleCheckboxes();
  timer = setInterval(loadCheckboxes, 1000);

  function loadCheckboxes() {
    var index;

    if (--counter < 0) {
      // Done
      cancelInterval(timer);
      timer = 0;
    }
    else {
      // Mimic adding three checkboxes
      for (index = 0; index < 3; ++index) {
        $("<br><label><input type='checkbox'>Another checkbox</label>").appendTo('#container');
      }

      // Re-trigger the styling code
      styleCheckboxes();
    }
  }

  function styleCheckboxes() {
    // Get only those we haven't styled before and style them.
    // Note that the class is used as a marker (you might _also_
    // use it to apply some style rules)
    $(":checkbox:not(.styled)").addClass("styled").css("width", "40px");
  }

});
</code>```

...where styleCheckboxes is the most relevant bit.

ContentLicense: CC BY-SA 2.5

Body:
Once the new checkboxes are loaded, you'll have to trigger your jQuery code to style those checkboxes (and only the new ones). Without seeing your code or markup it's impossible to give you a direct answer, but for instance, suppose your jQuery code adds a class to the checkboxes (presumably as part of, not all of, what it does; otherwise you'd just use CSS for styling). Then you'd simply have that code be sure to leave out those checkboxes:

var cbsToStyle = $(":checkbox:not(.foo)");

...and then style the cbsToStyle list.

Example (live copy):

HTML (obviously not the same as yours, but indicative):

<div id='container'>
  <label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
  <br><label><input type='checkbox'>Original checkbox</label>
</div>

JavaScript using jQuery:

jQuery(function($) {
  var timer = 0,
      counter = 4;

  styleCheckboxes();
  timer = setInterval(loadCheckboxes, 1000);

  function loadCheckboxes() {
    var index;

    if (--counter < 0) {
      // Done
      cancelInterval(timer);
      timer = 0;
    }
    else {
      // Mimic adding three checkboxes
      for (index = 0; index < 3; ++index) {
        $("<br><label><input type='checkbox'>Another checkbox</label>").appendTo('#container');
      }

      // Re-trigger the styling code
      styleCheckboxes();
    }
  }

  function styleCheckboxes() {
    // Get only those we haven't styled before and style them.
    // Note that the class is used as a marker (you might _also_
    // use it to apply some style rules)
    $(":checkbox:not(.styled)").addClass("styled").css("width", "40px");
  }

});

...where styleCheckboxes is the most relevant bit.


问:
Azure SQL Server Elastic Pool - automatically add database to pool
Currently we have an Azure SQL Server and each time we create new web app, we use EF Core Code First to generate the database. However after the database is created we manually go to Azure portal and add the newly created database to the Elastic Pool inside the Azure SQL Server. Is it possible to somehow automate the process so that each newly created database either via portal or generated using EF or whatever, it will be automatically added to the Pool?</p>

答:
You have to use the Elastic database client library to manage the creation of the DB so that the ShardMapManager can register the database.  Note that I said database (or shard in Elastic DB terminology) NOT Tenant (or Shardlet in Elastic DB terminology).

The entire Elastic DB components are as follows for SQL server, sharding was added via the Elastic Database SDK which involves the following components (some of which are available only in Azure):
•   Elastic Database Client Library
Manage the data distributions and map Tenants to databases.
•   Elastic Database Pools (Azure only)
Allocation of a pool of resources that can be shared across a number of databases.  Allows for database to consumer resources at their own rate, rather than each database having a specific amount of resources that are available.

•   Elastic Database Query
The ability to query across all Tenants within a Multi-Tenant database.

•   Elastic Database Jobs
Package and reliably deploy database maintenance operations or database schema changes to multiple databases.

•   Elastic Transactions
Process changes to several databases in an atomic and isolated way.

•   Elastic Database Split-Merge Tools
Allows for the movement of shards between databases that are participating in the sharding framework

Important concepts using this library is that a Shard can have one or mapping to hold Shardlets (or mappings from the ShardMapManager).  In fact the ShardMapManager maintains two collections: Shards (getShards), and Mapping (GetMappings).  Mappings are ShardKeys are MAPPED to the Shard...

You have can two types of Shard Key definitions: RangeMapShard, and ListMapShard - both which inherit ShardMap (which contains a property ShardMapType to define the subtype that instantiated the ShardMap).

RangeMapShard - hold a RANGE of keys for ONE mapping.. e.g. customer 100-200 (200 is one higher in value than what is allowed in the range (crappy way of defining it in my opinion... but that is MS documentation) so what they mean is 100-199, 200-299 is defined using ranges of 100-200, and 200-300.

ListMapShard - hold one Shard Key for each Shardlet.  So 1 value of a ShardKey is equal to 1 ShardMap ( a Shard can hold one or more Shardlets - so a Shard can hold mappings... )...

So you have to map your shard key(s) to a shard map, and then associated the shard map to a shard, and the shard has to be associated with a Database ....  remember, you can create a database that does not have a shard (or schema) defined within it.

I found that I wanted to think of this the other way around, starting from the DB, and sticking in the data into that DB.  IMO, the Elastic DB SDK works the other way, you define the Shardlet (tenant), map that to shard(schema), and then stick the Shard(schema) into a database.

HTH.


问:
C# EF DefaultIfEmpty with Where().Select()
Is there a way similar to what we can do with linq for left outer join with method based query syntax.

e.g.

```<code>var a = from m in context.MainClass
        join r in context.RefClass on m.RefID equals r.ID into joinedent
        from j in joinedent.DefaultIfEmpty()
        select new { m.Name , j.TypeName }
</code>```

Can I convert this into method based syntax with navigation property default if null

```<code>var a = context.MainClass.Select(x=> new {
               m.Name
               m.RefClass.TypeName // here need default if RefClass is null
        })
</code>```

I can do like (m.RefClass != null)?m.RefClass.TypeName:""   but would like to know if there is a proper way to do this like in above linq.

Thanks

答:
Just use new initialization in DefaultIfEmpty parameter

```<code>var a = from m in context.MainClass
    join r in context.RefClass on m.RefID equals r.ID on joinedent
    from j in joinedent.DefaultIfEmpt(new RefClass())
    select new { m.Name , j.TypeName }
</code>```

Hope the problem will be solve

ContentLicense: CC BY-SA 4.0

Body:
Is there a way similar to what we can do with linq for left outer join with method based query syntax.

e.g.

var a = from m in context.MainClass
        join r in context.RefClass on m.RefID equals r.ID into joinedent
        from j in joinedent.DefaultIfEmpty()
        select new { m.Name , j.TypeName }

Can I convert this into method based syntax with navigation property default if null

var a = context.MainClass.Select(x=> new {
               m.Name
               m.RefClass.TypeName // here need default if RefClass is null
        })

I can do like (m.RefClass != null)?m.RefClass.TypeName:""   but would like to know if there is a proper way to do this like in above linq.

Thanks

Body:
Just use new initialization in DefaultIfEmpty parameter

var a = from m in context.MainClass
    join r in context.RefClass on m.RefID equals r.ID on joinedent
    from j in joinedent.DefaultIfEmpt(new RefClass())
    select new { m.Name , j.TypeName }

Hope the problem will be solve


问:
Navigate between Screens
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

```<code>let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)
</code>```

答:
Since it is interconnected . pushToViewController or popTOViewController or dismiss is not worked. so I have used unwind.

StoreDetailsController:
I have below code in  StoreDetailsController

```<code>@IBAction func unwindToVC1(segue:UIStoryboardSegue) {
        print("Test")
    }
</code>```

In my ShoppingListViewController I have unwind Done bar button to exit.

```<code> @IBAction func done(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "unwindSegueToVC1", sender: self)
       }
</code>```

you can follow the below link for unwind

https://medium.com/@mimicatcodes/create-unwind-segues-in-swift-3-8793f7d23c6f

Title: Navigate between Screens

Body:
In my application,I have complex navigation.

I have Shopping Details .Which is View Controller of Tab bar controller.

When I select the any Store Name from Shopping Details View Controller .It will pop to a Shopping List View Controller which is embed in Navigation Controller.

When Select the Edit Button from Shopping List View Controller .It will pop to another View controller which ADD Screen. It is also embed in Navigation Controller

When I click save from Add Screen .It will go to the Shopping List View Controller

When I click Done button from the Shopping List View Controller  .I have to navigate to  Shopping Details View Controller of Tab bar controller.

Please provide me input. How to traverse to Tab Bar Controller ?

I have tried below Code. It is navigate to StoreDetails View Controller.Not displaying Tab Bar Items

let storeDetails = self.storyboard?.instantiateViewController(withIdentifier: "StoreDetailsController") as! StoreDetailsController
        storeDetails.managedContext = managedContext
        storeDetails.coreData = coreData
        storeDetails.back = true
self.navigationController?.pushViewController(storeDetails, animated: false)

Body:
Since it is interconnected . pushToViewController or popTOViewController or dismiss is not worked. so I have used unwind.

StoreDetailsController:
I have below code in  StoreDetailsController

@IBAction func unwindToVC1(segue:UIStoryboardSegue) {
        print("Test")
    }

In my ShoppingListViewController I have unwind Done bar button to exit.

 @IBAction func done(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "unwindSegueToVC1", sender: self)
       }

you can follow the below link for unwind

https://medium.com/@mimicatcodes/create-unwind-segues-in-swift-3-8793f7d23c6f


问:
iPython macros operations
I am an engineer and I use a python REPL as an advanced calculator while working. I use the "previous output" feature of the REPL, which is _, often.

```<code>>>>45*0.344
15.48
>>>_*2
30.96
</code>```

Something like that.

For some reason I find it kind of a chore to type the underscore though. I've used the Haskell REPL, which uses "it" as the previous output variable, which I find easier to type.

I learned that iPython lets you define macros that execute some code. So I popped open an iPython shell and defined a %macro called "it" that mimics the "_".

```<code>In [1]: _
Out[1]: ''

In [2]: %macro it 1
Macro `it` created. To execute, type its name (without quotes).
=== Macro contents: ===
_
</code>```

I can call "it" like so:

```<code>In [1]: 4
Out[1]: 4

In [2]: it
Out[2]: 4
</code>```

However, when I try to do something with "it" like it*4, I get the error unsupported operand type(s) for *: 'Macro' and 'int'.

I want "it" to be the type it's returning instead of the type Macro, so that I can use it just like I use "_".

答:
When I try that I get

```<code>In [329]: it.value
Out[329]: '_\n'
</code>```

The macro includes the '\n'.  So a stand alone it behaves ok. But it can't be used in-line.

Title: iPython macros operations

Body:
I am an engineer and I use a python REPL as an advanced calculator while working. I use the "previous output" feature of the REPL, which is _, often.

>>>45*0.344
15.48
>>>_*2
30.96

Something like that.

For some reason I find it kind of a chore to type the underscore though. I've used the Haskell REPL, which uses "it" as the previous output variable, which I find easier to type.

I learned that iPython lets you define macros that execute some code. So I popped open an iPython shell and defined a %macro called "it" that mimics the "_".

In [1]: _
Out[1]: ''

In [2]: %macro it 1
Macro `it` created. To execute, type its name (without quotes).
=== Macro contents: ===
_

I can call "it" like so:

In [1]: 4
Out[1]: 4

In [2]: it
Out[2]: 4

However, when I try to do something with "it" like it*4, I get the error unsupported operand type(s) for *: 'Macro' and 'int'.

I want "it" to be the type it's returning instead of the type Macro, so that I can use it just like I use "_".

Body:
When I try that I get

In [329]: it.value
Out[329]: '_\n'

The macro includes the '\n'.  So a stand alone it behaves ok. But it can't be used in-line.


问:
How to get additional claims on client side in identity server 4?
In my identity server's Startup.cs file, I have server configured as below. I am using asp.net identity for user management.

```<code>services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

services.AddTransient<IProfileService, ProfileService>();
</code>```

My IdentiyResources are as follow. Here I want to return extra claim as IS_Token which I want to use for some further business logic of my application.

```<code>public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    new IdentityResource("IS_token", new []{ "IS_token" } ),
                };
        }
</code>```

I'm also adding this claim in IssuedClaims inside my IProfileService as below.

```<code>public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        public ProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
        {
            _userManager = userManager;
            _claimsFactory = claimsFactory;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            var principal = await _claimsFactory.CreateAsync(user);

            var claims = principal.Claims.ToList();
            claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
            claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));
            claims.Add(new Claim(IdentityServerConstants.StandardScopes.Email, user.Email));

            //Get user claims from AspNetUserClaims table
            var userClaims = await _userManager.GetClaimsAsync(user);
            claims.AddRange(userClaims);

            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }
</code>```

My MVC client is configured as below

```<code>               new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "api"
                        },

                        AllowOfflineAccess = true
                    },
</code>```

In my MVC application, I have the following code in Startup.cs file

```<code>services.AddMvc();

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "mvc";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;

        options.Scope.Add("api");
        options.Scope.Add("offline_access");
    });
</code>```

When I authenticate user in identity server and get back to my secured link i got following claims but IS_token is missing from my users claims.

My secured page's cshtml

```<code><dl>

    @foreach (var claim in User.Claims)

    {

        <dt>@claim.Type</dt>

        <dd>@claim.Value</dd>

    }

    <dt>access token</dt>
    <dd>@await ViewContext.HttpContext.GetTokenAsync("access_token")</dd>

    <dt>refresh token</dt>
    <dd>@await ViewContext.HttpContext.GetTokenAsync("refresh_token")</dd>

</dl>
</code>```

This is my secured page's screenshot

My secure page's output

As you can see in image IS_token is missing. How can i get IS_token claim???

答:
In your client configuration, in AddOpenIdConnect, you should add:

options.Scope.Add("IS_token");

Otherwise, the claims of this scope are filtered out by your implementation of GetProfileDataAsync

Body:
In my identity server's Startup.cs file, I have server configured as below. I am using asp.net identity for user management.

services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

services.AddTransient<IProfileService, ProfileService>();

My IdentiyResources are as follow. Here I want to return extra claim as IS_Token which I want to use for some further business logic of my application.

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    new IdentityResource("IS_token", new []{ "IS_token" } ),
                };
        }

I'm also adding this claim in IssuedClaims inside my IProfileService as below.

public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        public ProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
        {
            _userManager = userManager;
            _claimsFactory = claimsFactory;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            var principal = await _claimsFactory.CreateAsync(user);

            var claims = principal.Claims.ToList();
            claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
            claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));
            claims.Add(new Claim(IdentityServerConstants.StandardScopes.Email, user.Email));

            //Get user claims from AspNetUserClaims table
            var userClaims = await _userManager.GetClaimsAsync(user);
            claims.AddRange(userClaims);

            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }

My MVC client is configured as below

               new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "api"
                        },

                        AllowOfflineAccess = true
                    },

In my MVC application, I have the following code in Startup.cs file

services.AddMvc();

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "mvc";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;

        options.Scope.Add("api");
        options.Scope.Add("offline_access");
    });

When I authenticate user in identity server and get back to my secured link i got following claims but IS_token is missing from my users claims.

My secured page's cshtml

    @foreach (var claim in User.Claims)

    {

@claim.Type

@claim.Value

    }

access token

@await ViewContext.HttpContext.GetTokenAsync("access_token")

refresh token

@await ViewContext.HttpContext.GetTokenAsync("refresh_token")

This is my secured page's screenshot

My secure page's output

As you can see in image IS_token is missing. How can i get IS_token claim???


问:
JavaScript / jQuery not being executed while in script tags
This is my code:

<form>
  <fieldset>
    <legend>Appearance</legend>

      Select Race:
      <select id="Race">
        <option value="human">Human</option>
        <option value="faela">Faela</option>
        <option value="domovoi">Domovoi</option>
        <option value="arcon">Arcon</option>
        <option value="tsaaran">Tsaaran</option>
      </select>

      Select Gender
      <select id="Gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
      </select>

      Select Age:
      <input type="range" min="10" max="80" id="slider" value="10" name="range">

  </fieldset>
</form>

```

My code works fine when the javascript is kept seperate as a .js file. However, when its within the HTML using the script tags, it does not work. The output of the slider values are not being outputted. I researched this and found that I should add window.onload = function() {} However, even after adding that it didnt ouput the values of the slider.

Please let me know how I can fix this.
Thanks,

答:
You should be seeing an error in your console that says the symbol $ is not recognized. This is because your document doesn't include the jQuery script. Add the following to your header:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</code>```

$(function() {
    let output = $('#output');
    let slider = $('#slider');

    output.html(slider.val());

    slider.on('change', function() {
        output.html(this.value);
    });

    $('#Race').on('change', function() {
        let min, max;

        switch (this.value) {
            case 'faela': min, max = 10, 70;
            case 'human': min, max = 10, 80;
        }

        slider.prop({ min, max });
        slider.val(min);

        output.html(min);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset>
    <legend>Appearance</legend>
    <p>
      <label>Select Race:</label>
      <select id="Race">
        <option value="human">Human</option>
        <option value="faela">Faela</option>
        <option value="domovoi">Domovoi</option>
        <option value="arcon">Arcon</option>
        <option value="tsaaran">Tsaaran</option>
      </select>
    </p>
    <p>
      <label>Select Gender</label>
      <select id="Gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
      </select>
    </p>
    <p>
      <label for="range">Select Age:</label>
      <input type="range" min="10" max="80" id="slider" value="10" name="range"> <span id="output"></span>

    </p>
  </fieldset>
</form></code>```

Body:
This is my code:

<form>
  <fieldset>
    <legend>Appearance</legend>

      Select Race:
      <select id="Race">
        <option value="human">Human</option>
        <option value="faela">Faela</option>
        <option value="domovoi">Domovoi</option>
        <option value="arcon">Arcon</option>
        <option value="tsaaran">Tsaaran</option>
      </select>

      Select Gender
      <select id="Gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
      </select>

      Select Age:
      <input type="range" min="10" max="80" id="slider" value="10" name="range">

  </fieldset>
</form>

My code works fine when the javascript is kept seperate as a .js file. However, when its within the HTML using the script tags, it does not work. The output of the slider values are not being outputted. I researched this and found that I should add window.onload = function() {} However, even after adding that it didnt ouput the values of the slider.

Please let me know how I can fix this.
Thanks,

Body:
You should be seeing an error in your console that says the symbol $ is not recognized. This is because your document doesn't include the jQuery script. Add the following to your header:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$(function() {
    let output = $('#output');
    let slider = $('#slider');

    output.html(slider.val());

    slider.on('change', function() {
        output.html(this.value);
    });

    $('#Race').on('change', function() {
        let min, max;

        switch (this.value) {
            case 'faela': min, max = 10, 70;
            case 'human': min, max = 10, 80;
        }

        slider.prop({ min, max });
        slider.val(min);

        output.html(min);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset>
    <legend>Appearance</legend>
    <p>
      <label>Select Race:</label>
      <select id="Race">
        <option value="human">Human</option>
        <option value="faela">Faela</option>
        <option value="domovoi">Domovoi</option>
        <option value="arcon">Arcon</option>
        <option value="tsaaran">Tsaaran</option>
      </select>
    </p>
    <p>
      <label>Select Gender</label>
      <select id="Gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
        <option value="other">Other</option>
      </select>
    </p>
    <p>
      <label for="range">Select Age:</label>
      <input type="range" min="10" max="80" id="slider" value="10" name="range"> <span id="output"></span>

    </p>
  </fieldset>
</form>


答:
Maybe try DOMContentLoaded instead.</p>

```<code>window.addEventListener('DOMContentLoaded', function () {
    //code
}, false);
</code>```

Title: JavaScript / jQuery not being executed while in script tags

Body:
Maybe try DOMContentLoaded instead.

window.addEventListener('DOMContentLoaded', function () {
    //code
}, false);


问:
JS server not recognized, continuing with build
Environment

Windows 10

Npm 5.5.1

react-native-cli 2.0.1

react-native 0.50.3

Genymotion Google Nexus 7 - 6.0.0 API 23

Android stuff:

Sdk Version: 26

buildToolsVersion '26.0.2'

TargetsdkVersion: 26

compile "com.android.support:appcompat-v7:26.0.2"

I have run npm start --reset-cache as well as react-native start --reset-cache but I keep getting the JS server not recognized, continuing with build. This prevents the packager bundling the assets before running on my Emulator.

I have followed solution 1 on this post:

https://github.com/facebook/react-native/issues/9136#issuecomment-306486102

as well as this one:

Unable to recognize JS server

I started this project with react-native init APP. Already having trouble building it with this error. checking serval posts on here and other sites mentioned using npm cache clean and react-native start --reset-cache and that did not seem to help I keep getting the same error. I had it running smoothly at one time but I altered an npm package and I think I broke it again. any help would be appreciated. I also updated the gradle version and synced that into the project

Heres some screenshots of what I am experiencing...

** CODE **

index.js

```<code>import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('hihi', () => App);
</code>```

App.js
    /**
     * Sample React Native App
     * https://github.com/facebook/react-native
     * @flow
     */

```<code>import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
</code>```

app.json

```<code>{
  "name": "hihi",
  "displayName": "hihi"
}
</code>```

.babelrc

```<code>{
  "presets": ["react-native"]
}
</code>```

package.json

```<code>{
    "name": "hihi",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.3",
        "watchman": "^0.1.8"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-polyfill": "^6.26.0",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react-native": "4.0.0",
        "babel-register": "^6.26.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}
</code>```

UPDATE UPDATE

I figured it out, it was a combination of the suggestions on this post and this solution as well:

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I needed to include google() in both locations as well as the solution of switching it to port 8082 and enabling that port on the emulator. THANK YOU ALL SO MUCH FOR YOUR HELP!!! =)

答:
Steps that helped me in similar case:

Running packager on port different than 8081: react-native start --port 8082 --reset-cache

Running command react-native run-android --port 8082 in second Command Prompt window.

After error screen appear clicking Ctrl + M.

Clicking Dev Settings button at the bottom.

Clicking Debug server host & port for device button.

Writing localhost:8082 and clicking OK button.

Again running command react-native run-android --port 8082

Body:
Environment

Windows 10

Npm 5.5.1

react-native-cli 2.0.1

react-native 0.50.3

Genymotion Google Nexus 7 - 6.0.0 API 23

Android stuff:

Sdk Version: 26

buildToolsVersion '26.0.2'

TargetsdkVersion: 26

compile "com.android.support:appcompat-v7:26.0.2"

I have run npm start --reset-cache as well as react-native start --reset-cache but I keep getting the JS server not recognized, continuing with build. This prevents the packager bundling the assets before running on my Emulator.

I have followed solution 1 on this post:

https://github.com/facebook/react-native/issues/9136#issuecomment-306486102

as well as this one:

Unable to recognize JS server

I started this project with react-native init APP. Already having trouble building it with this error. checking serval posts on here and other sites mentioned using npm cache clean and react-native start --reset-cache and that did not seem to help I keep getting the same error. I had it running smoothly at one time but I altered an npm package and I think I broke it again. any help would be appreciated. I also updated the gradle version and synced that into the project

Heres some screenshots of what I am experiencing...

** CODE **

index.js

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('hihi', () => App);

App.js
    /**
     * Sample React Native App
     * https://github.com/facebook/react-native
     * @flow
     */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

app.json

{
  "name": "hihi",
  "displayName": "hihi"
}

.babelrc

{
  "presets": ["react-native"]
}

package.json

{
    "name": "hihi",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.3",
        "watchman": "^0.1.8"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-polyfill": "^6.26.0",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react-native": "4.0.0",
        "babel-register": "^6.26.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}

UPDATE UPDATE

I figured it out, it was a combination of the suggestions on this post and this solution as well:

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I needed to include google() in both locations as well as the solution of switching it to port 8082 and enabling that port on the emulator. THANK YOU ALL SO MUCH FOR YOUR HELP!!! =)


问:
"Table not found" exception with hibernate
I'm getting the following exception with hibernate:

```<code>10:18:14,795 INFO  [SchemaValidator] Running schema validator

10:18:14,795 INFO  [SchemaValidator] fetching database metadata

10:18:16,958 INFO  [DatabaseMetadata] table not found: DUMMY_TABLE

10:18:16,963 ERROR [AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=bkoMdw-ear.ear/bkoMdw-ejb.jar#bkoMdw state=Create
javax.persistence.PersistenceException: [PersistenceUnit: bkoMdw] Unable to build EntityManagerFactory

(...)

Caused by: org.hibernate.HibernateException: Missing table: DUMMY_TABLE
     at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1127)
     at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
     at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:359)
     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1341)
     at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
     at

org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
</code>```

The problem is that the table exists and the datasource file is correctly configured.

What I'm missing? Any advise to troubleshoot this?

Thanks in advance!

答: I had the same problem with a view I used in my mapping. After I've disabled Hibernate's validation, it works correctly. Seems, that the validation has a problem with views.</p>

Body:
I'm getting the following exception with hibernate:

10:18:14,795 INFO  [SchemaValidator] Running schema validator

10:18:14,795 INFO  [SchemaValidator] fetching database metadata

10:18:16,958 INFO  [DatabaseMetadata] table not found: DUMMY_TABLE

10:18:16,963 ERROR [AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=bkoMdw-ear.ear/bkoMdw-ejb.jar#bkoMdw state=Create
javax.persistence.PersistenceException: [PersistenceUnit: bkoMdw] Unable to build EntityManagerFactory

(...)

Caused by: org.hibernate.HibernateException: Missing table: DUMMY_TABLE
     at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1127)
     at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
     at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:359)
     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1341)
     at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
     at

org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)

The problem is that the table exists and the datasource file is correctly configured.

What I'm missing? Any advise to troubleshoot this?

Thanks in advance!


问:
Receiving ConcurrentModificationException when attempting to iterate through HashMap
I am having issues with a project I am working on. There is a main loop that runs the program which calls the update() method every frame.

I have an object that is a World which contains a HashMap<ChunkPos, Chunk> where a ChunkPos is a data structure that has an xyz position which represents a Chunk's position in the World

I am attempting to iterate through all the Chunks in my the world in my update function, as each Chunk has it's own ArrayList of GameObject that has all of the objects inside this chunk of the world.

```<code>public void update() {
    HashMap<ChunkPos, Chunk> chunkMap = world.getChunkMap();
    Iterator<Map.Entry<ChunkPos, Chunk>> it = chunkMap.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry<ChunkPos, Chunk> item = it.next();
        ArrayList<GameObject> chunkObjects = item.getValue().getObjects();
        for(GameObject obj : chunkObjects) {
            obj.update();
        }
    }
}
</code>```

However, when I run the program, I am receiving a ConcurrentModificationException at this line:

```<code>Map.Entry<ChunkPos, Chunk> item = it.next();
</code>```

I've tried multiple different ways of iterating through the HashMap, but each time I end up with this same error. What am I doing wrong?

Here is the full StackTrace if it helps:

```<code>Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
at com.anzanama.lwjgl3d.Game.Game.update(Game.java:40)
at com.anzanama.lwjgl3d.Game.Game.loop(Game.java:31)
at com.anzanama.lwjgl3d.Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code>```

Just wanted to make a note here: I eventually ended up implementing a WorldChangeScheduler that would schedule changes to be made to the world once it has iterated through the whole world and updated it. This makes it more robust and has the added benefit that I can later go back and turn these WorldChanges into events that other people using my engine can hook into.

答:
HashMap is not thread-safe, so iterators fail fast when structural modifications happen by other threads, while iterating.

By replacing your Map implementation with ConcurrentHashMap, you will prevent such issues, but locking will apply on the update operations, which will affect their performance. You can configure concurrency level, thought, using the concurrencyLevel parameter of the ConcurrentHashMap, if a predictable number of threads is expected to update this Map concurrently.

Body:
I am having issues with a project I am working on. There is a main loop that runs the program which calls the update() method every frame.

I have an object that is a World which contains a HashMap<ChunkPos, Chunk> where a ChunkPos is a data structure that has an xyz position which represents a Chunk's position in the World

I am attempting to iterate through all the Chunks in my the world in my update function, as each Chunk has it's own ArrayList of GameObject that has all of the objects inside this chunk of the world.

public void update() {
    HashMap<ChunkPos, Chunk> chunkMap = world.getChunkMap();
    Iterator<Map.Entry<ChunkPos, Chunk>> it = chunkMap.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry<ChunkPos, Chunk> item = it.next();
        ArrayList<GameObject> chunkObjects = item.getValue().getObjects();
        for(GameObject obj : chunkObjects) {
            obj.update();
        }
    }
}

However, when I run the program, I am receiving a ConcurrentModificationException at this line:

Map.Entry<ChunkPos, Chunk> item = it.next();

I've tried multiple different ways of iterating through the HashMap, but each time I end up with this same error. What am I doing wrong?

Here is the full StackTrace if it helps:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
at com.anzanama.lwjgl3d.Game.Game.update(Game.java:40)
at com.anzanama.lwjgl3d.Game.Game.loop(Game.java:31)
at com.anzanama.lwjgl3d.Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Just wanted to make a note here: I eventually ended up implementing a WorldChangeScheduler that would schedule changes to be made to the world once it has iterated through the whole world and updated it. This makes it more robust and has the added benefit that I can later go back and turn these WorldChanges into events that other people using my engine can hook into.


问:
SQL how can I have sql return one row instead of multiple per distinct ID?
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

```<code>ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50
</code>```

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

```<code>SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID
</code>```

that worked fine.  I would get

```<code>01 2016-08-21
02 2016-10-01
</code>```

I soon realized that I also need PERCENT column.

```<code>SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT
</code>```

but now, I'm getting the multiple rows for ID 01 which is wrong...

```<code>01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50
</code>```

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

```<code>01  2016-08-21  1111  52
02  2016-10-01  1111  50
</code>```

答:
If this is SQL Server, you can use TOP 1 WITH TIES along with an ORDER BY:

```<code>SELECT TOP 1 WITH TIES ID, DATE, PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND  CODE = 1111
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE ASC)
</code>```

Body:
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID

that worked fine.  I would get

01 2016-08-21
02 2016-10-01

I soon realized that I also need PERCENT column.

SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT

but now, I'm getting the multiple rows for ID 01 which is wrong...

01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

01  2016-08-21  1111  52
02  2016-10-01  1111  50

Body:
If this is SQL Server, you can use TOP 1 WITH TIES along with an ORDER BY:

SELECT TOP 1 WITH TIES ID, DATE, PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND  CODE = 1111
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE ASC)


答:
Do not group by PERCENT, just group by ID. Add code in the select statement.</p>

```<code>select id, min(date), code, percent
from tablename
where date between '2016-01-01' AND  '2017-11-01'
and   code = 1111
group by id;
</code>```

Title: SQL how can I have sql return one row instead of multiple per distinct ID?

Body:
Do not group by PERCENT, just group by ID. Add code in the select statement.

select id, min(date), code, percent
from tablename
where date between '2016-01-01' AND  '2017-11-01'
and   code = 1111
group by id;


问:
Angular - How to create a persistent/permanent "Add to Home screen" button in my web app, just like Google Contribute
How to create a persistent/permanent "Add to Home screen" button in my web app, just like Google Contribute? (see image below)

Background: It's an Angular v5 app with PWA service worker and manifest.json all setup. On landing in the app, a banner will pop-up inviting users to Add to Home Screen. It's all working good.

So how to have a button in my web app like Google Contribute (see image below)?

答:
You can achieve this by ng-content. Let's say we have CardComponent,
In card.component.html we can have this:

```<code><div class="card">
  <ng-content></ng-content>
</div>
</code>```

In our ContriobuteComponent, we have:

```<code><card>
  <div class="card-block">
    <a href="#" class="btn btn-primary">Add to Home Screen</a>
   <h2>{{username | uppercase }}</h2>
  </div>
</card>
</code>```

The content in div would be injected to ng-content. Similarly,in ReviewsComponent you can inject different contents

Body:
You can achieve this by ng-content. Let's say we have CardComponent,
In card.component.html we can have this:

<div class="card">
  <ng-content></ng-content>
</div>

In our ContriobuteComponent, we have:

<card>
  <div class="card-block">
    <a href="#" class="btn btn-primary">Add to Home Screen</a>
   <h2>{{username | uppercase }}</h2>
  </div>
</card>

The content in div would be injected to ng-content. Similarly,in ReviewsComponent you can inject different contents


问:
How to write both h1 and h2 in the same line?
I have a page and I want simply to make a header. This header is an
 text aligned to the left, and an
 aligned to the right, in the same line, and after them, an
. My code so far look as follows (if you test it, you'll see that it's wrong):

```<code><h1 align="left">Title</h1>
<h2 align="right">Context</h2>
<hr/>
</code>```

Thanks guys!

答:
Keyword float:

```<code><h1 style="text-align:left;float:left;">Title</h1>
<h2 style="text-align:right;float:right;">Context</h2>
<hr style="clear:both;"/>
</code>```

Body:
I have a page and I want simply to make a header. This header is an
 text aligned to the left, and an
 aligned to the right, in the same line, and after them, an
. My code so far look as follows (if you test it, you'll see that it's wrong):

Title

Context

Thanks guys!

Body:
Keyword float:

<h1 style="text-align:left;float:left;">Title</h1>
<h2 style="text-align:right;float:right;">Context</h2>
<hr style="clear:both;"/>


问:
Is it impossible to manually force a $_SESSION['iamlogged'] value?
I would like to be sure that a $_SESSION cannot be fooled in a login scheme involving it. I over-simplified it here to keep only the core of the question.

When using

```<code><?php
$password = "...";

session_set_cookie_params(3600, dirname($_SERVER['SCRIPT_NAME']));
session_start();

if (isset($_POST['pass']) && $_POST['pass'] === $password) {
    $_SESSION['iamlogged'] = 1;
}

if (!isset($_SESSION['iamlogged']) || !($_SESSION['iamlogged'] == 1)) {
    echo '<html><body><form action="." method="post"><input type="password" name="pass" '
         . 'value=""><input type="submit" value="Submit"></form></body></html>';
    exit;
}

echo "You logged in in the last 30 minutes.";
// Now we can do some work
</code>```

is it sure that the last line cannot be displayed for anyone not having the password? Or is there a currently known technique in PHP, to manually force this $_SESSION['iamlogged'] value?

Note: Of course, I do use password hasing+salting, etc., but I removed all of this to focus only on the $_SESSION safetyness.

Note2: I assume register_globals is off because PHP is newer than 5.4.

Note3: Here is a live version.

答:
The session may possibly give you a false positive if there is a relic $_SESSION['iamlogged'] floating around from previously.

As a safety measure, you should do:

```<code><?php
$password = "...";

//unset false positive, if it exists
if (array_key_exists('iamlogged', $_SESSION)) {
    unset($_SESSION['iamlogged'];
}

//carry on normally
if (isset($_POST['pass']) && $_POST['pass'] === $password) {
    $_SESSION['iamlogged'] = 1;
}
...
</code>```

Or you could do it this way for simplicity:

```<code>session_start();
session_destroy();
session_start();
</code>```

However the latter here would also lose everything else in $_SESSION, so if there's other relevant stuff in there you want to retain, don't do it the second way.

Body:
I would like to be sure that a $_SESSION cannot be fooled in a login scheme involving it. I over-simplified it here to keep only the core of the question.

When using

<?php
$password = "...";

session_set_cookie_params(3600, dirname($_SERVER['SCRIPT_NAME']));
session_start();

if (isset($_POST['pass']) && $_POST['pass'] === $password) {
    $_SESSION['iamlogged'] = 1;
}

if (!isset($_SESSION['iamlogged']) || !($_SESSION['iamlogged'] == 1)) {
    echo '<form action="." method="post"><input type="password" name="pass" '
         . 'value=""><input type="submit" value="Submit"></form>';
    exit;
}

echo "You logged in in the last 30 minutes.";
// Now we can do some work

is it sure that the last line cannot be displayed for anyone not having the password? Or is there a currently known technique in PHP, to manually force this $_SESSION['iamlogged'] value?

Note: Of course, I do use password hasing+salting, etc., but I removed all of this to focus only on the $_SESSION safetyness.

Note2: I assume register_globals is off because PHP is newer than 5.4.

Note3: Here is a live version.

Body:
The session may possibly give you a false positive if there is a relic $_SESSION['iamlogged'] floating around from previously.

As a safety measure, you should do:

<?php
$password = "...";

//unset false positive, if it exists
if (array_key_exists('iamlogged', $_SESSION)) {
    unset($_SESSION['iamlogged'];
}

//carry on normally
if (isset($_POST['pass']) && $_POST['pass'] === $password) {
    $_SESSION['iamlogged'] = 1;
}
...

Or you could do it this way for simplicity:

session_start();
session_destroy();
session_start();

However the latter here would also lose everything else in $_SESSION, so if there's other relevant stuff in there you want to retain, don't do it the second way.


问:
Lambda Python boto3 store file in S3 bucket
ok, I've seen a few examples of this, and here is my code in AWS Lambda Python 3.6:

```<code># I just wrote out the file before this...
import boto3
tmp = open('/tmp/' + name_str,"rb")
s3_client = boto3.resource('s3')
bucket = s3_client.Bucket(S3BUCKETNAME)
bucket.put_object(Key=name_str, Body=tmp, ContentType='text/csv', ContentEncoding='utf-8')
</code>```

The error I get is :

's3.ServiceResource' object has no attribute 'put_object':
  AttributeError

Well, then I try:

```<code>s3_client.upload_file('/tmp/' + name_str, S3BUCKETNAME, name_str)
</code>```

's3.ServiceResource' object has no attribute 'upload_file':
  AttributeError

So... I must be missing something basic... Is there some other import? Why can't the system find these functions?

答:
This was a misunderstanding of what type to use. It should have been:

s3_client = boto3.client('s3')

But note that the code I actually use now is more like:

```<code>s3_client = boto3.client('s3')
with open('/tmp/' + name_str) as file:
    object = file.read()
    s3_client.put_object(Body=object, Bucket=S3BUCKET, Key=name_str, ContentType='whatever/something', ContentEncoding='whatever-itis', StorageClass='PICK_ONE', ACL='you_choose')
</code>```

Body:
ok, I've seen a few examples of this, and here is my code in AWS Lambda Python 3.6:

# I just wrote out the file before this...
import boto3
tmp = open('/tmp/' + name_str,"rb")
s3_client = boto3.resource('s3')
bucket = s3_client.Bucket(S3BUCKETNAME)
bucket.put_object(Key=name_str, Body=tmp, ContentType='text/csv', ContentEncoding='utf-8')

The error I get is :

's3.ServiceResource' object has no attribute 'put_object':
  AttributeError

Well, then I try:

s3_client.upload_file('/tmp/' + name_str, S3BUCKETNAME, name_str)

's3.ServiceResource' object has no attribute 'upload_file':
  AttributeError

So... I must be missing something basic... Is there some other import? Why can't the system find these functions?

Body:
This was a misunderstanding of what type to use. It should have been:

s3_client = boto3.client('s3')

But note that the code I actually use now is more like:

s3_client = boto3.client('s3')
with open('/tmp/' + name_str) as file:
    object = file.read()
    s3_client.put_object(Body=object, Bucket=S3BUCKET, Key=name_str, ContentType='whatever/something', ContentEncoding='whatever-itis', StorageClass='PICK_ONE', ACL='you_choose')


问:
AngularJS V1.2 - Error: $q is not a function
```<code>(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

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

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

答:
there's an error in the injection as suggested in the comments

```<code>Testing.$inject('$q', '$location', 'authentication')
</code>```

should be

```<code>Testing.$inject = ['$q', '$location', 'authentication']
</code>```

link to doc

Body:
(function () {
angular.module('Testing')
    .controller('Testing', Testing);
    Testing.$inject('$q', '$location', 'authentication');
    function  Testing($q, $location, authentication) {
    var vm = this;

    function asyncGreet(name) {
    return $q(function (resolve, reject) {
        setTimeout(function(){
            if(username){
                resolve('Hello, ' + username);
            }
            else {
                reject('Greeting ' +  name + 'is not allowed');
            }
        }, 3000)
    });
}

var promise = asyncGreet("oo");
promise.then(function (greeting) {
    console.log('Success: ' + greeting);
}, function (reason) {
    console.log('Failed: ' + reason);
});

} ());

I am using angular version 1.2.9, and i am trying to make use of $q, and i keep getting an error that says $q is not a function, .

Can someone please point me to what i am doing wrong? Thank you.

Body:
there's an error in the injection as suggested in the comments

Testing.$inject('$q', '$location', 'authentication')

should be

Testing.$inject = ['$q', '$location', 'authentication']

link to doc


问:
IBM Content Collector error receiving response after external WS call
In my current project using IBM Content Collector 4.0.1 SP5 with IBM Filenet P8 Content Engine 5.2.1 I need to collect files from file system and add them to a certain P8's object store.

This issue is related and comes after this one.

The WS response must conform to a custom metadata source called Esito which contains two metadata properties called resultCode and message.

The call seems correct but when getting the response I can read this message in the log and the file is not uploaded into P8 Content Manager:

2017-11-10T08:54:05.708Z FINEST [52] [ctms-native]
  2017-11-10T08:54:05Z Trace2 0x15a4 Feeding JavaTask with 1 TaskInputs
  ufibridge.dll:0x114ac [com.ibm.afu.ufibridge.logging.LoggingAdapter
  log] [CTMS-task-15a4 45] 2017-11-10T08:54:05.708Z FINEST [53] Prepared
  content to send to
  webservice:{"e:\report\amm_000001_00001\2017\11\201711_amm_000001_00001_qxn_report_00.pdf":{"esito":"KO","fileName":"201711_AMM_000001_00001_QXN_REPORT_00(1)(2)(3).pdf"},"e:\report\amm_000001_00001\2017\11\201711_amm_000001_00001_qxn_report_00.xml":{"esito":"KO","fileName":"201711_AMM_000001_00001_QXN_REPORT_00(1)(2)(3).xml"}}
  [com.ibm.afu.connector.webservice.task.InvokeServiceTask
  getInputHttpEntity] [CTMS-task-15a4 45] 2017-11-10T08:54:05.708Z
  FINEST [54] Configuration:

property name="message" type="STRING" displayName="message"

  property name="resultCode" type="STRING" displayName="resultCode"

  http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione

fileName esito
  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-15a4 45] 2017-11-10T08:54:05.708Z FINEST [55] Invoking
  webservice
  URI:http://192.168.8.29:8080/sirfAcq/filenet/notificaArchiviazione
  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-15a4 45] 2017-11-10T08:54:05.739Z FINEST [56] Invocation
  took time (ms): 31
  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-15a4 45] 2017-11-10T08:54:05.739Z SEVERE [57]
  java.lang.String incompatible with com.ibm.json.java.JSONObject
  [com.ibm.afu.connector.webservice.task.InvokeServiceTask execute]
  [CTMS-task-15a4 45]Exception [java.lang.ClassCastException]:
  java.lang.String incompatible with com.ibm.json.java.JSONObject
  com.ibm.afu.connector.webservice.task.InvokeServiceTask.processResponse(InvokeServiceTask.java:140)
  com.ibm.afu.connector.webservice.task.InvokeServiceTask.execute(InvokeServiceTask.java:112)

Could someone please explain me the correct format of the WS response JSON?

Could it be possible to use the One-Way mode instead of the Request-Response mode?

答:
This issue seems to happen because of the incompatibility between the produce and the response body definition, based on the code snippet I had for your first post, your problem should be here:

```<code>   produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })

   @ResponseBody
   String notificaArchiviazione(@RequestParam("fileName") String fileName, @RequestParam("esito") String esito)
</code>```

The first parameter in produce is sat as JSONMediaType.APPLICATION_JSON_VALUE while in the response body you expect a string @RequestParam("fileName") String fileName

Body:
This issue seems to happen because of the incompatibility between the produce and the response body definition, based on the code snippet I had for your first post, your problem should be here:

   produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })

   @ResponseBody
   String notificaArchiviazione(@RequestParam("fileName") String fileName, @RequestParam("esito") String esito)

The first parameter in produce is sat as JSONMediaType.APPLICATION_JSON_VALUE while in the response body you expect a string @RequestParam("fileName") String fileName


问:
Selecting Specific Array Element
I am working with Couchbase v4.5 and the .NET SDK version 2.3.8. I am in the midst of migrating a view to a N1QL query. The Javascirpt available to the view provided me the flexibility of sorting array members of the document, and subsequently selecting just a single element from the array. So whereas in my view I had:

```<code>'Username': doc.Document.LogActions.sort(function(a,b){ return (a.Time > b.Time) })[doc.Document.LogActions.length - 1].Username
</code>```

...I'm now struggling to accomplish the same via the .NET SDK in a N1QL query. The caveat is that I'm attempting to do this solely in LINQ. I realize that I can use the raw string queries, which offer full N1QL support, but the team lead wants this done via LINQ...unless there's absolutely no way to do it via LINQ.

I've tried the following:

Sorting - Not allowed to sort by a property on an object in an array

```<code>Username = doc.Document.LogActions
                       .OrderByDescending(logAction => logAction.Time)
                       .FirstOrDefault()
                       .Username,
</code>```

Take Just Last - Last not supported

```<code>Username = transaction.Document.LogActions
                               .LastOrDefault()
                               .Username,
</code>```

No Sorting - Still returns an array

```<code>Username = transaction.Document
                      .LogActions[transaction.Document.LogActions.Count - 1]
                      .Username
</code>```

The only other thing I can think to do is just return the array back to .NET and do the filtering there. However, we have no baseline for how many items will be in the array on average. We'd rather avoid bringing back data we don't need.

Am I relegated to using a raw string query? Ideally I'm trying to find the most recent "log action" from the array, based on the Time property.

答:
I played around some more with this, and while it seems like something like this should work:

```<code>Username = transaction.Document.LogActions
                               .OrderByDescending(logAction => logAction.Time)
                               .Select(g => g.Username)
                               .ToArray()[0],
</code>```

...alas, it does not. I receive an error of "N1Ql Array Subqueries Support One Ordering By The Array Elements Only". So I tried using a GroupBy--for giggles--and lo and behold I do get results back:

```<code>Username = transaction.Document.LogActions
                               .OrderByDescending(logAction => logAction.Time)
                               .GroupBy(logAction => new { logAction.Time, logAction.Username })
                               .Select(g => g.Key.Username)
                               .ToArray()[0],
</code>```

This leaves me with confirming that I get the correct result back--since CB's ordering seems a bit wonky--but it's at least semi-working.

Title: Selecting Specific Array Element

Body:
I am working with Couchbase v4.5 and the .NET SDK version 2.3.8. I am in the midst of migrating a view to a N1QL query. The Javascirpt available to the view provided me the flexibility of sorting array members of the document, and subsequently selecting just a single element from the array. So whereas in my view I had:

'Username': doc.Document.LogActions.sort(function(a,b){ return (a.Time > b.Time) })[doc.Document.LogActions.length - 1].Username

...I'm now struggling to accomplish the same via the .NET SDK in a N1QL query. The caveat is that I'm attempting to do this solely in LINQ. I realize that I can use the raw string queries, which offer full N1QL support, but the team lead wants this done via LINQ...unless there's absolutely no way to do it via LINQ.

I've tried the following:

Sorting - Not allowed to sort by a property on an object in an array

Username = doc.Document.LogActions
                       .OrderByDescending(logAction => logAction.Time)
                       .FirstOrDefault()
                       .Username,

Take Just Last - Last not supported

Username = transaction.Document.LogActions
                               .LastOrDefault()
                               .Username,

No Sorting - Still returns an array

Username = transaction.Document
                      .LogActions[transaction.Document.LogActions.Count - 1]
                      .Username

The only other thing I can think to do is just return the array back to .NET and do the filtering there. However, we have no baseline for how many items will be in the array on average. We'd rather avoid bringing back data we don't need.

Am I relegated to using a raw string query? Ideally I'm trying to find the most recent "log action" from the array, based on the Time property.

Body:
I played around some more with this, and while it seems like something like this should work:

Username = transaction.Document.LogActions
                               .OrderByDescending(logAction => logAction.Time)
                               .Select(g => g.Username)
                               .ToArray()[0],

...alas, it does not. I receive an error of "N1Ql Array Subqueries Support One Ordering By The Array Elements Only". So I tried using a GroupBy--for giggles--and lo and behold I do get results back:

Username = transaction.Document.LogActions
                               .OrderByDescending(logAction => logAction.Time)
                               .GroupBy(logAction => new { logAction.Time, logAction.Username })
                               .Select(g => g.Key.Username)
                               .ToArray()[0],

This leaves me with confirming that I get the correct result back--since CB's ordering seems a bit wonky--but it's at least semi-working.


问:
How to check if value is correct for key in HashMap in Java
I'm writing a simple GUI program where I have to input login and password for user and then check if he is in database (my Hashmap). That's where i have problem. I checked if login is correct by containsKey and checked for password by containsValue. The problem is, that if in example I have 2 users:

```<code>login: user1 password: example
login: user2 password: programing
</code>```

If I put login as user1 in my JTextField and password "programing", the program says, that it's correct.

That's where I have a problem. How to check the password for exact login, which is key?

Would be very thankful for any clues or solutions :)

答:
You can use a check like this:

```<code> if(userEnteredPassword.equals(hashMap.get(userEnteredUsername))){
     // Correct credentials.
     .....
 }
</code>```

It's important to use userEnteredPassword.equals.... instead of hashMap.get(userEnteredUsername).equals... because you'll get a null pointer exception if there is no map entry for userEnteredUsername

Body:
I'm writing a simple GUI program where I have to input login and password for user and then check if he is in database (my Hashmap). That's where i have problem. I checked if login is correct by containsKey and checked for password by containsValue. The problem is, that if in example I have 2 users:

login: user1 password: example
login: user2 password: programing

If I put login as user1 in my JTextField and password "programing", the program says, that it's correct.

That's where I have a problem. How to check the password for exact login, which is key?

Would be very thankful for any clues or solutions :)

Body:
You can use a check like this:

 if(userEnteredPassword.equals(hashMap.get(userEnteredUsername))){
     // Correct credentials.
     .....
 }

It's important to use userEnteredPassword.equals.... instead of hashMap.get(userEnteredUsername).equals... because you'll get a null pointer exception if there is no map entry for userEnteredUsername


问:
Concatenate ByteArrayOutputStream
```<code>public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

```<code>public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

答:
You could write dataObject and recordid in the current (wrong) order then rotate them into place:

```<code>public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        int pos = objectStream.size();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);
        dout.close();
        objectStream.close();
        byte[] array = return objectStream.toByteArray();
        rotate(array, pos);
        return array;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

private static void rotate(byte[] array, int pos) {
    reverse(array, 0, pos);
    reverse(array, pos, array.length);
    reverse(array, 0, array.length);
}

private static void reverse(byte[] array, int start, int end) {
    while (start < --end) {
        byte t = array[start];
        array[start] = array[end];
        array[end] = t;
        ++ start;
    }
}
</code>```

Title: Concatenate ByteArrayOutputStream

Body:
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Body:
You could write dataObject and recordid in the current (wrong) order then rotate them into place:

public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        int pos = objectStream.size();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);
        dout.close();
        objectStream.close();
        byte[] array = return objectStream.toByteArray();
        rotate(array, pos);
        return array;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

private static void rotate(byte[] array, int pos) {
    reverse(array, 0, pos);
    reverse(array, pos, array.length);
    reverse(array, 0, array.length);
}

private static void reverse(byte[] array, int start, int end) {
    while (start < --end) {
        byte t = array[start];
        array[start] = array[end];
        array[end] = t;
        ++ start;
    }
}