问:
Nuget package installation failure
When trying to install a package from our newly created private Nuget Feed i get the following error.

Could not install package 'GC.Timecode 1.0.0.3'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.1', but the package does not contain any assembly references or content files that are compatible with that framework.

The Nuget package also targets 4.5.1. (Screenshot take from Nuget Package Explorer)

The Nuget Package is created by Octopack via On premises TFS, and then published to a private Proget Server

Nuspec file looks like this

```<code><?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>GC.Timecode</id>
<version>1.0.0.3</version>
<authors>user</authors>
<owners>user</owners>
<licenseUrl>http://example.com</licenseUrl>
<projectUrl>http://example.com</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>The GC.Timecode deployment package, built on 25/01/2016</description>
<releaseNotes />
</metadata>
</package>
</code>```

Contents of Package

What's going on here?

答:
This happened to me and I didn't find my solution posted to any of these sites, so hopefully this helps someone else.

The message I was getting was:

Could not install package 'Package Name'. You are trying to install
  this package into a project that targets
  '.NETFramework,Version=v4.6.1', but the package does not contain any
  assembly references or content files that are compatible with that
  framework. For more information, contact the package author.

I had a Nuget package that was built for all 4.x versions so it shouldn't matter that it didn't specify version 4.6.1 specifically.  I tried changing the class library build to 4.0, 4.5, 4.5.2, 4.6, 4.6.1, and 4.6.2 but nothing fixed this problem.  I also added multiple versions of the DLL to the package in individual /lib/Net4(5,51,52,6,61,62) folders and the error was still there.

Eventually, I found out the reason for my problem was the initial private Nuget package I created was a "bad" package and that bad package was cached to my local machine.

I fixed the package problem and pushed the new package to our Nuget server (leaving the version name the same), but Nuget inside Visual Studio wasn't pulling down the new package but instead referenced the bad package cached on my local machine at.  Package Manager showed the package was updated and displayed the information correctly from our Nuget server but it was never fetching the new package.  It was always retrieving the cached package at:

C:\Users\your_user_account\.Nuget\packages\

Simply deleting the package in question under your local user account forced Package Manager to pull down the new package from the server.

Title: Nuget package installation failure

Body:
When trying to install a package from our newly created private Nuget Feed i get the following error.

Could not install package 'GC.Timecode 1.0.0.3'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.1', but the package does not contain any assembly references or content files that are compatible with that framework.

The Nuget package also targets 4.5.1. (Screenshot take from Nuget Package Explorer)

The Nuget Package is created by Octopack via On premises TFS, and then published to a private Proget Server

Nuspec file looks like this

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>GC.Timecode</id>
<version>1.0.0.3</version>
<authors>user</authors>
<owners>user</owners>
<licenseUrl>http://example.com</licenseUrl>
<projectUrl>http://example.com</projectUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>The GC.Timecode deployment package, built on 25/01/2016</description>
<releaseNotes />
</metadata>
</package>

Contents of Package

What's going on here?


来源: stackexchange

问:
Inserting SUM of one column from one table to another column of another table in JAVA
I have F_table and S_table in my database.I want to insert the sum of all of the values of the Quantity_column of my F_table into Total_column of the S_table. For doing that what I have to write in JAVA?

Suppose, I have two table one is Product_table and another is Stock_table.In the Product_table there are Columns like ID,Name,Quantity. And in the Stock_table there columns like ID,TotalProduct. Now I want the sum of all of the raw of Quantity Column of Product_table and insert it into the TotalProduct Column of Stock_table. When each time I add any product and its quantity then the TotalProduct will increase automatically. For getting that what I have to do in JAVA?

Sorry if it is a newbie type question. I am actually a beginner. It will be great if anyone help me.

答:
If I'm understanding correctly you want to get the total quantity for each ID from the product table, and insert those into the stock table, yes?

The below will get you the sum of the quantity, grouped by the id:

```<code>select id, sum(quantity) from product_table group by id;
</code>```

So if you have :

```<code>1, test1, 5
1, test2, 10
2, test3, 20
2, test4, 1
3, test5, 5
</code>```

you would get something like:

```<code>1, 15
2, 21
3, 5
</code>```

Then just insert these into the correct table.

To combine the two you should be able to do something like:

```<code>insert into stock_table
select id, sum(quantity) from product_table group by id;
</code>```

Keep in mind this is entirely an SQL problem that you're asking about. But to make it jdbc/java related, the jdbc for something like this would be:

```<code>String sql = "insert into stock_table select id, sum(quantity) from product_table group by id";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.executeUpdate();

stmt.close();
</code>```

You would probably want to check the number of rows updated/inserted by stmt.executeUpdate().

ContentLicense: CC BY-SA 3.0

Body:
If I'm understanding correctly you want to get the total quantity for each ID from the product table, and insert those into the stock table, yes?

The below will get you the sum of the quantity, grouped by the id:

select id, sum(quantity) from product_table group by id;

So if you have :

1, test1, 5
1, test2, 10
2, test3, 20
2, test4, 1
3, test5, 5

you would get something like:

1, 15
2, 21
3, 5

Then just insert these into the correct table.

To combine the two you should be able to do something like:

insert into stock_table
select id, sum(quantity) from product_table group by id;

Keep in mind this is entirely an SQL problem that you're asking about. But to make it jdbc/java related, the jdbc for something like this would be:

String sql = "insert into stock_table select id, sum(quantity) from product_table group by id";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.executeUpdate();

stmt.close();

You would probably want to check the number of rows updated/inserted by stmt.executeUpdate().


问:
Laravel: How to have comments on multiple content types?
I have a 'comments' table that has a foreign key of 'content_id' and a qualifier column (if you will) of 'content_type'. The possible values in that column would be e.g. articles, clubs, challenges. Since Articles, Clubs, and Challenges each are their own type of content (different tables, models, controllers etc) and each have an auto-incrementing primary key field (id: 1,2,..,n) when associating through a hasMany I would like to use the content_id and content_type columns on the comments table to differentiate between comments with foreign content_id of 1 that belong to Article 1 and not Club 1 or Challenge 1.

I could have tables/types of ArticleComment, ClubComment, and ChallengeComment but that smells to me. In SQL I would just say (basically) select * from commments where content_id = 1 and content_type = 'article'.

```<code>mysql> select * from comments where content_id = 1 and content_type = 'article';
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
| id | user_id | content_id | content_type | body                                                                                | created_at          | updated_at          |
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
|  1 |      51 |          1 | article      | Laborum veniam placeat velit aut doloribus rem vitae quisquam. Qui occaecati dolores cupiditate et. Ut nam cupiditate vitae impedit blanditiis recusandae. Non temporibus minima quae rem occaecati temporibus molestiae. Eligendi ipsa laborum velit natus. | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  2 |      52 |          1 | article      | Quos et molestiae sequi aut. Dolorum eius dolorem est et sint voluptas ut. Ut ab et hic sed tenetur eaque. Neque aut qui labore animi architecto sit. Sunt excepturi laborum pariatur at dolorem est.                                                        | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  3 |      53 |          1 | article      | Quae ducimus minus et architecto non. Quas delectus accusantium sunt ipsam quisquam voluptas. Autem quo assumenda aut qui.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  4 |      54 |          1 | article      | Ut officiis totam doloremque et amet est. Modi et quia dolores fugit modi temporibus. Dicta dolor nemo enim. Unde quos ab voluptatum nihil ducimus reiciendis accusantium. Qui vel rem sunt sit quasi autem.                                                 | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  5 |      55 |          1 | article      | Velit saepe vero officia reiciendis sed nisi aut. Aliquam id dolorem eum qui molestiae dolores quam. Error adipisci possimus voluptatem aut. Sed odio quae et esse veniam quisquam est.                                                                      | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  6 |      56 |          1 | article      | Totam similique illum autem ut odio nihil. Placeat sunt labore suscipit sapiente et totam et. Modi autem aut ut et dolorem laudantium et. Hic laboriosam vel odio accusantium dolor quia soluta.                                                             | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  7 |      57 |          1 | article      | Voluptas facere dolores porro quas est. Dolorem sunt quis adipisci ut. Et et vero minus similique beatae distinctio ducimus. Voluptas iure laudantium incidunt aut.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  8 |      58 |          1 | article      | Aut libero temporibus necessitatibus et vel sit officia sit. Esse aliquid placeat amet illum dolor aut fugiat.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  9 |      59 |          1 | article      | Repellat ducimus ipsa adipisci aliquid. Mollitia laborum ea omnis aut error error. Hic dolore qui vero nobis repellendus exercitationem amet dolores. Corrupti facere labore incidunt reprehenderit quo officia.                                             | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
| 10 |      60 |          1 | article      | Deserunt quae provident veritatis rerum unde. Voluptas dolores quia velit repellat ad ipsa saepe. Officiis corporis magni id ullam deleniti. Porro aut non veniam dolore quas suscipit.                                                                      | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
10 rows in set (0.00 sec)
</code>```

My comments relationship on my models looks like this:

```<code>    return $this->hasMany(Comment::class, 'content_id');
</code>```

and it, rightly so, grabs all comments with content_id matching the article as well as everything other piece of content with that ID.

I would like to add in some qualifier so I can say "and content_type = 'mytype'". I've done a bit of googling and haven't found a straight-forward way to do what I assume would be a simple differentiation.

I don't like the code smelly (IMO) version of multiple comment types and I could do the Drupal-type setup where I have a node/content table that store all this type of content then references another table but I think I'd be in a similar scenario with also adding in some complication to the storing of these types.

Any clues or tips?

答: mkaatman's comment "Look into eloquent polymorphic relationships" is the appropriate solution to my problem. Thanks so much. Simple and succinct.</p>

Body:
I have a 'comments' table that has a foreign key of 'content_id' and a qualifier column (if you will) of 'content_type'. The possible values in that column would be e.g. articles, clubs, challenges. Since Articles, Clubs, and Challenges each are their own type of content (different tables, models, controllers etc) and each have an auto-incrementing primary key field (id: 1,2,..,n) when associating through a hasMany I would like to use the content_id and content_type columns on the comments table to differentiate between comments with foreign content_id of 1 that belong to Article 1 and not Club 1 or Challenge 1.

I could have tables/types of ArticleComment, ClubComment, and ChallengeComment but that smells to me. In SQL I would just say (basically) select * from commments where content_id = 1 and content_type = 'article'.

mysql> select * from comments where content_id = 1 and content_type = 'article';
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
| id | user_id | content_id | content_type | body                                                                                | created_at          | updated_at          |
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
|  1 |      51 |          1 | article      | Laborum veniam placeat velit aut doloribus rem vitae quisquam. Qui occaecati dolores cupiditate et. Ut nam cupiditate vitae impedit blanditiis recusandae. Non temporibus minima quae rem occaecati temporibus molestiae. Eligendi ipsa laborum velit natus. | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  2 |      52 |          1 | article      | Quos et molestiae sequi aut. Dolorum eius dolorem est et sint voluptas ut. Ut ab et hic sed tenetur eaque. Neque aut qui labore animi architecto sit. Sunt excepturi laborum pariatur at dolorem est.                                                        | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  3 |      53 |          1 | article      | Quae ducimus minus et architecto non. Quas delectus accusantium sunt ipsam quisquam voluptas. Autem quo assumenda aut qui.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  4 |      54 |          1 | article      | Ut officiis totam doloremque et amet est. Modi et quia dolores fugit modi temporibus. Dicta dolor nemo enim. Unde quos ab voluptatum nihil ducimus reiciendis accusantium. Qui vel rem sunt sit quasi autem.                                                 | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  5 |      55 |          1 | article      | Velit saepe vero officia reiciendis sed nisi aut. Aliquam id dolorem eum qui molestiae dolores quam. Error adipisci possimus voluptatem aut. Sed odio quae et esse veniam quisquam est.                                                                      | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  6 |      56 |          1 | article      | Totam similique illum autem ut odio nihil. Placeat sunt labore suscipit sapiente et totam et. Modi autem aut ut et dolorem laudantium et. Hic laboriosam vel odio accusantium dolor quia soluta.                                                             | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  7 |      57 |          1 | article      | Voluptas facere dolores porro quas est. Dolorem sunt quis adipisci ut. Et et vero minus similique beatae distinctio ducimus. Voluptas iure laudantium incidunt aut.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  8 |      58 |          1 | article      | Aut libero temporibus necessitatibus et vel sit officia sit. Esse aliquid placeat amet illum dolor aut fugiat.                                                                                | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
|  9 |      59 |          1 | article      | Repellat ducimus ipsa adipisci aliquid. Mollitia laborum ea omnis aut error error. Hic dolore qui vero nobis repellendus exercitationem amet dolores. Corrupti facere labore incidunt reprehenderit quo officia.                                             | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
| 10 |      60 |          1 | article      | Deserunt quae provident veritatis rerum unde. Voluptas dolores quia velit repellat ad ipsa saepe. Officiis corporis magni id ullam deleniti. Porro aut non veniam dolore quas suscipit.                                                                      | 2017-03-29 15:09:13 | 2017-03-29 15:09:13 |
+----+---------+------------+--------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+---------------------+
10 rows in set (0.00 sec)

My comments relationship on my models looks like this:

    return $this->hasMany(Comment::class, 'content_id');

and it, rightly so, grabs all comments with content_id matching the article as well as everything other piece of content with that ID.

I would like to add in some qualifier so I can say "and content_type = 'mytype'". I've done a bit of googling and haven't found a straight-forward way to do what I assume would be a simple differentiation.

I don't like the code smelly (IMO) version of multiple comment types and I could do the Drupal-type setup where I have a node/content table that store all this type of content then references another table but I think I'd be in a similar scenario with also adding in some complication to the storing of these types.

Any clues or tips?


问:
get variable located inside callback function
```<code>var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}
</code>```

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

答:
If your goal is simply to have your body parsed and have the parsed JSON available readily, you should consider using a middleware such as body-parser. It is a standard pattern... Consider this code for example: (from https://github.com/expressjs/body-parser)</p>

```<code>var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})
</code>```

Body:
var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}
exports.parse = function(){
   request(options, callback);
}

Hi, how can i get info variable located inside callback function.
Sorry, i'm beginner in js and didn't find answer inside my brain / peace

Body:
If your goal is simply to have your body parsed and have the parsed JSON available readily, you should consider using a middleware such as body-parser. It is a standard pattern... Consider this code for example: (from https://github.com/expressjs/body-parser)

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})


问:
Shuffle an array with python, randomize array item order with python
What's the easiest way to shuffle an array with python?</p>

答:
Just in case you want a new array you can use sample:

```<code>import random
new_array = random.sample( array, len(array) )
</code>```

Body:
Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )


问:
C++ static member modifiers for subclasses
Consider the following code:

```<code>#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};
</code>```

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.

答:
Using CRTP may get you what you want, assuming you don't have to access GetAttr() through Base* and can leave without constattribute_ in Base itself. Just follow the rule that every programming problem can be solved by entering another level of indirection, which I did below:

```<code>class Base {
  public:
    virtual void do_something() const = 0;

    virtual ~Base()     // should define it as you are using Base*
    {
    }
};

typedef Base* Derived_Ptr;

template<class T>
class BaseConstAttr : public Base
{
  public:
    int GetAttrib () const
    {
      return(constattribute_);
    };

    static const int constattribute_;
};

class DerivedA : public BaseConstAttr<DerivedA>
{
  public:
    void do_something() const
    {
    };
};

class DerivedB : public BaseConstAttr<DerivedB>
{
  public:
    void do_something() const
    {
    };
};

template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);
</code>```

If you need GettAttr from top to bottom of the inheritance tree you can modify the above code a bit, but this will cost you making GetAttr virtual (but still one implementation only):

```<code>class Base {
  public:
    virtual void do_something() const = 0;
    virtual int GetAttrib () const = 0;

    virtual ~Base()     // should define it as you are using Base*
    {
    }
};

typedef Base* Derived_Ptr;

template<class T>
class BaseConstAttr : public Base
{
  public:
    int GetAttrib () const
    {
      return(constattribute_);
    };

    static const int constattribute_;
};

class DerivedA : public BaseConstAttr<DerivedA>
{
  public:
    void do_something() const
    {
    };
};

class DerivedB : public BaseConstAttr<DerivedB>
{
  public:
    void do_something() const
    {
    };
};

template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);
</code>```

Please note that I don't know how well (or bad) it will behave with deep inheritance tree (ie. when inheriting from DerivedA and/or DerivedB). In this case I would probably remove BaseConstAttr from inheritance tree right below Base and would try to inject it between most derived class and its predecessor or use multiple inheritance.

Body:
Consider the following code:

#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.

Body:
Using CRTP may get you what you want, assuming you don't have to access GetAttr() through Base* and can leave without constattribute_ in Base itself. Just follow the rule that every programming problem can be solved by entering another level of indirection, which I did below:

class Base {
  public:
    virtual void do_something() const = 0;

    virtual ~Base()     // should define it as you are using Base*
    {
    }
};

typedef Base* Derived_Ptr;

template<class T>
class BaseConstAttr : public Base
{
  public:
    int GetAttrib () const
    {
      return(constattribute_);
    };

    static const int constattribute_;
};

class DerivedA : public BaseConstAttr<DerivedA>
{
  public:
    void do_something() const
    {
    };
};

class DerivedB : public BaseConstAttr<DerivedB>
{
  public:
    void do_something() const
    {
    };
};

template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);

If you need GettAttr from top to bottom of the inheritance tree you can modify the above code a bit, but this will cost you making GetAttr virtual (but still one implementation only):

class Base {
  public:
    virtual void do_something() const = 0;
    virtual int GetAttrib () const = 0;

    virtual ~Base()     // should define it as you are using Base*
    {
    }
};

typedef Base* Derived_Ptr;

template<class T>
class BaseConstAttr : public Base
{
  public:
    int GetAttrib () const
    {
      return(constattribute_);
    };

    static const int constattribute_;
};

class DerivedA : public BaseConstAttr<DerivedA>
{
  public:
    void do_something() const
    {
    };
};

class DerivedB : public BaseConstAttr<DerivedB>
{
  public:
    void do_something() const
    {
    };
};

template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);

Please note that I don't know how well (or bad) it will behave with deep inheritance tree (ie. when inheriting from DerivedA and/or DerivedB). In this case I would probably remove BaseConstAttr from inheritance tree right below Base and would try to inject it between most derived class and its predecessor or use multiple inheritance.


问:
How to modify videomixer sink pad alpha value dynamically
I want to take a video file and overlay subtitles that fade in and fade out.

I'm just beginning to learn how to work with Gstreamer.

So far, I've managed to put together a pipeline that composits a subtitle stream drawn by the textrender element onto an original video stream with the videomixer element.  Unfortunately, textrender, and its sister element textoverlay do not have a fade-in/fade-out feature.

The videomixer sink pad does have an alpha property.  For now, I have set the alpha value of the pad named videomixer.sink_1 to 1.0.  Here is the command-line version of that pipeline:

```<code>#!/bin/bash

gst-launch-1.0 \
    filesrc location=sample_videos/my-video.mp4 ! decodebin ! mixer.sink_0 \
    filesrc location=subtitles.srt ! subparse ! textrender !  mixer.sink_1 \
    videomixer name=mixer sink_0::zorder=2 sink_1::zorder=3 sink_1::ypos=-25 sink_1::alpha=1 \
        ! video/x-raw, height=540 \
        ! videoconvert ! autovideosink
</code>```

I am looking for a way to dynamically modify that alpha value over time so that I can make the subtitle component fade in and out at the appropriate times.  (I will parse the SRT file separately to determine when fades begin and end.)

I am studying the GstBin C API (my actual code is in Python).  I think after I create the pipeline with Gst.parse_launch(), I can grab any named element with gst_get_bin_by_name(), then use that value to access the pad "sink_1".

Once I've gotten that far, will I be able to modify that alpha value dynamically from an event handler that receives timer events?  Will the videomixer element respond instantly to changes in that pad's property?  Has anyone else done this?

I found a partial answers here: https://stackoverflow.com/a/17331845/270511 but they don't tell me if this will work after the pipeline is running.

答: I got this to work.  You can read about it in this post: https://westside-consulting.blogspot.com/2017/03/getting-to-know-gstreamer-part-4.html</p>

Body:
I want to take a video file and overlay subtitles that fade in and fade out.

I'm just beginning to learn how to work with Gstreamer.

So far, I've managed to put together a pipeline that composits a subtitle stream drawn by the textrender element onto an original video stream with the videomixer element.  Unfortunately, textrender, and its sister element textoverlay do not have a fade-in/fade-out feature.

The videomixer sink pad does have an alpha property.  For now, I have set the alpha value of the pad named videomixer.sink_1 to 1.0.  Here is the command-line version of that pipeline:

#!/bin/bash

gst-launch-1.0 \
    filesrc location=sample_videos/my-video.mp4 ! decodebin ! mixer.sink_0 \
    filesrc location=subtitles.srt ! subparse ! textrender !  mixer.sink_1 \
    videomixer name=mixer sink_0::zorder=2 sink_1::zorder=3 sink_1::ypos=-25 sink_1::alpha=1 \
        ! video/x-raw, height=540 \
        ! videoconvert ! autovideosink

I am looking for a way to dynamically modify that alpha value over time so that I can make the subtitle component fade in and out at the appropriate times.  (I will parse the SRT file separately to determine when fades begin and end.)

I am studying the GstBin C API (my actual code is in Python).  I think after I create the pipeline with Gst.parse_launch(), I can grab any named element with gst_get_bin_by_name(), then use that value to access the pad "sink_1".

Once I've gotten that far, will I be able to modify that alpha value dynamically from an event handler that receives timer events?  Will the videomixer element respond instantly to changes in that pad's property?  Has anyone else done this?

I found a partial answers here: https://stackoverflow.com/a/17331845/270511 but they don't tell me if this will work after the pipeline is running.


问:
rearrange a variable based on another variable
Data:

```<code>set.seed(25)
df<- data.frame(rank=round(rnorm(10)),category=round(runif(10)),v=round(rnorm(10)))

   rank category  v
1     0        0  1
2    -1        0 -1
3    -1        0  1
4     0        0  2
5    -2        0 -1
6     0        0  1
7     2        0  0
8     1        1  0
9     0        1  2
10    0        0 -2
</code>```

I want the variable "v" follows the same ranking as the variable "rank1", within each category. My question is how could I create the desired variable "v1"?

Desired output:

```<code>df <- transform(df, rank1 = ave(v, category, FUN = function(x) rank(x, ties.method = "random")))

   rank category  v rank1  v1
1     0        0  1     6 -1
2    -1        0 -1     3  1
3    -1        0  1     7 -1
4     0        0  2     8 -2
5    -2        0 -1     2  1
6     0        0  1     5  0
7     2        0  0     4  1
8     1        1  0     1  2
9     0        1  2     2  0
10    0        0 -2     1  2
</code>```

答:
So I get the desired result:

```<code>set.seed(25)
df <- data.frame(rank=round(rnorm(10)), category=round(runif(10)), v=round(rnorm(10)))
df <- transform(df, rank1 = ave(v, category, FUN = function(x) rank(x, ties.method = "random")))

df$v1 <- NA

for (i in unique(df$category)) {
  df$v1[df$category==i] <- sort(df$v[df$category==i], decrea=TRUE)[df$rank1[df$category==i]]
}
</code>```

The idea is going through the categories and apply the order given by rank1 to the sorted part of the vector v.

Body:
Data:

set.seed(25)
df<- data.frame(rank=round(rnorm(10)),category=round(runif(10)),v=round(rnorm(10)))

   rank category  v
1     0        0  1
2    -1        0 -1
3    -1        0  1
4     0        0  2
5    -2        0 -1
6     0        0  1
7     2        0  0
8     1        1  0
9     0        1  2
10    0        0 -2

I want the variable "v" follows the same ranking as the variable "rank1", within each category. My question is how could I create the desired variable "v1"?

Desired output:

df <- transform(df, rank1 = ave(v, category, FUN = function(x) rank(x, ties.method = "random")))

   rank category  v rank1  v1
1     0        0  1     6 -1
2    -1        0 -1     3  1
3    -1        0  1     7 -1
4     0        0  2     8 -2
5    -2        0 -1     2  1
6     0        0  1     5  0
7     2        0  0     4  1
8     1        1  0     1  2
9     0        1  2     2  0
10    0        0 -2     1  2

Body:
So I get the desired result:

set.seed(25)
df <- data.frame(rank=round(rnorm(10)), category=round(runif(10)), v=round(rnorm(10)))
df <- transform(df, rank1 = ave(v, category, FUN = function(x) rank(x, ties.method = "random")))

df$v1 <- NA

for (i in unique(df$category)) {
  df$v1[df$category==i] <- sort(df$v[df$category==i], decrea=TRUE)[df$rank1[df$category==i]]
}

The idea is going through the categories and apply the order given by rank1 to the sorted part of the vector v.


问:
Samsung "App optimisation" feature kills background applications after 3 days
We are currently developing an Android app that is a fitness-tracker application. It runs constantly in the background, and it works fine on most devices, but we've been having issues with the application dying completely on some Samsung devices. After some investigation, it seems like some Samsung devices has a completely custom "App Optimisation" feature (http://forums.androidcentral.com/samsung-galaxy-s6/599408-app-optimisation-after-updating.html), which is basically a (very) primitive version of the Doze feature that exists in later versions of Android which basically just murders apps if they haven't been used for three days.

As this app is more or less only doing logging, and doesn't open the activity, it presents a big problem for us, because this feature is pre-enabled on many Samsung devices. The problem is solved by using a foreground service, but that is a sledgehammer of a solution that requires disturbing the user with a constant notification, and we really don't need the app to be in the foreground - we are fine with the normal power management of Android.

The Samsung App Optimisation feature clearly states that it will "optimise" apps if they have not been used for three days. Does anyone have insight in what Samsung considers to be "used" and can I somehow trigger that?

Side-rant: In my opinion, this is a badly implemented feature that makes development on Android more hostile. Besides our use case, it will any messenger applications break. If it were not for the fact that Facebook Messenger and Whatsapp are hard-wired to be exempt for the app, users would be going crazy because it would be breaking their experiences.

答:
I've owned (and currently own) Samsung devices, so I know a little as to how it works from the user's point of view. The technical specifications and how it works on the inside is an entirely separate issue, and one I can't answer.

The system can detect if you open an app. Samsung uses that in their app optimization, and will save power on apps that haven't been used in over three days. It is a terrible system though.

It ignores background-processes that may be critical to apps, and even if it is an app you actively use, like a fitness tracker, it will have issues. To quote what it says inside the app optimization-list:

"To save battery power, apps that haven't been used for more than 3 days will be designated to save power. Apps designated to save power may not show notifications"

(Rough translation from Norwegian, originally taken from an S6 running Android 6)

Therefore, apps that have been manually, or automatically set (3 days of no use) may give various issues with background processes. But remember that the user can set any app to never save battery, and ignoring the automatic setting. So with this in mind, let's consider possible solutions.

There is one scenario where you do not need to worry about the app and app optimization: When app optimization is disabled entirely.

Looking aside that, there is really only two things you can do:

Ask users on Samsung to disable battery optimization for your app to prevent issues

As @MinaSamy suggested (in their now deleted answer), SyncAdapter and having a periodic synchronization. Note that I haven't tested this, so I don't know whether it works or not.

And there's also a third option, which really isn't a solution, but you can ignore it and gamble on app optimization being disabled, or just not care about it at all.

Does anyone have insight in what Samsung considers to be "used" and can I somehow trigger that?

As far as I know, unless Samsung added some safeguards against accidental opening or added some kind of minimum activity requirement, opening is enough. It appears to be a "stupid" feature, which runs on hard-coded rules rather than a dynamic system that actually detects app use and sets power saving relative to that. It's "easy to enable", but fortunately easy to disable as well.

Meaning you cannot trigger an event that will keep it alive (unless SyncAdapter does the trick)

And to make the facts clear, from @Neil's answer:

It does seem like the user can do this, so there must be some database or setting somewhere that controls it.

There kinda is. There are a total of four settings, three of which are app-specific, and it is stored in a database (or some other form of data storage). These four settings can be used, although extremely shallow, to alter the behavior of the app optimization:

Always optimize

Automatic optimization

Never optimize

Disable app optimization

The first three options are on a per-app basis, which means each app can have separate settings. Disabling app optimization is exactly what you'd expect: it disables the entire feature for all apps. If it's disabled entirely, nothing is optimized.

There's also a website listing ways of bypassing optimizations on a per-brand basis. The entry for Samsung is more or less what I've said: tell the user to manually disable optimization. There are no developer solutions.

ContentLicense: CC BY-SA 4.0


问:
React Native -Why does the Touchable Highlight press automatically?
When I run the application the TouchableHighlight onPress event is called automatically.
Also the button does not change color on, onPress event.
Here is the code,

```<code>    import React, { Component } from 'react';
    import formatTime from 'minutes-seconds-milliseconds';

    import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
    } from 'react-native';

    class Stopwatch extends Component {

    constructor(props) {
    super(props);
    this.state = {
      timerRunning: true,
      timeDisplayed: null,
    }
    }

    _onPressStart() {
    console.log('start button')
    /*setInterval(function(){ alert("Hello Start"); }, 3000);*/
    }

    _onPressLap() {
    console.log('lap button')
    /*setInterval(function(){ alert("Hello Lap"); }, 3000);*/
    }

    render() {
     return (
      <View style={styles.overallContainer}>
        <View style={styles.upperContainer}>
          <View style={styles.timeCover}>
            <Text style={styles.timeWrapper}>
              {formatTime(this.state.timeDisplayed)}
            </Text>
          </View>
          <View style={styles.buttonCover}>
            <TouchableHighlight style={styles.button} onPress = {this._onPressStart()}>
              <Text>Start</Text>
            </TouchableHighlight>
            <TouchableHighlight style={styles.button} onPress = {this._onPressLap()}>
              <Text>Lap</Text>
            </TouchableHighlight>
          </View>
        </View>
        <View style={styles.lapCover}>
          <Text>
            List of laps
          </Text>
        </View>
    </View>
    );
    }
    }

    const styles = StyleSheet.create({

    overallContainer: {
    flex: 1,
    },

    upperContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
    borderWidth: 4,
    borderColor: 'yellow',
    },
    timeWrapper: {
    fontSize: 50,
    },
    startWrapper: {
    fontSize: 20,
    },
    lapWrapper: {
    fontSize: 20,
    },
    timeCover: {
    flex:5,
    borderWidth: 2,
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'red',
    },
    buttonCover: {
    flex:3,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'green',
    },
    lapCover: {
    flex:1,
    borderWidth: 4,
    borderColor: 'blue',
    },
    button: {
    borderRadius: 50,
    borderWidth: 2,
    height:100,
    width:100,
    justifyContent: 'center',
    alignItems: 'center'
    }
    });

    AppRegistry.registerComponent('Stopwatch', () => Stopwatch);

When I execute the application in iphone simulator, it displays "import React, { Component } from 'react';
import formatTime from 'minutes-seconds-milliseconds';

import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';

class Stopwatch extends Component {

  constructor(props) {
    super(props);
    this.state = {
      timerRunning: true,
      timeDisplayed: null,
    }
  }

  _onPressStart() {
    console.log('start button')
    /*setInterval(function(){ alert("Hello Start"); }, 3000);*/
  }

  _onPressLap() {
    console.log('lap button')
    /*setInterval(function(){ alert("Hello Lap"); }, 3000);*/
  }

  render() {
    return (
      <View style={styles.overallContainer}>
        <View style={styles.upperContainer}>
          <View style={styles.timeCover}>
            <Text style={styles.timeWrapper}>
              {formatTime(this.state.timeDisplayed)}
            </Text>
          </View>
          <View style={styles.buttonCover}>
            <TouchableHighlight style={styles.button} onPress = {this._onPressStart()}>
              <Text>Start</Text>
            </TouchableHighlight>
            <TouchableHighlight style={styles.button} onPress = {this._onPressLap()}>
              <Text>Lap</Text>
            </TouchableHighlight>
          </View>
        </View>
        <View style={styles.lapCover}>
          <Text>
            List of laps
          </Text>
        </View>
    </View>
    );
  }
}

const styles = StyleSheet.create({

  overallContainer: {
    flex: 1,
  },

  upperContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
    borderWidth: 4,
    borderColor: 'yellow',
  },
  timeWrapper: {
    fontSize: 50,
  },
  startWrapper: {
    fontSize: 20,
  },
  lapWrapper: {
    fontSize: 20,
  },
  timeCover: {
    flex:5,
    borderWidth: 2,
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'red',
  },
  buttonCover: {
    flex:3,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'green',
  },
  lapCover: {
    flex:1,
    borderWidth: 4,
    borderColor: 'blue',
  },
  button: {
    borderRadius: 50,
    borderWidth: 2,
    height:100,
    width:100,
    justifyContent: 'center',
    alignItems: 'center'
  }

});

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

When I run the application in iphone simulator the debugger shows "start button" and "lap buttin" even before pressing the buttons.

答:
This is because of the fact you have this._onPressStart() instead of this._onPressStart

this._onPressStart() calls the function when the coded reaches it, but you want to run it when the events happens therefore you need to use this._onPressStart

Body:
When I run the application the TouchableHighlight onPress event is called automatically.
Also the button does not change color on, onPress event.
Here is the code,

    import React, { Component } from 'react';
    import formatTime from 'minutes-seconds-milliseconds';

    import {
    AppRegistry,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
    } from 'react-native';

    class Stopwatch extends Component {

    constructor(props) {
    super(props);
    this.state = {
      timerRunning: true,
      timeDisplayed: null,
    }
    }

    _onPressStart() {
    console.log('start button')
    /*setInterval(function(){ alert("Hello Start"); }, 3000);*/
    }

    _onPressLap() {
    console.log('lap button')
    /*setInterval(function(){ alert("Hello Lap"); }, 3000);*/
    }

    render() {
     return (
      <View style={styles.overallContainer}>
        <View style={styles.upperContainer}>
          <View style={styles.timeCover}>
            <Text style={styles.timeWrapper}>
              {formatTime(this.state.timeDisplayed)}
            </Text>
          </View>
          <View style={styles.buttonCover}>
            <TouchableHighlight style={styles.button} onPress = {this._onPressStart()}>
              <Text>Start</Text>
            </TouchableHighlight>
            <TouchableHighlight style={styles.button} onPress = {this._onPressLap()}>
              <Text>Lap</Text>
            </TouchableHighlight>
          </View>
        </View>
        <View style={styles.lapCover}>
          <Text>
            List of laps
          </Text>
        </View>
    </View>
    );
    }
    }

    const styles = StyleSheet.create({

    overallContainer: {
    flex: 1,
    },

    upperContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
    borderWidth: 4,
    borderColor: 'yellow',
    },
    timeWrapper: {
    fontSize: 50,
    },
    startWrapper: {
    fontSize: 20,
    },
    lapWrapper: {
    fontSize: 20,
    },
    timeCover: {
    flex:5,
    borderWidth: 2,
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'red',
    },
    buttonCover: {
    flex:3,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'green',
    },
    lapCover: {
    flex:1,
    borderWidth: 4,
    borderColor: 'blue',
    },
    button: {
    borderRadius: 50,
    borderWidth: 2,
    height:100,
    width:100,
    justifyContent: 'center',
    alignItems: 'center'
    }
    });

    AppRegistry.registerComponent('Stopwatch', () => Stopwatch);

When I execute the application in iphone simulator, it displays "import React, { Component } from 'react';
import formatTime from 'minutes-seconds-milliseconds';

import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';

class Stopwatch extends Component {

  constructor(props) {
    super(props);
    this.state = {
      timerRunning: true,
      timeDisplayed: null,
    }
  }

  _onPressStart() {
    console.log('start button')
    /*setInterval(function(){ alert("Hello Start"); }, 3000);*/
  }

  _onPressLap() {
    console.log('lap button')
    /*setInterval(function(){ alert("Hello Lap"); }, 3000);*/
  }

  render() {
    return (
      <View style={styles.overallContainer}>
        <View style={styles.upperContainer}>
          <View style={styles.timeCover}>
            <Text style={styles.timeWrapper}>
              {formatTime(this.state.timeDisplayed)}
            </Text>
          </View>
          <View style={styles.buttonCover}>
            <TouchableHighlight style={styles.button} onPress = {this._onPressStart()}>
              <Text>Start</Text>
            </TouchableHighlight>
            <TouchableHighlight style={styles.button} onPress = {this._onPressLap()}>
              <Text>Lap</Text>
            </TouchableHighlight>
          </View>
        </View>
        <View style={styles.lapCover}>
          <Text>
            List of laps
          </Text>
        </View>
    </View>
    );
  }
}

const styles = StyleSheet.create({

  overallContainer: {
    flex: 1,
  },

  upperContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
    borderWidth: 4,
    borderColor: 'yellow',
  },
  timeWrapper: {
    fontSize: 50,
  },
  startWrapper: {
    fontSize: 20,
  },
  lapWrapper: {
    fontSize: 20,
  },
  timeCover: {
    flex:5,
    borderWidth: 2,
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'red',
  },
  buttonCover: {
    flex:3,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'green',
  },
  lapCover: {
    flex:1,
    borderWidth: 4,
    borderColor: 'blue',
  },
  button: {
    borderRadius: 50,
    borderWidth: 2,
    height:100,
    width:100,
    justifyContent: 'center',
    alignItems: 'center'
  }

});

AppRegistry.registerComponent('Stopwatch', () => Stopwatch);

When I run the application in iphone simulator the debugger shows "start button" and "lap buttin" even before pressing the buttons.


问:
ArrayOutofBounds and NumberFormat Exception
I am getting those two exceptions when using token split method and parse int.
ArrayOutofBounds when I have the printline statement in the code, and the other one when I comment out the printline statement

```<code>public class MyArtistNodes {

public ArrayList<ArtistNode> myArtistNodes = null;

public MyArtistNodes(String filename) {
       Scanner input;

       try {
           input = new Scanner(new File(filename));
           myArtistNodes = new ArrayList<ArtistNode>();
           while(input != null && input.hasNext()) {

               String line = input.nextLine();
               String[] tokens = line.trim().split("@");
               tokens = line.split(" ");
              // System.out.println(tokens.length+" "+tokens[1]+" -- "+Integer.parseInt(tokens[0].trim()));
               ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
               myArtistNodes.add(newA);
           }
           input.close();

       } catch (NumberFormatException | FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }
</code>```

Error:

```<code>     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

     at MyArtistNodes.<init>(MyArtistNodes.java:27)

     at Exam3Step3A.<init>(Exam3Step3A.java:6)

     at Exam3.main(Exam3.java:6)
</code>```

答:
Error NumberFormat Exception it could be because of this line:

```<code>       ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
</code>```

as you can see you're traying to make an Integer from a String (tokens[0]) so, your token[0] must not be a valid number sometimes and that is why you get that excepcion.

ArrayIndexOutOfBoundsException

it could be because you're trying to read the array in a position that does not exist and the problem should be in the same line:

```<code>   ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
</code>```

maybe your

```<code>  String[] tokens = line.trim().split("@");
               tokens = line.split(" ");
</code>```

split didn't work for all cases.

Hope it helps

Body:
I am getting those two exceptions when using token split method and parse int.
ArrayOutofBounds when I have the printline statement in the code, and the other one when I comment out the printline statement

public class MyArtistNodes {

public ArrayList<ArtistNode> myArtistNodes = null;

public MyArtistNodes(String filename) {
       Scanner input;

       try {
           input = new Scanner(new File(filename));
           myArtistNodes = new ArrayList<ArtistNode>();
           while(input != null && input.hasNext()) {

               String line = input.nextLine();
               String[] tokens = line.trim().split("@");
               tokens = line.split(" ");
              // System.out.println(tokens.length+" "+tokens[1]+" -- "+Integer.parseInt(tokens[0].trim()));
               ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
               myArtistNodes.add(newA);
           }
           input.close();

       } catch (NumberFormatException | FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

Error:

     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

     at MyArtistNodes.<init>(MyArtistNodes.java:27)

     at Exam3Step3A.<init>(Exam3Step3A.java:6)

     at Exam3.main(Exam3.java:6)

Body:
Error NumberFormat Exception it could be because of this line:

       ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));

as you can see you're traying to make an Integer from a String (tokens[0]) so, your token[0] must not be a valid number sometimes and that is why you get that excepcion.

ArrayIndexOutOfBoundsException

it could be because you're trying to read the array in a position that does not exist and the problem should be in the same line:

   ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));

maybe your

  String[] tokens = line.trim().split("@");
               tokens = line.split(" ");

split didn't work for all cases.

Hope it helps


问:
Fetching language detection from Google api
I have a CSV with keywords in one column and the number of impressions in a second column.

I'd like to provide the keywords in a url (while looping) and for the Google language api to return what type of language was the keyword in.

I have it working manually. If I enter (with the correct api key):
http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=merde
I get:
{"responseData": {"language":"fr","isReliable":false,"confidence":6.213709E-4}, "responseDetails": null, "responseStatus": 200}
which is correct, 'merde' is French.

so far I have this code but I keep getting server unreachable errors:

```<code>import time
import csv
from operator import itemgetter
import sys
import fileinput
import urllib2
import json

E_OPERATION_ERROR = 1
E_INVALID_PARAMS = 2

#not working
def parse_result(result):
  """Parse a JSONP result string and return a list of terms"""

  # Deserialize JSON to Python objects
  result_object = json.loads(result)

  #Get the rows in the table, then get the second column's value
  # for each row
  return row in result_object

#not working
def retrieve_terms(seedterm):

  print(seedterm)
  """Retrieves and parses data and returns a list of terms"""
  url_template = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=%(seed)s'
  url = url_template % {"seed": seedterm}

  try:
    with urllib2.urlopen(url) as data:
      data = perform_request(seedterm)
      result = data.read()
  except:
    sys.stderr.write('%s\n' % 'Could not request data from server')
    exit(E_OPERATION_ERROR)

  #terms = parse_result(result)
  #print terms
  print result

def main(argv):
  filename = argv[1]

  csvfile = open(filename, 'r')
  csvreader = csv.DictReader(csvfile)

  rows = []
  for row in csvreader:
    rows.append(row)

  sortedrows = sorted(rows, key=itemgetter('impressions'), reverse = True)

  keys = sortedrows[0].keys()

  for item in sortedrows:
    retrieve_terms(item['keywords'])

  try:
    outputfile = open('Output_%s.csv' % (filename),'w')
  except IOError:
    print("The file is active in another program - close it first!")
    sys.exit()
  dict_writer = csv.DictWriter(outputfile, keys, lineterminator='\n')
  dict_writer.writer.writerow(keys)
  dict_writer.writerows(sortedrows)
  outputfile.close()

  print("File is Done!! Check your folder")

if __name__ == '__main__':
  start_time = time.clock()
  main(sys.argv)
  print("\n")
  print time.clock() - start_time, "seconds for script time"
</code>```

Any idea how to finish the code so that it will work?  Thank you!

答:
Try to add referrer, userip as described in the docs:

An area to pay special attention to
  relates to correctly identifying
  yourself in your requests.
  Applications MUST always include a
  valid and accurate http referer header
  in their requests. In addition, we
  ask, but do not require, that each
  request contains a valid API Key. By
  providing a key, your application
  provides us with a secondary
  identification mechanism that is
  useful should we need to contact you
  in order to correct any problems. Read
  more about the usefulness of having an
  API key

Developers are also encouraged to make
  use of the userip parameter (see
  below) to supply the IP address of the
  end-user on whose behalf you are
  making the API request. Doing so will
  help distinguish this legitimate
  server-side traffic from traffic which
  doesn't come from an end-user.

Here's an example based on the answer to the question "access to google with python":

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import urllib, urllib2
from pprint import pprint

api_key, userip = None, None
query = {'q' : 'матрёшка'}
referrer = "https://stackoverflow.com/q/4309599/4279"

if userip:
    query.update(userip=userip)
if api_key:
    query.update(key=api_key)

url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&%s' %(
    urllib.urlencode(query))

request = urllib2.Request(url, headers=dict(Referer=referrer))
json_data = json.load(urllib2.urlopen(request))

pprint(json_data['responseData'])
</code>```

Output

```<code>{u'confidence': 0.070496580000000003, u'isReliable': False, u'language': u'ru'}
</code>```

Another issue might be that seedterm is not properly quoted:

```<code>if isinstance(seedterm, unicode):
   value = seedterm
else: # bytes
   value = seedterm.decode(put_encoding_here)
url = 'http://...q=%s' % urllib.quote_plus(value.encode('utf-8'))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a CSV with keywords in one column and the number of impressions in a second column.

I'd like to provide the keywords in a url (while looping) and for the Google language api to return what type of language was the keyword in.

I have it working manually. If I enter (with the correct api key):
http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=merde
I get:
{"responseData": {"language":"fr","isReliable":false,"confidence":6.213709E-4}, "responseDetails": null, "responseStatus": 200}
which is correct, 'merde' is French.

so far I have this code but I keep getting server unreachable errors:

import time
import csv
from operator import itemgetter
import sys
import fileinput
import urllib2
import json

E_OPERATION_ERROR = 1
E_INVALID_PARAMS = 2

#not working
def parse_result(result):
  """Parse a JSONP result string and return a list of terms"""

  # Deserialize JSON to Python objects
  result_object = json.loads(result)

  #Get the rows in the table, then get the second column's value
  # for each row
  return row in result_object

#not working
def retrieve_terms(seedterm):

  print(seedterm)
  """Retrieves and parses data and returns a list of terms"""
  url_template = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&key=myapikey&q=%(seed)s'
  url = url_template % {"seed": seedterm}

  try:
    with urllib2.urlopen(url) as data:
      data = perform_request(seedterm)
      result = data.read()
  except:
    sys.stderr.write('%s\n' % 'Could not request data from server')
    exit(E_OPERATION_ERROR)

  #terms = parse_result(result)
  #print terms
  print result

def main(argv):
  filename = argv[1]

  csvfile = open(filename, 'r')
  csvreader = csv.DictReader(csvfile)

  rows = []
  for row in csvreader:
    rows.append(row)

  sortedrows = sorted(rows, key=itemgetter('impressions'), reverse = True)

  keys = sortedrows[0].keys()

  for item in sortedrows:
    retrieve_terms(item['keywords'])

  try:
    outputfile = open('Output_%s.csv' % (filename),'w')
  except IOError:
    print("The file is active in another program - close it first!")
    sys.exit()
  dict_writer = csv.DictWriter(outputfile, keys, lineterminator='\n')
  dict_writer.writer.writerow(keys)
  dict_writer.writerows(sortedrows)
  outputfile.close()

  print("File is Done!! Check your folder")

if __name__ == '__main__':
  start_time = time.clock()
  main(sys.argv)
  print("\n")
  print time.clock() - start_time, "seconds for script time"

Any idea how to finish the code so that it will work?  Thank you!

Body:
Try to add referrer, userip as described in the docs:

An area to pay special attention to
  relates to correctly identifying
  yourself in your requests.
  Applications MUST always include a
  valid and accurate http referer header
  in their requests. In addition, we
  ask, but do not require, that each
  request contains a valid API Key. By
  providing a key, your application
  provides us with a secondary
  identification mechanism that is
  useful should we need to contact you
  in order to correct any problems. Read
  more about the usefulness of having an
  API key

Developers are also encouraged to make
  use of the userip parameter (see
  below) to supply the IP address of the
  end-user on whose behalf you are
  making the API request. Doing so will
  help distinguish this legitimate
  server-side traffic from traffic which
  doesn't come from an end-user.

Here's an example based on the answer to the question "access to google with python":

#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import urllib, urllib2
from pprint import pprint

api_key, userip = None, None
query = {'q' : 'матрёшка'}
referrer = "https://stackoverflow.com/q/4309599/4279"

if userip:
    query.update(userip=userip)
if api_key:
    query.update(key=api_key)

url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&%s' %(
    urllib.urlencode(query))

request = urllib2.Request(url, headers=dict(Referer=referrer))
json_data = json.load(urllib2.urlopen(request))

pprint(json_data['responseData'])

Output

{u'confidence': 0.070496580000000003, u'isReliable': False, u'language': u'ru'}

Another issue might be that seedterm is not properly quoted:

if isinstance(seedterm, unicode):
   value = seedterm
else: # bytes
   value = seedterm.decode(put_encoding_here)
url = 'http://...q=%s' % urllib.quote_plus(value.encode('utf-8'))


问:
Represent numeric value with typical dollar amount format
I have a data frame storing the dollar amount, it looks like this

```<code>> a
  cost
1 1e+05
2 2e+05
</code>```

I would like it can be shown as this

```<code>> a
  cost
1 $100,000
2 $200,000
</code>```

How to do that in R?

答:
You can use the currency() function from the formattable package. With OP's example

```<code>a <- data.frame(cost = c(1e+05, 2e+05))
a
</code>```

```<code>   cost
1 1e+05
2 2e+05
</code>```

```<code>library(formattable)
a$cost <- currency(a$cost, digits = 0L)
a
</code>```

```<code>      cost
1 $100,000
2 $200,000
</code>```

By default, 2 digits after the decimal point are shown. This has been overruled using the digits parameter to meet OP's expectations.

The benfit of formattable is that numbers are still numbers even with a format attached, e.g.,

```<code>a$cost2 <- 2 * a$cost
a
</code>```

```<code>      cost    cost2
1 $100,000 $200,000
2 $200,000 $400,000
</code>```

Body:
I have a data frame storing the dollar amount, it looks like this

> a
  cost
1 1e+05
2 2e+05

I would like it can be shown as this

> a
  cost
1 $100,000
2 $200,000

How to do that in R?

Body:
You can use the currency() function from the formattable package. With OP's example

a <- data.frame(cost = c(1e+05, 2e+05))
a

   cost
1 1e+05
2 2e+05

library(formattable)
a$cost <- currency(a$cost, digits = 0L)
a

      cost
1 $100,000
2 $200,000

By default, 2 digits after the decimal point are shown. This has been overruled using the digits parameter to meet OP's expectations.

The benfit of formattable is that numbers are still numbers even with a format attached, e.g.,

a$cost2 <- 2 * a$cost
a

      cost    cost2
1 $100,000 $200,000
2 $200,000 $400,000


问:
How register overloaded template member function in ChaiScript?
I have the next definition class:

```<code>class MyType {
public:
    template <typename T>
    MyType& put(const std::string& s, T&& val);

    template <typename T>
    MyType& put(size_t pos, T&& val);

    template <typename M, typename T, typename = std::enable_if_t<std::is_same<MyType, std::decay_t<M>>::value>>
    MyType& put(const M& o, T&& val);
}
</code>```

How is the right way to register overloaded template member functions MyType::put in ChaiScript v6.0.0?

I am trying specialized value template (Discussed in: http://discourse.chaiscript.com/t/issues-with-adding-templated-and-or-overloaded-operators/19/3):

```<code>chai.add(chaiscript::fun(static_cast<MyType& (MyType::*)(const std::string&, uint64_t)>(&MyType::put<uint64_t>), "put");
</code>```

But not compile because there several candidate function.

答:
You wrote:

```<code>static_cast<MyType& (MyType::*)(const std::string&, uint64_t)>(
    &MyType::put<uint64_t>)
</code>```

But if you look at your first member function, its signature is:

```<code>template <typename T>
MyType& put(const std::string& s, T&& val);
</code>```

If T is uint64_t, then the second argument isn't uint64_t. It's uint64_t&&. Hence, what you want is:

```<code>static_cast<MyType& (MyType::*)(const std::string&, uint64_t&&)>(
    &MyType::put<uint64_t>)
//                                                  ~~~~~~~~~~~
</code>```

Body:
I have the next definition class:

class MyType {
public:
    template <typename T>
    MyType& put(const std::string& s, T&& val);

    template <typename T>
    MyType& put(size_t pos, T&& val);

    template <typename M, typename T, typename = std::enable_if_t<std::is_same<MyType, std::decay_t<M>>::value>>
    MyType& put(const M& o, T&& val);
}

How is the right way to register overloaded template member functions MyType::put in ChaiScript v6.0.0?

I am trying specialized value template (Discussed in: http://discourse.chaiscript.com/t/issues-with-adding-templated-and-or-overloaded-operators/19/3):

chai.add(chaiscript::fun(static_cast<MyType& (MyType::*)(const std::string&, uint64_t)>(&MyType::put<uint64_t>), "put");

But not compile because there several candidate function.

Body:
You wrote:

static_cast<MyType& (MyType::*)(const std::string&, uint64_t)>(
    &MyType::put<uint64_t>)

But if you look at your first member function, its signature is:

template <typename T>
MyType& put(const std::string& s, T&& val);

If T is uint64_t, then the second argument isn't uint64_t. It's uint64_t&&. Hence, what you want is:

static_cast<MyType& (MyType::*)(const std::string&, uint64_t&&)>(
    &MyType::put<uint64_t>)
//                                                  ~~~~~~~~~~~


问:
Convert date and time into Correct format to compare to current date
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

```<code>string date = "2017-03-29";
string time  = "09:30"
</code>```

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

答:
Using the variables provided:</p>

```<code>  string dateTime = date + " " + time;
  DateTime d = Convert.ToDateTime(dateTime);
</code>```

Body:
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

string date = "2017-03-29";
string time  = "09:30"

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

Body:
Using the variables provided:

  string dateTime = date + " " + time;
  DateTime d = Convert.ToDateTime(dateTime);


问:
I get different results for same image in a program
I made a small program that calculates the number of white pixels in a grayscale image. I get different results if I open the image twice in the same program. Same if I display the intensity of the pixels, it changes even if it is the same image. If anyone sees where the problem is please help.

```<code>#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;
int main()
{ int i=0,j,nbr=0,nbr1=0;

Mat image=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);
Mat image2=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);

for(i=0;i<image.rows;i++)
{
    for( j=0;j<image.cols;j++)
    {if (image.at<int>(i,j)!=0)
           nbr++;
     if (image2.at<int>(i,j)!=0)
           nbr1++;
    }
}
printf("%d\n %d\n",nbr,nbr1);

    return 0;}
</code>```

Thank you for your help.

答: It is may be because you need to avoid using int, but uchar for grayscale image. Using int you go out of image memory.

Body:
I made a small program that calculates the number of white pixels in a grayscale image. I get different results if I open the image twice in the same program. Same if I display the intensity of the pixels, it changes even if it is the same image. If anyone sees where the problem is please help.

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace std;
using namespace cv;
int main()
{ int i=0,j,nbr=0,nbr1=0;

Mat image=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);
Mat image2=imread("2_.png",CV_LOAD_IMAGE_GRAYSCALE);

for(i=0;i<image.rows;i++)
{
    for( j=0;j<image.cols;j++)
    {if (image.at<int>(i,j)!=0)
           nbr++;
     if (image2.at<int>(i,j)!=0)
           nbr1++;
    }
}
printf("%d\n %d\n",nbr,nbr1);

    return 0;}

Thank you for your help.


问:
Vim Syntax Highlighting: highlight `self` python keyword with regex
I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword self but only when it is followed by a .. Here is the code I came up with:

```<code>syn match   pythonBoolean     "\(\Wself\)\%(\.\)"
</code>```

Unfortunately, the . is also highlighted though I use a non capturing group \%(\.\).

Any idea?

答:
Building on @Meninx's answer, I added this to my .vimrc:

```<code>augroup PythonCustomization
  " highlight python self, when followed by a comma, a period or a parenth
   :autocmd FileType python syn match pythonStatement "\(\W\|^\)\@<=self\([\.,)]\)\@="
augroup END
</code>```

Note 1: that in addition to what the op asked, it will also highlight when self is followed by a comma or a closing parenthesis.

Note 2: instead of using pythonBoolean, this highlights self using pythonStatement (personal preference). You can use other highlight-groups (run :syn with a python file open to see what's available)

Body:
I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword self but only when it is followed by a .. Here is the code I came up with:

syn match   pythonBoolean     "\(\Wself\)\%(\.\)"

Unfortunately, the . is also highlighted though I use a non capturing group \%(\.\).

Any idea?

Body:
Building on @Meninx's answer, I added this to my .vimrc:

augroup PythonCustomization
  " highlight python self, when followed by a comma, a period or a parenth
   :autocmd FileType python syn match pythonStatement "\(\W\|^\)\@<=self\([\.,)]\)\@="
augroup END

Note 1: that in addition to what the op asked, it will also highlight when self is followed by a comma or a closing parenthesis.

Note 2: instead of using pythonBoolean, this highlights self using pythonStatement (personal preference). You can use other highlight-groups (run :syn with a python file open to see what's available)


问:
Azure Mobile Apps Facebook Authentication stopped working
I'm using Azure Mobile Apps with the .NET SDK as a backend for my iOS app. The authentication done via Facebook. Yesterday out of nowhere (no code changes either on backend or app) the authentication with Facebook failed. The login inside the iOS client app is done via

```<code>self.client?.login(withProvider:"facebook", token: ["access_token" : FBSDKAccessToken.current().tokenString] ){ (user, error) in }
</code>```

By calling this function I'm getting the following result, on the client.

```<code>Error Domain=com.Microsoft.MicrosoftAzureMobile.ErrorDomain Code=-1302 "You do not have permission to view this directory or page."
</code>```

By inspecting the streaming logs of Azure Mobile Apps, I found out that the backend gets an Unauthorized 401.71 return back from calling the Facebook Graph API.

Streaming Log:

```<code>Microsoft.Azure.AppService.Authentication Verbose: 0 : Received request: POST https://XXXXXXXXXX.azurewebsites.net/.auth/login/facebook
'w3wp.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'D:\Windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll'. Skipped loading symbols.
'w3wp.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'D:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll'. Skipped loading symbols.
Microsoft.Azure.AppService.Authentication Verbose: 0 : Calling into external HTTP endpoint GET https://graph.facebook.com/oauth/access_token.
Microsoft.Azure.AppService.Authentication Information: 0 : Sending response: 401.71 Unauthorized
</code>```

I already tried cloning the Mobile App in Azure and creating a new Facebook App, without success.

答: This should be rolled out now.  If you have any further questions see the MSDN thread from above: https://social.msdn.microsoft.com/Forums/azure/en-US/397f6952-57bf-4c28-b383-6bba08d28f9a/facebook-login-failures-with-app-service-authentication-authorization?forum=windowsazurewebsitespreview</p>

Body:
I'm using Azure Mobile Apps with the .NET SDK as a backend for my iOS app. The authentication done via Facebook. Yesterday out of nowhere (no code changes either on backend or app) the authentication with Facebook failed. The login inside the iOS client app is done via

self.client?.login(withProvider:"facebook", token: ["access_token" : FBSDKAccessToken.current().tokenString] ){ (user, error) in }

By calling this function I'm getting the following result, on the client.

Error Domain=com.Microsoft.MicrosoftAzureMobile.ErrorDomain Code=-1302 "You do not have permission to view this directory or page."

By inspecting the streaming logs of Azure Mobile Apps, I found out that the backend gets an Unauthorized 401.71 return back from calling the Facebook Graph API.

Streaming Log:

Microsoft.Azure.AppService.Authentication Verbose: 0 : Received request: POST https://XXXXXXXXXX.azurewebsites.net/.auth/login/facebook
'w3wp.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'D:\Windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll'. Skipped loading symbols.
'w3wp.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'D:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll'. Skipped loading symbols.
Microsoft.Azure.AppService.Authentication Verbose: 0 : Calling into external HTTP endpoint GET https://graph.facebook.com/oauth/access_token.
Microsoft.Azure.AppService.Authentication Information: 0 : Sending response: 401.71 Unauthorized

I already tried cloning the Mobile App in Azure and creating a new Facebook App, without success.


问:
Configure logger in vertx 3
I am using vertx 3.0 with spring boot. Now I am trying to config logger log levels, using below config:

JVM Arguments:

```<code>-Dspring.profiles.active=dev
-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory
-Djava.util.logging.config.file=logging.properties
</code>```

logging.properties:

```<code>handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=ERROR
com.sensegrow.level=ERROR
</code>```

JAVA Class:

```<code>package com.sensegrow.main;

@SpringBootApplication
public class Application{

    private static Logger logger ;
    public static JsonObject config;
    private static Vertx vertx;

    // Convenience method so you can run it in your IDE
    public static void main(String[] args) throws Exception
    {
        logger = LoggerFactory.getLogger(Application.class);
        logger.trace("trace");
        logger.debug("debug");
        logger.info("info");
        logger.warn("warning");
        logger.error("error");
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Output:

```<code>16:29:58.073 [                main] INFO  - com.sensegrow.main.Application           - info
16:29:58.076 [                main] WARN  - com.sensegrow.main.Application           - warning
16:29:58.076 [                main] ERROR - com.sensegrow.main.Application           - error
</code>```

As log level for package com.sensegrow is error. Why I am getting Info and warn level logs.

答:
I configured Logback in Vert.x successfully, you can check the details in the following answer:

https://stackoverflow.com/a/43101501/973418

Title: Configure logger in vertx 3

Body:
I am using vertx 3.0 with spring boot. Now I am trying to config logger log levels, using below config:

JVM Arguments:

-Dspring.profiles.active=dev
-Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory
-Djava.util.logging.config.file=logging.properties

logging.properties:

handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=ERROR
com.sensegrow.level=ERROR

JAVA Class:

package com.sensegrow.main;

@SpringBootApplication
public class Application{

    private static Logger logger ;
    public static JsonObject config;
    private static Vertx vertx;

    // Convenience method so you can run it in your IDE
    public static void main(String[] args) throws Exception
    {
        logger = LoggerFactory.getLogger(Application.class);
        logger.trace("trace");
        logger.debug("debug");
        logger.info("info");
        logger.warn("warning");
        logger.error("error");
        SpringApplication.run(Application.class, args);
    }
}

Output:

16:29:58.073 [                main] INFO  - com.sensegrow.main.Application           - info
16:29:58.076 [                main] WARN  - com.sensegrow.main.Application           - warning
16:29:58.076 [                main] ERROR - com.sensegrow.main.Application           - error

As log level for package com.sensegrow is error. Why I am getting Info and warn level logs.


问:
How Do I Configure SQL Server Security for a WCF Service?
I'm learning WCF. I've created a WCF service which uses a local SQL Server database. I've configured the database server to use Windows authentication. When I use the WCF service with a WPF application, everything works.

When I use the WCF service with a WPF browser application, however, I get an error which, I believe, means I don't have security configured properly. The specific error is: "That assembly does not allow partially trusted callers."

I'm trying to figure out how to configure the security properly, starting with the security in SQL Server, but I'm having trouble finding answers. Can anyone help me with these questions?

1) Do I need to reconfigure SQL Server to use SQL Server authentication instead of Windows authentication? If so, are there recommended guidelines for naming the user and configuring the privileges of the account created for the WCF service?

2) The database is on the local machine now only so I can experiment. Down the road, I'm going to move the database to a server. Will the security configuration required by WCF change when I do that?

-TC

答:
do you host your WCF in IIS (which version) or self hosted? If IIS then probably need to run IIS it in Full Trust mode

try not to use SQL Server Authentication if you don't have to.


问:
Javascript Table within Cognos, using List as Data
We have Javascript that will produce a chart from a table of data within the code.

We are looking to use Cognos to automate the process of pulling the data. Essentially we want to use a list within Report Studio to populate the table section of the below Javascript code.

We tried adding a HTML item before and after a list with the code that is before and after the table, and the page populates as blank.

Any help would be appreciated.
Thank you

```<code><script type="text/javascript"     src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
  google.charts.load("current", {packages:["timeline"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

var container = document.getElementById('example5.1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Room' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([

['Job1', '',  new Date(0,0,0,18,0,0), new Date(0,0,0,18,0,1) ],
['Job2', '',  new Date(0,0,0,18,3,0), new Date(0,0,0,18,3,7) ],
['Job3', '',  new Date(0,0,0,17,30,0), new Date(0,0,0,18,0,39) ],
['Job4', '',  new Date(0,0,0,18,0,0), new Date(0,0,0,18,10,19) ],
['Job5', '',  new Date(0,0,0,18,0,0), new Date(0,0,0,18,0,22) ]

  ]);

var options = {
  timeline: { colorByRowLabel: true }
};

chart.draw(dataTable, options);
  }

</script>

<div id="example5.1" style="height: 500px;" style="width: 100px;"></div>
</code>```

答:
We figured out how to do this.

First, we had to place the Javascript within a HTML Item within a Singleton. Once the HTML item with the JS was in the singleton, we were able to get the Chart to show (with the static table) when running the Cognos report.

Since we wanted the table within the JS to run from data in a Cognos Query, we removed the existing JS from the HTML, and placed the first part of the JS in an HTML item within a Singleton.

First part of the JS:

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
  google.charts.load("current", {packages:["timeline"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

var container = document.getElementById('example5.1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Room' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
</code>```

Next place a Repeater to the right of the HTML item. Place a HTML item within the Repeater. In the properties of this HTML item, change the Source Type to Data Item Value. In the Data Item Value, place your Data Item that you would like displayed within the table section of the JS.

NOTE: Make sure you format the Data Item with the same format as the table is in the original JS. Our Data Item code to make the table is outlined below. Use the [FinalDataItem] in the HTML within the Repeater.

[ConcatenatedDataItem]

```<code>'['''+[JobName]+''''+', ''' +
[ExecutionStatus] + ''''
+', new Date(0,0,0,'
+cast(Datepart({HH}, [StartTime]) as nvarchar(10)) + ','
+ cast(DatePart({MI}, [StartTime]) as nvarchar(10)) + ',' + cast(DatePart({SS}, [StartTime]) as nvarchar(10)) + '), new Date(0,0,0,' + cast(Datepart({HH}, [EndTime]) as nvarchar(10)) + ','
+ cast(DatePart({MI}, [EndTime]) as nvarchar(10)) + ',' + cast(DatePart({SS}, [EndTime]) as nvarchar(10)) + ') ]'
</code>```

Since each row needs a comma at the end, except the last row, we used the following method.

1) [RowNum]: Create a Data Item to give each row a number using running-count([YourConcatenatedDataItem]).

2) [MaxRowNum]: Make another data item to get the Max Row Number for the report using Maximum([RowNumberDataItem] FOR REPORT). Set both Aggregate Functions to Automatic.

3) [FinalDataItem]: Create a new Data Item. In this new Data Item we will make it so every row has a comma at the end, except the last row. Use CASE WHEN [RowNum] <> [MaxRowNum] THEN [YourConcatenatedDataItem]+',' ELSE [YourConcatenatedDataItem] END.

Back on the report you will want to add another HTML item to the right of the Repeater. In this HTML item you will place the last part of the JS within it.

```<code>  ]);

var options = {
  timeline: { colorByRowLabel: true }
};

chart.draw(dataTable, options);
  }

</script>

<div id="example5.1" style="height: 500px;" style="width: 100px;"></div>
</code>```

Body:
We figured out how to do this.

First, we had to place the Javascript within a HTML Item within a Singleton. Once the HTML item with the JS was in the singleton, we were able to get the Chart to show (with the static table) when running the Cognos report.

Since we wanted the table within the JS to run from data in a Cognos Query, we removed the existing JS from the HTML, and placed the first part of the JS in an HTML item within a Singleton.

First part of the JS:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
  google.charts.load("current", {packages:["timeline"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

var container = document.getElementById('example5.1');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Room' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([

Next place a Repeater to the right of the HTML item. Place a HTML item within the Repeater. In the properties of this HTML item, change the Source Type to Data Item Value. In the Data Item Value, place your Data Item that you would like displayed within the table section of the JS.

NOTE: Make sure you format the Data Item with the same format as the table is in the original JS. Our Data Item code to make the table is outlined below. Use the [FinalDataItem] in the HTML within the Repeater.

[ConcatenatedDataItem]

'['''+[JobName]+''''+', ''' +
[ExecutionStatus] + ''''
+', new Date(0,0,0,'
+cast(Datepart({HH}, [StartTime]) as nvarchar(10)) + ','
+ cast(DatePart({MI}, [StartTime]) as nvarchar(10)) + ',' + cast(DatePart({SS}, [StartTime]) as nvarchar(10)) + '), new Date(0,0,0,' + cast(Datepart({HH}, [EndTime]) as nvarchar(10)) + ','
+ cast(DatePart({MI}, [EndTime]) as nvarchar(10)) + ',' + cast(DatePart({SS}, [EndTime]) as nvarchar(10)) + ') ]'

Since each row needs a comma at the end, except the last row, we used the following method.

1) [RowNum]: Create a Data Item to give each row a number using running-count([YourConcatenatedDataItem]).

2) [MaxRowNum]: Make another data item to get the Max Row Number for the report using Maximum([RowNumberDataItem] FOR REPORT). Set both Aggregate Functions to Automatic.

3) [FinalDataItem]: Create a new Data Item. In this new Data Item we will make it so every row has a comma at the end, except the last row. Use CASE WHEN [RowNum] <> [MaxRowNum] THEN [YourConcatenatedDataItem]+',' ELSE [YourConcatenatedDataItem] END.

Back on the report you will want to add another HTML item to the right of the Repeater. In this HTML item you will place the last part of the JS within it.

  ]);

var options = {
  timeline: { colorByRowLabel: true }
};

chart.draw(dataTable, options);
  }

</script>

<div id="example5.1" style="height: 500px;" style="width: 100px;"></div>


问:
Changing Light Intensity Unity Multiplayer
I am currently facing an issue when trying to change the intensity of my light in multiplayer.

The light intensities changes fine for the person who starts the game, the host. However the people who connect to the host, their light intensity does not change.

I am trying to change the light intensity using the [SyncVar] however the player who connects to the host is not seeing the light intensity change at all. Here's my code:

```<code> using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;

 public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

     Light light;
     float fadeTime = 1f;
     [SyncVar(hook = "OnLightAmountChange")]
     float lightAmout = 0f;
     SpawnManager_waveLevel level;

     public override void OnStartLocalPlayer()
     {
         light = GetComponentInChildren<Light>();
         level = GetComponent<SpawnManager_waveLevel>();
         light.intensity = lightAmout;
     }

     // Update is called once per frame
     void Update () {

         changeLight();
     }

     void changeLight()
     {
         if (isLocalPlayer)
         {
             if (level.waveCounter == 1)
             {
                 lightAmout = 0.03f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
             else
             {
                 lightAmout = 1f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
         }
     }

     void OnLightAmountChange(float amount)
     {
         lightAmout = amount;
         changeLight();
     }
 }
</code>```

My issue is that the light intensity is only changing for one player, the host. I want the light intensity to change for all player who connect to the game. Any suggestions are welcome.

答:
Quite a simple fix - you aren't giving the script an alternative if 'isLocalPlayer' is false.

Here's a fixed light change for you:

```<code>void changeLight()
 {
     if (isLocalPlayer)
     {
         if (level.waveCounter == 1)
         {
             lightAmout = 0.03f;
             light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
         }
         else
         {
             lightAmout = 1f;
             light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
         }
     }
     else{
         // If not a local player, simply update to the new light intensity.
         light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
     }
 }
</code>```

Body:
I am currently facing an issue when trying to change the intensity of my light in multiplayer.

The light intensities changes fine for the person who starts the game, the host. However the people who connect to the host, their light intensity does not change.

I am trying to change the light intensity using the [SyncVar] however the player who connects to the host is not seeing the light intensity change at all. Here's my code:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.Networking;

 public class dayNightCycle : NetworkBehaviour { //changes day and night based on the wavelevel SpawnManager_waveLevel.cs script

     Light light;
     float fadeTime = 1f;
     [SyncVar(hook = "OnLightAmountChange")]
     float lightAmout = 0f;
     SpawnManager_waveLevel level;

     public override void OnStartLocalPlayer()
     {
         light = GetComponentInChildren<Light>();
         level = GetComponent<SpawnManager_waveLevel>();
         light.intensity = lightAmout;
     }

     // Update is called once per frame
     void Update () {

         changeLight();
     }

     void changeLight()
     {
         if (isLocalPlayer)
         {
             if (level.waveCounter == 1)
             {
                 lightAmout = 0.03f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
             else
             {
                 lightAmout = 1f;
                 light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
             }
         }
     }

     void OnLightAmountChange(float amount)
     {
         lightAmout = amount;
         changeLight();
     }
 }

My issue is that the light intensity is only changing for one player, the host. I want the light intensity to change for all player who connect to the game. Any suggestions are welcome.

Body:
Quite a simple fix - you aren't giving the script an alternative if 'isLocalPlayer' is false.

Here's a fixed light change for you:

void changeLight()
 {
     if (isLocalPlayer)
     {
         if (level.waveCounter == 1)
         {
             lightAmout = 0.03f;
             light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
         }
         else
         {
             lightAmout = 1f;
             light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
         }
     }
     else{
         // If not a local player, simply update to the new light intensity.
         light.intensity = Mathf.Lerp(light.intensity, lightAmout, fadeTime * Time.deltaTime);
     }
 }