问:
DynamoDB Array of String becomes Array of Objects
I insert an array of string to DynamoDB:

```<code>[13, 12, 12, 4]
</code>```

It becomes Array of Objects when I view it in DynamoDB:

```<code>[ { "S" : "13" }, { "S" : "12" }, { "S" : "12" }, { "S" : "4" }]
</code>```

Is it reasonable? Do I need to do something to make my data being inserted as array of string?

Here is how I put my array to DynamoDB:

```<code>var params = {
   TableName: "MatchDate",
   Item:{
      position: [1, 3, 4, 5]
   }
};

DynamoDBClient.put(params, function(err, data) {
   //Some other code
});
</code>```

答:
If you want a single object (an array of strings) you need to set your attribute type to String Set

Then you will get

```<code>"SS": ["13", "12" ,"12", "4"]
</code>```

Or you can use Number Set

```<code>"NS": ["13", "12" ,"12", "4"]
</code>```

EDIT: Try something like this in nodejs

```<code>var params = {
   TableName: "MatchDate",
   Item: {
   "position": {
      SS: [
         '12',
         '13',
         '4'
      ]
   }
};

DynamoDBClient.put(params, function(err, data) {
   //Some other code
});
</code>```

Check here for AWS Refernce of Javascript putItem

Body:
I insert an array of string to DynamoDB:

[13, 12, 12, 4]

It becomes Array of Objects when I view it in DynamoDB:

[ { "S" : "13" }, { "S" : "12" }, { "S" : "12" }, { "S" : "4" }]

Is it reasonable? Do I need to do something to make my data being inserted as array of string?

Here is how I put my array to DynamoDB:

var params = {
   TableName: "MatchDate",
   Item:{
      position: [1, 3, 4, 5]
   }
};

DynamoDBClient.put(params, function(err, data) {
   //Some other code
});

Body:
If you want a single object (an array of strings) you need to set your attribute type to String Set

Then you will get

"SS": ["13", "12" ,"12", "4"]

Or you can use Number Set

"NS": ["13", "12" ,"12", "4"]

EDIT: Try something like this in nodejs

var params = {
   TableName: "MatchDate",
   Item: {
   "position": {
      SS: [
         '12',
         '13',
         '4'
      ]
   }
};

DynamoDBClient.put(params, function(err, data) {
   //Some other code
});

Check here for AWS Refernce of Javascript putItem


来源: stackexchange

问:
how to query child objects in mongodb
I'm new to mongodb and am trying to query child objects. I have a collection of States, and each State has child Cities. One of the Cities has a Name property that is null, which is causing errors in my app. How would I query the State collections to find child Cities that have a name == null?</p>

答:
If it is exactly null (as opposed to not set):

```<code>db.states.find({"cities.name": null})
</code>```

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

```<code>db.states.find({"cities.name": {"$exists": false}})
</code>```

I've tested the above with a collection created with these two inserts:

```<code>db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
</code>```

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

```<code>db.states.find({"$or": [
  {"cities.name": null},
  {"cities.name": {"$exists": false}}
]})
</code>```

ContentLicense: CC BY-SA 2.5

Title: how to query child objects in mongodb

Body:
If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null})

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}})

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [
  {"cities.name": null},
  {"cities.name": {"$exists": false}}
]})


问:
Python: IF doesn't work in SQLITE3
When I create the DataBase CURRENT_users.db:

```<code>    import sqlite3

conn = sqlite3.connect('CURRENT_users.db')

cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
          id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          nome TEXT NOT NULL,
          email TEXT NOT NULL,
          created_in DATE NOT NULL,
          password TEXT NOT NULL

)
""")

print("Success! DATABASE created with success!")

conn.close()

import UserLoginUI_Part2_Tes
</code>```

t1

And I insert the DATA:

```<code>    import sqlite3

conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()

cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon@Outlook.com", 2005-4-21, "Plugxyvj9");
""")

conn.commit()

print("A new user has been incremented! Now,have fun!!!")

conn.close()

import UserInterface
</code>```

In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!

```<code>    import sqlite3

conn = sqlite3.connect("CURRENT_users.db")

cursor = conn.cursor()

user_INFO = cursor.execute(""" SELECT nome FROM users; """)

user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))

logged_in = False;

if user_in_SCRIPT == user_INFO:
      print("You are logged in! Enjoy your new account...")
      logged_in = True;

else:
      print("Error: Not a valid user or USERNAME!!")
      conn.close()
</code>```

And it ever shows me the ELSE "command block"..

Please,who can help me?

Thanks for everything...

PRINT OF THE ERROR:

答:
You've called SQL SELECT but you need to fetch the data.

```<code>cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
</code>```

This would return a tuple, so to get the string inside, take the zero index:

```<code>if user_in_SCRIPT == user_INFO[0]:
    print("You are logged in! Enjoy your new account...")
    logged_in = True
</code>```

BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)

ContentLicense: CC BY-SA 3.0

Title: Python: IF doesn't work in SQLITE3

Body:
When I create the DataBase CURRENT_users.db:

    import sqlite3

conn = sqlite3.connect('CURRENT_users.db')

cursor = conn.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
          id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          nome TEXT NOT NULL,
          email TEXT NOT NULL,
          created_in DATE NOT NULL,
          password TEXT NOT NULL

)
""")

print("Success! DATABASE created with success!")

conn.close()

import UserLoginUI_Part2_Tes

t1

And I insert the DATA:

    import sqlite3

conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()

cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon@Outlook.com", 2005-4-21, "Plugxyvj9");
""")

conn.commit()

print("A new user has been incremented! Now,have fun!!!")

conn.close()

import UserInterface

In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!

    import sqlite3

conn = sqlite3.connect("CURRENT_users.db")

cursor = conn.cursor()

user_INFO = cursor.execute(""" SELECT nome FROM users; """)

user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))

logged_in = False;

if user_in_SCRIPT == user_INFO:
      print("You are logged in! Enjoy your new account...")
      logged_in = True;

else:
      print("Error: Not a valid user or USERNAME!!")
      conn.close()

And it ever shows me the ELSE "command block"..

Please,who can help me?

Thanks for everything...

PRINT OF THE ERROR:

Body:
You've called SQL SELECT but you need to fetch the data.

cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()

This would return a tuple, so to get the string inside, take the zero index:

if user_in_SCRIPT == user_INFO[0]:
    print("You are logged in! Enjoy your new account...")
    logged_in = True

BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)


问:
actionmailer not sending emails even after setting all the possible configurations
This is the method inside ApplicationMailer

```<code>class CancelTrip < ApplicationMailer
    default from: 'xyz@gmail.com'

    def cancel_trip
        @recvr= "ssdd@gmail.com"
        mail(to: @recvr, subject: 'Your trip has been cancelled as per your request' )
    end
end
</code>```

And the environmental variables as follows:

```<code>SMTP_ADDRESS: 'smtp.gmail.com'
SMTP_PORT: 587
SMTP_DOMAIN: 'localhost:3000'
SMTP_USERNAME: 'xyz@gmail.com'
SMTP_PASSWORD: 'gggh2354'
</code>```

And I am call the mailer method in my controller as follows:

```<code>def cancel
   xxxxx
   CancelTrip.cancel_trip.deliver_now
end
</code>```

developement.rb has following

```<code>config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = {host: 'localhost', port:3000}
config.action_mailer.perform_deliveries = true
</code>```

Log shows the email being sent. But I dont see any email in inbox.
My rails version is 4.2.6.

答: One possibility may be your firewall not allows to send email. Try connect different network.</p>

Body:
This is the method inside ApplicationMailer

class CancelTrip < ApplicationMailer
    default from: 'xyz@gmail.com'

    def cancel_trip
        @recvr= "ssdd@gmail.com"
        mail(to: @recvr, subject: 'Your trip has been cancelled as per your request' )
    end
end

And the environmental variables as follows:

SMTP_ADDRESS: 'smtp.gmail.com'
SMTP_PORT: 587
SMTP_DOMAIN: 'localhost:3000'
SMTP_USERNAME: 'xyz@gmail.com'
SMTP_PASSWORD: 'gggh2354'

And I am call the mailer method in my controller as follows:

def cancel
   xxxxx
   CancelTrip.cancel_trip.deliver_now
end

developement.rb has following

config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = {host: 'localhost', port:3000}
config.action_mailer.perform_deliveries = true

Log shows the email being sent. But I dont see any email in inbox.
My rails version is 4.2.6.


问:
Determine if iOS device is 32- or 64-bit
Does anyone know of an easy way to tell if an iOS7 device has 32- or 64-bit hardware? I don't mean programmatically, I just mean via settings, model number, 3rd-party app, etc.

I'm having a problem that I suspect is 64-bit related. Apple's advice is to test on the 64-bit simulator but also on an actual 64-bit device, but then doesn't say anything about how to determine that. I can write a test app to check sizeof(int) or whatever, but there's got to be some way for, say, tech support to know what they're working with.

Eric

答:
In runtime you can use something like this</p>

```<code>extension UIDevice {
    static let is64Bit = MemoryLayout<Int>.size == MemoryLayout<Int64>.size
}
</code>```

Body:
In runtime you can use something like this

extension UIDevice {
    static let is64Bit = MemoryLayout<Int>.size == MemoryLayout<Int64>.size
}


问:
How to get Header Text and Detail text from Firemonkey TListView by Header textGlyphButton on ItemClickEx Event?
On my TListView on FireMonkey having the Header appearence as "Custom", I need to get the header´s item text and detail text, on the TListview.ItemExClick event, when user click on the Header´s TListItemTextButton.

I have something like this...

```<code>   procedure TForm1.lv1ItemClickEx(const Sender: TObject; ItemIndex:
    Integer;
      const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
   begin
     if ItemObject is TListItemTextButton then
     begin
       if TListItemTextButton(ItemObject).Text = '-' then
       begin
         TListItemTextButton(ItemObject).Text := '+';
         //Do something with header´s text
       end
       else if TListItemTextButton(ItemObject).Text = '+' then
       begin
         TListItemTextButton(ItemObject).Text := '-';
         //Do something with header´s text
       end;
     end;
    end;
</code>```

Any clues?
Thanx in advance.

答:
Event OnItemCkick doesn´t work for the header.
So, the easyest way, is to use a TTextButton insted.</p>

Body:
On my TListView on FireMonkey having the Header appearence as "Custom", I need to get the header´s item text and detail text, on the TListview.ItemExClick event, when user click on the Header´s TListItemTextButton.

I have something like this...

   procedure TForm1.lv1ItemClickEx(const Sender: TObject; ItemIndex:
    Integer;
      const LocalClickPos: TPointF; const ItemObject: TListItemDrawable);
   begin
     if ItemObject is TListItemTextButton then
     begin
       if TListItemTextButton(ItemObject).Text = '-' then
       begin
         TListItemTextButton(ItemObject).Text := '+';
         //Do something with header´s text
       end
       else if TListItemTextButton(ItemObject).Text = '+' then
       begin
         TListItemTextButton(ItemObject).Text := '-';
         //Do something with header´s text
       end;
     end;
    end;

Any clues?
Thanx in advance.


问:
How do I write a route that allows for underscores in ASP.NET MVC?
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

```<code>01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }
</code>```

You implement a controller named HomeController that includes methods with the following
signatures.

```<code>public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)
</code>```

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );
</code>```

B. Replace line 05 with the following code segment.

```<code>routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );
</code>```

C. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );
</code>```

D. At line 04, add the following code segment.

```<code>routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );
</code>```

答:
When an ASP.NET MVC route looks for an action to map to, it takes several things into account:

The action name (Non-case sensitive)

The parameter names (non-case sensitive)

Whether or not the constraints are matched on the route.

Because of that, if you want a route that matches the criteria you listed, this route would be the correct answer:

```<code>routes.MapRoute(
    "Details by Username",
    "{username}",
    new { controller = "Home", action = "DetailsByUsername" },
    new { username = @"\w{3,20}" }
);
</code>```

A URL with this structure would match that route for the following reasons:

```<code>http://example.com/my_user_name
</code>```

The action name matches,

It's looking for a parameter in the action called 'username', and

The criteria for non-alphanumeric characters is met.

C is the correct answer as it adds to the current routes.

Answer B replaces the existing route definition, thus preventing the default routing to the Home controller Index action.

Body:
I received the following problem on the MCTS exam. The book says the answer is C, but I thought B would be the correct answer. Why is it C?

You create a new ASP.NET MVC 2 Web application. The following default routes are created in
the Global.asax.cs file. (Line numbers are included for reference only.)

01 public static void RegisterRoutes(RouteCollection routes)
02 {
03 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
04
05 routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } );
06 }

You implement a controller named HomeController that includes methods with the following
signatures.

public ActionResult Index()
public ActionResult Details(int id)
public ActionResult DetailsByUsername(string username)

You need to add a route to meet the following requirements:

The details for a user must to be displayed when a user name is entered as the path by invoking the DetailsByUsername action.

User names can contain alphanumeric characters and underscores, and can be between 3 and 20 characters long. What should you do?

A. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "DetailsByUsername", id = "" } );

B. Replace line 05 with the following code segment.

routes.MapRoute( "Default", "{controller}/{action}/{username}", new { controller = "Home", action = "DetailsByUsername", username = "" }, new { username = @"\w{3,20}" } );

C. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{username}", new { controller = "Home", action = "DetailsByUsername" }, new { username = @"\w{3,20}" } );

D. At line 04, add the following code segment.

routes.MapRoute( "Details by Username", "{id}", new { controller = "Home", action = "DetailsByUsername" }, new { id = @"\w{3,20}" } );

Body:
When an ASP.NET MVC route looks for an action to map to, it takes several things into account:

The action name (Non-case sensitive)

The parameter names (non-case sensitive)

Whether or not the constraints are matched on the route.

Because of that, if you want a route that matches the criteria you listed, this route would be the correct answer:

routes.MapRoute(
    "Details by Username",
    "{username}",
    new { controller = "Home", action = "DetailsByUsername" },
    new { username = @"\w{3,20}" }
);

A URL with this structure would match that route for the following reasons:

http://example.com/my_user_name

The action name matches,

It's looking for a parameter in the action called 'username', and

The criteria for non-alphanumeric characters is met.

C is the correct answer as it adds to the current routes.

Answer B replaces the existing route definition, thus preventing the default routing to the Home controller Index action.


问:
How to convert python(.py) file to unreadable code format
I have written python code and saved as program.py file.Now When i open "program.py" file it should be unreadable format.

Can anyone suggest me how to fix this issue.

答:
One way to do that is by compiling the source code using the py_compile module:

```<code>python -m py_compile my-py-source.py
</code>```

The compiled source code will be in _pycache/my-py-source.pyc (relative to your current directory). And the code will still run normally when you run python my-py-source.pyc.

Body:
One way to do that is by compiling the source code using the py_compile module:

python -m py_compile my-py-source.py

The compiled source code will be in _pycache/my-py-source.pyc (relative to your current directory). And the code will still run normally when you run python my-py-source.pyc.


问:
Error deploying Rails 4 App to Heroku redis
I have like a year deploying my rails app in heroku without problem but recently when I try to push the app it just crashes. I tested it using heroku local and it works but on heroku it doesnt.

I didn't change anything on the conf files it just suddenly do not work on heroku

```<code>Starting process with command `bundle exec puma -C config/puma.rb`
[4] Puma starting in cluster mode...
[4] * Version 3.11.0 (ruby 2.3.1-p112), codename: Love Song
[4] * Min threads: 2, max threads: 2
[4] * Environment: production
[4] * Process workers: 1
[4] * Preloading application
[4] ! Unable to load application: Redis::CannotConnectError: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)
bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
Redis::CannotConnectError: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:344:in `rescue in establish_connection'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:329:in `establish_connection'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:99:in `block in connect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:291:in `with_reconnect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:98:in `connect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:363:in `ensure_connected'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:219:in `block in process'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:304:in `logging'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:218:in `process'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:118:in `call'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:1423:in `block in smembers'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:45:in `block in synchronize'
   /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:45:in `synchronize'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:1422:in `smembers'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:442:in `call_with_namespace'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:328:in `method_missing'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque/data_store.rb:236:in `worker_ids'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque/worker.rb:72:in `all'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque.rb:464:in `workers'
   /app/config/application.rb:44:in `<class:Application>'
   /app/config/application.rb:13:in `<module:Truckbu>'
   /app/config/application.rb:12:in `<top (required)>'
   /app/config/environment.rb:2:in `require'
   /app/config/environment.rb:2:in `<top (required)>'
   config.ru:3:in `require'
   config.ru:3:in `block in <main>'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:55:in `instance_eval'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:55:in `initialize'
   config.ru:in `new'
   config.ru:in `<main>'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:49:in `eval'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:49:in `new_from_string'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:40:in `parse_file'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/configuration.rb:318:in `load_rackup'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/configuration.rb:243:in `app'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/runner.rb:138:in `load_and_bind'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/cluster.rb:397:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/launcher.rb:183:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/cli.rb:77:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/bin/puma:10:in `<top (required)>'
  /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `load'
  /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `<top (required)>'
 State changed from starting to crashed
 Process exited with status 1
</code>```

The redis url is set in ENV as usual.

答: I finally could find the problem and it was that the project is configured to work with Redis 3.3.5. They updated the gem and then the configuration changed. I solved it by setting the gem version that work with the current configuration in the Gemfile.</p>

Body:
I have like a year deploying my rails app in heroku without problem but recently when I try to push the app it just crashes. I tested it using heroku local and it works but on heroku it doesnt.

I didn't change anything on the conf files it just suddenly do not work on heroku

Starting process with command `bundle exec puma -C config/puma.rb`
[4] Puma starting in cluster mode...
[4] * Version 3.11.0 (ruby 2.3.1-p112), codename: Love Song
[4] * Min threads: 2, max threads: 2
[4] * Environment: production
[4] * Process workers: 1
[4] * Preloading application
[4] ! Unable to load application: Redis::CannotConnectError: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)
bundler: failed to load command: puma (/app/vendor/bundle/ruby/2.3.0/bin/puma)
Redis::CannotConnectError: Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:344:in `rescue in establish_connection'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:329:in `establish_connection'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:99:in `block in connect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:291:in `with_reconnect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:98:in `connect'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:363:in `ensure_connected'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:219:in `block in process'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:304:in `logging'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:218:in `process'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis/client.rb:118:in `call'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:1423:in `block in smembers'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:45:in `block in synchronize'
   /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:45:in `synchronize'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-4.0.1/lib/redis.rb:1422:in `smembers'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:442:in `call_with_namespace'
   /app/vendor/bundle/ruby/2.3.0/gems/redis-namespace-1.6.0/lib/redis/namespace.rb:328:in `method_missing'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque/data_store.rb:236:in `worker_ids'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque/worker.rb:72:in `all'
   /app/vendor/bundle/ruby/2.3.0/gems/resque-1.27.4/lib/resque.rb:464:in `workers'
   /app/config/application.rb:44:in `<class:Application>'
   /app/config/application.rb:13:in `<module:Truckbu>'
   /app/config/application.rb:12:in `<top (required)>'
   /app/config/environment.rb:2:in `require'
   /app/config/environment.rb:2:in `<top (required)>'
   config.ru:3:in `require'
   config.ru:3:in `block in '
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:55:in `instance_eval'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:55:in `initialize'
   config.ru:in `new'
   config.ru:in `'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:49:in `eval'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:49:in `new_from_string'
   /app/vendor/bundle/ruby/2.3.0/gems/rack-1.6.8/lib/rack/builder.rb:40:in `parse_file'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/configuration.rb:318:in `load_rackup'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/configuration.rb:243:in `app'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/runner.rb:138:in `load_and_bind'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/cluster.rb:397:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/launcher.rb:183:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/lib/puma/cli.rb:77:in `run'
   /app/vendor/bundle/ruby/2.3.0/gems/puma-3.11.0/bin/puma:10:in `<top (required)>'
  /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `load'
  /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `<top (required)>'
 State changed from starting to crashed
 Process exited with status 1

The redis url is set in ENV as usual.


问:
Flower doesn't show task events
Here I find how to send event to Flower. Next, I try to use it in my code like in github issue. My version:

```<code>@celery.task()
def add():
    try:
        ...
    except Exception as exc:
        add.send_event('task-failed', exception=str(exc))
</code>```

In case of error, Flower receives information about failed task:

Flower's dashboard

But when I try to click and find extra inforamtion about it, I see:

Information about failed tasks

How should I use send_event ?

答:
Possible solution:

send_event uses task.request.id to publish event into Flower. If replace this id to another, in Flower will be two records about one task. But need to use different ids for these records. Example of function:

```<code>def send_to_flower(task, event, **kwargs):
    task.request.id = str(uuid4())
    task.send_event(event, **kwargs)
</code>```

Title: Flower doesn't show task events

Body:
Here I find how to send event to Flower. Next, I try to use it in my code like in github issue. My version:

@celery.task()
def add():
    try:
        ...
    except Exception as exc:
        add.send_event('task-failed', exception=str(exc))

In case of error, Flower receives information about failed task:

Flower's dashboard

But when I try to click and find extra inforamtion about it, I see:

Information about failed tasks

How should I use send_event ?

Body:
Possible solution:

send_event uses task.request.id to publish event into Flower. If replace this id to another, in Flower will be two records about one task. But need to use different ids for these records. Example of function:

def send_to_flower(task, event, **kwargs):
    task.request.id = str(uuid4())
    task.send_event(event, **kwargs)


问:
Reduce config tables:SymmetricDS
Well i'm trying to migrate data from my in-memory DB1 to my DB2. For this I'm using SymmetricDS configured in such a way that, when SymmetricDS starts, it will perform an inital load from DB1 to DB2. Furthermore whenever some data modification occurs in DB1, the same is pulled to DB2.

Now this is where i have a problem. SymmetricDS requires configuration tables or Sym Tables to be present at both the DB1 side and DB2 side.

Since my DB1 is in-memory, these configuration tables are taking a lot of memory.

So what I would like to know is whether there is a way ,to keep the configuration tables entirely in a seperate on-disk db, from DB1 side, and yet retain the existing functionality?

Hope i was able to make myself clear.

Any and all suggestions would be appreciated.

答:
Low hanging fruit would be to decrease the purge period, i.e. decrease the parameter job.purge.period.time.ms from five days (in seconds -- 7200000) to few hours. SymmetricDs would clean all successfully synchronized outgoing batches (sym_outgoin_batch) and associated extracted data (sym_data) more often keeping the memory footprint lower.

SymmetricDs allows keeping its tables in another catalog and/or schema which doesn't really solve your problem.

Title: Reduce config tables:SymmetricDS


问:
The jQuery Metadata Plugin is deprecated. What is the alternative?
I read at http://blog.jquery.com/2011/04/16/official-plugins-a-change-in-the-roadmap/ the following announcement:

The Metadata plugin will be deprecated, in favor of similar functionality provided by jQuery 1.4.3 and above.

What is the

similar functionality

that jQuery provides as an alternative from version 1.4.3 and on?

答: I upgraded to the latest version of jQuery available but kept this deprecated Metadata plugin in my code. I removed the jQuery Migrate plugin from my code and everything works correctly, meaning that even though the Metadata plugin is officially deprecated, it does not use jQuery code or methods that are incompatible with the latest version of jQuery.</p>


问:
Database table relationships with 3 entities
I have three entities in our environment, Account, User and Company. Right now I have tables for account, account_user, account_company, company and user. It seemed fine initially but now that I think about it, it seems like it could be simplified with the joining tables.

Every Account (portfolio) has 1 or more Companies and 1 or more User managing it

User Joe Doe logs in to view Account Joe's Accounts with company(s) Joe's Company &&/|| Joe's Wife's Company

How would it be in Logical Design (designing database tables and relationships)?

Hope I described this clearly
Thank you

答:
This kind of schema might be of help to you.

Table Company :

Company ID NAME DESCRIPTION ETC

Table Account:

Account ID NAME DESCRIPTION ETC, Associated Company ID(foreign key)

Table User:

User Details

Table User_Permissions:

Users allowed on accounts

If you need one account to be part of multiple companies(which should not be the case) then you can make a bridge table for the account and companies too like for user permissions.


问:
Possible JQuery functions to use
I am currently working on a website which has a fixed header and body and within the body is a main DIV.

For the page to change, the contents of the main DIV is changed. (Not my development)

I would like to display a notice to the user (Please wait loading) for any DB requests to the server or if the page changes. (The contents of the main DIV is changed for this to occur). Once the results from the DB has been returned or the main DIV has completed loading, I would like for the notice to be removed.

I am considering using JQuery to achieve this, by having a loader DIV within the body and for this to be visible when required and hidden when not.

What would be the best JQuery function to use to achieve my requirements?

There is no AJAX used on the site.

Many thanks

答:
This is my all favorite bookmark on how to create a jQuery ajax webpage:

http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp

Title: Possible JQuery functions to use


问:
AEM Dispatcher configuration
Happend to see an interesting presentation in Slide Share on AEM Dispatcher. I'm new to to Dispatcher configuration. I have doubt on one of the slides which shows a generic deployment architecture :

This Slide shows an one-to-one relationship between publish and dispatchers ie. one specific dispatcher is associated with a specific publisher only. Is this figure represents a real use case? Is it possible for a particular dispatcher to cache content from more than one publisher?

答:
Dispatcher can be used as a

1, load balancing (configure one dispatcher with multiple publish instances) or
2, one to one mapping (one dispatcher with single publisher).

Caching is possible in both the setups.

We use option 2 when we go for automation of tasks(Zero down time deployment).

Title: AEM Dispatcher configuration


问:
return multiple elements in array.map / Subcategories in dropdown
I'm using array.map to loop through a nested array.
indicatorCategories is my first array which contains a name and id, and an nested array named indicators.

I'm mapping these indicators to a dropdown in react-bootstrap, but I also have to map the name of the category.

Currently this is the code I have.

```<code>{indicatorCategories.map(indicatorCategory => {
            return (
              (
                <option
                  disabled
                  key={indicatorCategory.id}
                  value={indicatorCategory.id}
                >
                  {"---" + indicatorCategory.name + "---"}
                </option>
              ),
              indicatorCategory.indicators.map(indicator => {
                return (
                  <option key={indicator.id} value={indicator.id}>
                    {indicator.name}
                  </option>
                );
              })
            );
          })}
</code>```

The result is that I'm only mapping the indicators, the indicatorCategories do not show up. I guess array.map isn't ment to return an element and map over a nested array? Or am I just making a stupid syntax error? Been wrestling with it for a while but no cigar.

If it's not possible, what are the alternatives here? I prefer not using some hover over categories to show the indicators from that category since it isn't very mobile friendly.

Thanks.

答:
You can do what you need to do with a combination of reduce and map. Here's an example with dummy data, you transfer it to react.

```<code>let data = [
    {
    id: 1,
    value: 'a',
    data: [
      {id: 11, value: 'b'}
    ]
  },
  {
    id: 2,
    value: 'aa',
    data: [
      {id: 12, value: 'bb'},
      {id: 12, value: 'bb'},
    ]
  }
]

let results = data.reduce((acc, cur) => {
    acc = acc.concat(cur.value);

  return acc.concat(
    cur.data.map((nested) => {
        return nested.value;
    })
  )
}, []);

console.log(results)
</code>```

https://jsfiddle.net/avLvxsb6/

As you can see in results you have all the values from the array and the nested arrays. Another alternative is to map the data and then flatten the results so you don't have nested arrays. Then you loop through that and render

Body:
I'm using array.map to loop through a nested array.
indicatorCategories is my first array which contains a name and id, and an nested array named indicators.

I'm mapping these indicators to a dropdown in react-bootstrap, but I also have to map the name of the category.

Currently this is the code I have.

{indicatorCategories.map(indicatorCategory => {
            return (
              (
                <option
                  disabled
                  key={indicatorCategory.id}
                  value={indicatorCategory.id}
                >
                  {"---" + indicatorCategory.name + "---"}
                </option>
              ),
              indicatorCategory.indicators.map(indicator => {
                return (
                  <option key={indicator.id} value={indicator.id}>
                    {indicator.name}
                  </option>
                );
              })
            );
          })}

The result is that I'm only mapping the indicators, the indicatorCategories do not show up. I guess array.map isn't ment to return an element and map over a nested array? Or am I just making a stupid syntax error? Been wrestling with it for a while but no cigar.

If it's not possible, what are the alternatives here? I prefer not using some hover over categories to show the indicators from that category since it isn't very mobile friendly.

Thanks.

Body:
You can do what you need to do with a combination of reduce and map. Here's an example with dummy data, you transfer it to react.

let data = [
    {
    id: 1,
    value: 'a',
    data: [
      {id: 11, value: 'b'}
    ]
  },
  {
    id: 2,
    value: 'aa',
    data: [
      {id: 12, value: 'bb'},
      {id: 12, value: 'bb'},
    ]
  }
]

let results = data.reduce((acc, cur) => {
    acc = acc.concat(cur.value);

  return acc.concat(
    cur.data.map((nested) => {
        return nested.value;
    })
  )
}, []);

console.log(results)

https://jsfiddle.net/avLvxsb6/

As you can see in results you have all the values from the array and the nested arrays. Another alternative is to map the data and then flatten the results so you don't have nested arrays. Then you loop through that and render


问:
Scraping a website to download all documents on it with BeautifulSoup throws IOError

Hi, I would like to download all the files that are published on the following website (https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer) via a Python, Julia or whatever language script. It used to be a http website where BeautifulSoup was working fine; it is now a https website on my code is unfortunately not working anymore.

All the files I desire to download are in a 'a' tag and are of class 'download'. Hence the line in the code that is not working is the following:

```<code>fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)
</code>```

which raises the following error:

```<code>raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 403, 'Forbidden', <httplib.HTTPMessage instance at 0x104f79e60>)
</code>```

After some research on the net, I have not been able to find any  information on how I could scrap the document on an https website, would anyone have a suggestion?

Thank you in advance for your answers!

Julien

```<code>import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-
operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):
  document_name = document["title"]
  document_url = mainLocation+document["href"]
  fileDownloader.retrieve(document_url, "files/"+document_name)
</code>```

答:
The problem with the issue is that you should pass the agent as a header in order the request to be fulfilled.

I don't know how to do it with urllib but since you are already using requests (which is more human friendly) you can achieve this with the following code:

```<code>import requests
import urllib

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

mainLocation = "http://www2.nationalgrid.com"
header = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'
}

for a_link in soup.find_all('a', class_='download'):
    document_name = a_link["title"]
    document_url = mainLocation + a_link["href"]
    print('Getting file: {}'.format(document_url))
    page = requests.get(document_url, headers=header)
    file_to_store = a_link.get('href').split('/')[-1]
    with open('files/' + file_to_store, 'w') as f_out:
        f_out.write(page.content)
</code>```

Only with a small hack to retrieve the file name from the link.

ContentLicense: CC BY-SA 4.0

Body:
Hi, I would like to download all the files that are published on the following website (https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer) via a Python, Julia or whatever language script. It used to be a http website where BeautifulSoup was working fine; it is now a https website on my code is unfortunately not working anymore.

All the files I desire to download are in a 'a' tag and are of class 'download'. Hence the line in the code that is not working is the following:

fileDownloader.retrieve(document_url, "forecasted-demand-files/"+document_name)

which raises the following error:

raise IOError, ('http error', errcode, errmsg, headers)
IOError: ('http error', 403, 'Forbidden', <httplib.HTTPMessage instance at 0x104f79e60>)

After some research on the net, I have not been able to find any  information on how I could scrap the document on an https website, would anyone have a suggestion?

Thank you in advance for your answers!

Julien

import requests
import urllib
import re

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-
operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

fileDownloader = urllib.URLopener()
mainLocation = "https://www.nationalgrid.com"

for document in soup.find_all('a', class_='download'):
  document_name = document["title"]
  document_url = mainLocation+document["href"]
  fileDownloader.retrieve(document_url, "files/"+document_name)

Body:
The problem with the issue is that you should pass the agent as a header in order the request to be fulfilled.

I don't know how to do it with urllib but since you are already using requests (which is more human friendly) you can achieve this with the following code:

import requests
import urllib

from bs4 import BeautifulSoup

page = requests.get("https://www.nationalgrid.com/uk/electricity/market-and-operational-data/data-explorer")
soup = BeautifulSoup(page.content, 'html.parser')

mainLocation = "http://www2.nationalgrid.com"
header = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'
}

for a_link in soup.find_all('a', class_='download'):
    document_name = a_link["title"]
    document_url = mainLocation + a_link["href"]
    print('Getting file: {}'.format(document_url))
    page = requests.get(document_url, headers=header)
    file_to_store = a_link.get('href').split('/')[-1]
    with open('files/' + file_to_store, 'w') as f_out:
        f_out.write(page.content)

Only with a small hack to retrieve the file name from the link.


问:
Loop through elements with matching data attribute values
I have the following setup:

    $( document ).on( 'click touch', '.target', function() {
        if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
           alert('do stuff');
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
</div></code>```

Whenever user clicks on .target element, I want to do stuff to all divs within the closest .list. So if user clicks on .target with post-id data value 1,  it should so something to all others with the same data attribute value...

How do I do this type of loop with jQuery?

答:
There are more ways how to achieve the result.

I've add removing classname from previous run, it puts a red color to just last selected items.

$( document ).on( 'click touch', '.target', function() {
    var postID = $(this).data("post-id");

    $('.red').removeClass('red');

    $('.target').each(function() {
        var el = $(this);

        if (el.data('post-id') == postID) {
            el.addClass('red');
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {background: red}</code>```

a

b

a

a

b

```

Body:
I have the following setup:

    $( document ).on( 'click touch', '.target', function() {
        if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
           alert('do stuff');
        }
    });

a

b

a

a

b

Whenever user clicks on .target element, I want to do stuff to all divs within the closest .list. So if user clicks on .target with post-id data value 1,  it should so something to all others with the same data attribute value...

How do I do this type of loop with jQuery?

Body:
There are more ways how to achieve the result.

I've add removing classname from previous run, it puts a red color to just last selected items.

$( document ).on( 'click touch', '.target', function() {
    var postID = $(this).data("post-id");

    $('.red').removeClass('red');

    $('.target').each(function() {
        var el = $(this);

        if (el.data('post-id') == postID) {
            el.addClass('red');
        }
    });
});

.red {background: red}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
</div>


问:
R - rotating a difficult data frame
Suppose I've got sales data for three sales reps selling a variety of products. What makes it difficult is that each rep sells a different combination of products, and not necessarily the same number of them, either:

Bob sells Products A, B, and C

Mike sells Products A, B, C, and D

Sara sells Products A, B, and E

```<code>   RepName Product SalesDollarAmt SalesQty
 1     Bob       A             43        3
 2    Mike       A             14        5
 3    Sara       A             53        1
 4     Bob       B            100       35
 5    Mike       B            215       80
 6    Sara       B            310      105
 7     Bob       C              5        8
 8    Mike       C             10        3
 9    Mike       D            105       50
10    Sara       E             25       18
</code>```

I want to rotate this on the Product, so that the result looks like this:

```<code>  RepName Product.1 SalesDollarAmt.1 SalesQty.1 Product.2 SalesDollarAmt.2 SalesQty.2 Product.3 SalesDollarAmt.3 SalesQty.3 Product.4 SalesDollarAmt.4 SalesQty.4
1     Bob         A               43          3         B              100         35         C                5          8      <NA>                0          0
2    Mike         A               14          5         B              215         80         C               10          3         D              105         50
3    Sara         A               53          1         B              310        105         E               25         18      <NA>                0          0
</code>```

If they all had the same products, I'd have filtered them by Product into separate dataframes and then joined them back together on RepName. I've tried everything I can think of with spread and dcast. Thanks for any help!

Code for sample data frames:

```<code>library(tidyverse)

# initial sales data
df <- tribble(
  ~RepName, ~Product, ~SalesDollarAmt, ~SalesQty,
               #-------------------------------
               "Bob", "A", 43, 3,
               "Mike", "A", 14, 5,
               "Sara", "A", 53, 1,
               "Bob", "B", 100, 35,
               "Mike", "B", 215, 80,
               "Sara", "B", 310, 105,
               "Bob", "C", 5, 8,
               "Mike", "C", 10, 3,
               "Mike", "D", 105, 50,
               "Sara", "E", 25, 18
                )

# ideally rotated data
df2 <- tribble(
  ~RepName, ~Product.1, ~SalesDollarAmt.1, ~SalesQty.1, ~Product.2, ~SalesDollarAmt.2, ~SalesQty.2, ~Product.3, ~SalesDollarAmt.3, ~SalesQty.3, ~Product.4, ~SalesDollarAmt.4, ~SalesQty.4,
  #--------------------------------------------------------------
  "Bob", "A", 43, 3, "B", 100, 35, "C", 5, 8, NA, 0, 0,
  "Mike", "A", 14, 5, "B", 215, 80, "C", 10, 3, "D", 105, 50,
  "Sara", "A", 53, 1, "B", 310, 105, "E", 25, 18, NA, 0, 0
)
</code>```

答:
The question is tagged with dcast, so I feel obliged to post a solution which uses dcast().

The data.table version of dcast() can reshape multiple value columns simultaneously which is exactly what we need here. In addition, the rowid() function is used to fill the columns individually for each RepName:

```<code>library(data.table)
cast(setDT(df), RepName ~ rowid(RepName), value.var = c("Product", "SalesDollarAmt", "SalesQty"))
</code>```

```<code>   RepName Product_1 Product_2 Product_3 Product_4 SalesDollarAmt_1 SalesDollarAmt_2 SalesDollarAmt_3 SalesDollarAmt_4 SalesQty_1 SalesQty_2 SalesQty_3 SalesQty_4
1:     Bob         A         B         C        NA               43              100                5               NA          3         35          8         NA
2:    Mike         A         B         C         D               14              215               10              105          5         80          3         50
3:    Sara         A         B         E        NA               53              310               25               NA          1        105         18         NA
</code>```

Edit: Improved version with columns in requested order

In a comment, the OP has disclosed that the reshaping is required because the data will be further processed by an Excel macro. Usually, the position of columns is crucial for Excel formulae.

Therefore the variant below is reordering the columns so that all columns which belong to one product are grouped together:

```<code>library(data.table)
# value columns
val <- c("Product", "SalesDollarAmt", "SalesQty")
# create vector of column names in the expected order
col_order <- setDT(df)[, .N, by = RepName][, CJ(seq_len(max(N)), val)][, paste(V2, V1, sep = "_")]
dcast(df, RepName ~ rowid(RepName), value.var = val)[
  #re-order columns in place, i.e., without copying
  , setcolorder(.SD, c("RepName", col_order))]
</code>```

```<code>   RepName Product_1 SalesDollarAmt_1 SalesQty_1 Product_2 SalesDollarAmt_2 SalesQty_2 Product_3 SalesDollarAmt_3 SalesQty_3 Product_4 SalesDollarAmt_4 SalesQty_4
1:     Bob         A               43          3         B              100         35         C                5          8        NA               NA         NA
2:    Mike         A               14          5         B              215         80         C               10          3         D              105         50
3:    Sara         A               53          1         B              310        105         E               25         18        NA               NA         NA
</code>```

Title: R - rotating a difficult data frame

Body:
Suppose I've got sales data for three sales reps selling a variety of products. What makes it difficult is that each rep sells a different combination of products, and not necessarily the same number of them, either:

Bob sells Products A, B, and C

Mike sells Products A, B, C, and D

Sara sells Products A, B, and E

   RepName Product SalesDollarAmt SalesQty
 1     Bob       A             43        3
 2    Mike       A             14        5
 3    Sara       A             53        1
 4     Bob       B            100       35
 5    Mike       B            215       80
 6    Sara       B            310      105
 7     Bob       C              5        8
 8    Mike       C             10        3
 9    Mike       D            105       50
10    Sara       E             25       18

I want to rotate this on the Product, so that the result looks like this:

  RepName Product.1 SalesDollarAmt.1 SalesQty.1 Product.2 SalesDollarAmt.2 SalesQty.2 Product.3 SalesDollarAmt.3 SalesQty.3 Product.4 SalesDollarAmt.4 SalesQty.4
1     Bob         A               43          3         B              100         35         C                5          8      <NA>                0          0
2    Mike         A               14          5         B              215         80         C               10          3         D              105         50
3    Sara         A               53          1         B              310        105         E               25         18      <NA>                0          0

If they all had the same products, I'd have filtered them by Product into separate dataframes and then joined them back together on RepName. I've tried everything I can think of with spread and dcast. Thanks for any help!

Code for sample data frames:

library(tidyverse)

# initial sales data
df <- tribble(
  ~RepName, ~Product, ~SalesDollarAmt, ~SalesQty,
               #-------------------------------
               "Bob", "A", 43, 3,
               "Mike", "A", 14, 5,
               "Sara", "A", 53, 1,
               "Bob", "B", 100, 35,
               "Mike", "B", 215, 80,
               "Sara", "B", 310, 105,
               "Bob", "C", 5, 8,
               "Mike", "C", 10, 3,
               "Mike", "D", 105, 50,
               "Sara", "E", 25, 18
                )

# ideally rotated data
df2 <- tribble(
  ~RepName, ~Product.1, ~SalesDollarAmt.1, ~SalesQty.1, ~Product.2, ~SalesDollarAmt.2, ~SalesQty.2, ~Product.3, ~SalesDollarAmt.3, ~SalesQty.3, ~Product.4, ~SalesDollarAmt.4, ~SalesQty.4,
  #--------------------------------------------------------------
  "Bob", "A", 43, 3, "B", 100, 35, "C", 5, 8, NA, 0, 0,
  "Mike", "A", 14, 5, "B", 215, 80, "C", 10, 3, "D", 105, 50,
  "Sara", "A", 53, 1, "B", 310, 105, "E", 25, 18, NA, 0, 0
)

Body:
The question is tagged with dcast, so I feel obliged to post a solution which uses dcast().

The data.table version of dcast() can reshape multiple value columns simultaneously which is exactly what we need here. In addition, the rowid() function is used to fill the columns individually for each RepName:

library(data.table)
cast(setDT(df), RepName ~ rowid(RepName), value.var = c("Product", "SalesDollarAmt", "SalesQty"))

   RepName Product_1 Product_2 Product_3 Product_4 SalesDollarAmt_1 SalesDollarAmt_2 SalesDollarAmt_3 SalesDollarAmt_4 SalesQty_1 SalesQty_2 SalesQty_3 SalesQty_4
1:     Bob         A         B         C        NA               43              100                5               NA          3         35          8         NA
2:    Mike         A         B         C         D               14              215               10              105          5         80          3         50
3:    Sara         A         B         E        NA               53              310               25               NA          1        105         18         NA

Edit: Improved version with columns in requested order

In a comment, the OP has disclosed that the reshaping is required because the data will be further processed by an Excel macro. Usually, the position of columns is crucial for Excel formulae.

Therefore the variant below is reordering the columns so that all columns which belong to one product are grouped together:

library(data.table)
# value columns
val <- c("Product", "SalesDollarAmt", "SalesQty")
# create vector of column names in the expected order
col_order <- setDT(df)[, .N, by = RepName][, CJ(seq_len(max(N)), val)][, paste(V2, V1, sep = "_")]
dcast(df, RepName ~ rowid(RepName), value.var = val)[
  #re-order columns in place, i.e., without copying
  , setcolorder(.SD, c("RepName", col_order))]

   RepName Product_1 SalesDollarAmt_1 SalesQty_1 Product_2 SalesDollarAmt_2 SalesQty_2 Product_3 SalesDollarAmt_3 SalesQty_3 Product_4 SalesDollarAmt_4 SalesQty_4
1:     Bob         A               43          3         B              100         35         C                5          8        NA               NA         NA
2:    Mike         A               14          5         B              215         80         C               10          3         D              105         50
3:    Sara         A               53          1         B              310        105         E               25         18        NA               NA         NA


问:
scraping pagination with Python and Beautiful Soup
I am new in Python and also in Web scraping...

I am trying to select all the pages from this webpage

http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0

this is quite complicated: I saw the html code with "active first" and "next last.

I did a python code and it worked for 4 pages (page 2,3,4 and 11)

```<code>import requests
from bs4 import BeautifulSoup
url_pagination= "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0"
dept_page_Url=[]
r=requests.get(url_pagination)
soup = BeautifulSoup(r.content, "html.parser")
pagination= soup.find_all("ul",{"class":"pagination"})
if len(pagination) == 0 :
    dept_page_Url.append(url_pagination)
else:
    for page_url_list in pagination:
        for page_url in page_url_list.find_all("a"):
            dept_page_Url.append(root_url + page_url.get('href'))
print(dept_page_Url)
</code>```

In fact I know why I have just 4 pages, it is because I selected only the "Href" html code. But I don't know how to improve my code.

Any clue such as a webpage with some information to help me or some who know how to do it???

Thanks a lot

答:
The pagination gives only 4 links (pages 2-4 and the last page), so you can't get all the page links from the html document directly.

However you can get the number of pages from the last page and create all the pages with range.

```<code>import requests
from bs4 import BeautifulSoup

url_pagination= "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0"
r = requests.get(url_pagination)
soup = BeautifulSoup(r.content, "html.parser")

page_url = "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0?page={}"
last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
#last_page = soup.select_one('ul.pagination li.next a')['href'].split('=')[1] # with css selectors
dept_page_url = [page_url.format(i) for i in range(1, int(last_page)+1)]

print(dept_page_url)
</code>```

soup.find('ul', class_='pagination').find('li', class_='next').a['href'] finds the first 'ul.pagination', then 'li.next', then 'a', and selects 'href'.

The result is: '/annuaire-ehpad-en-hebergement-permanent/64/0?page=11'.

.split('=') splits the string by '=' in a list of 2 items and .split('=')[1] selects the 2nd item which is '11', so last_page = '11'.

range(1, int(last_page)+1) creates a range of numbers from 1 to 11.

page_url.format(i) formats those numbers in page_url, so dept_page_url contains 11 urls.

Body:
I am new in Python and also in Web scraping...

I am trying to select all the pages from this webpage

http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0

this is quite complicated: I saw the html code with "active first" and "next last.

I did a python code and it worked for 4 pages (page 2,3,4 and 11)

import requests
from bs4 import BeautifulSoup
url_pagination= "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0"
dept_page_Url=[]
r=requests.get(url_pagination)
soup = BeautifulSoup(r.content, "html.parser")
pagination= soup.find_all("ul",{"class":"pagination"})
if len(pagination) == 0 :
    dept_page_Url.append(url_pagination)
else:
    for page_url_list in pagination:
        for page_url in page_url_list.find_all("a"):
            dept_page_Url.append(root_url + page_url.get('href'))
print(dept_page_Url)

In fact I know why I have just 4 pages, it is because I selected only the "Href" html code. But I don't know how to improve my code.

Any clue such as a webpage with some information to help me or some who know how to do it???

Thanks a lot

Body:
The pagination gives only 4 links (pages 2-4 and the last page), so you can't get all the page links from the html document directly.

However you can get the number of pages from the last page and create all the pages with range.

import requests
from bs4 import BeautifulSoup

url_pagination= "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0"
r = requests.get(url_pagination)
soup = BeautifulSoup(r.content, "html.parser")

page_url = "http://www.pour-les-personnes-agees.gouv.fr/annuaire-ehpad-en-hebergement-permanent/64/0?page={}"
last_page = soup.find('ul', class_='pagination').find('li', class_='next').a['href'].split('=')[1]
#last_page = soup.select_one('ul.pagination li.next a')['href'].split('=')[1] # with css selectors
dept_page_url = [page_url.format(i) for i in range(1, int(last_page)+1)]

print(dept_page_url)

soup.find('ul', class_='pagination').find('li', class_='next').a['href'] finds the first 'ul.pagination', then 'li.next', then 'a', and selects 'href'.

The result is: '/annuaire-ehpad-en-hebergement-permanent/64/0?page=11'.

.split('=') splits the string by '=' in a list of 2 items and .split('=')[1] selects the 2nd item which is '11', so last_page = '11'.

range(1, int(last_page)+1) creates a range of numbers from 1 to 11.

page_url.format(i) formats those numbers in page_url, so dept_page_url contains 11 urls.


问:
Easy way to convert web forms to MVC3?
I haven't worked with MVC3 that much - as it was just released, but I was wondering if there was some kind of conversion tool - to convert exisiting Views / Forms into the newer up-to-date "Razor" view engine.

I'm not sure if it is possible but I just thought this would be the place to ask...

Thanks!

答:
I recently read on Dave Hayden's blog this morning about Telerik releasing a Razor View Conversion tool. I believe they used it to convert all of their demos on their site from all of their existing WebForm view to the new Razor View engine.

Here is Dave's short blurb regarding the tool and if you want to play around with it yourself, it is available on Github using the following link:

Github - Telerik Razor Conversion Tool

Hope this helps you out (I haven't had the chance to play around with it much - but knowing Telerik, it's probably pretty decent.)

OwnerDisplayName: Online Prodigy

Title: Easy way to convert web forms to MVC3?


问:
Java, Reading two different types of variables from a file and using them as objects later
I working on a project that is based on reading a text from a file and putting it as objects in my code.

My file has the following elements:
(ignore the bullet points)

4

Christmas Party

20

Valentine

12

Easter

5

Halloween

8

The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.

So for example, Christmas Party has 20 places available

Here's my code for saving the information from the file as objects.

```<code>public class Parties
{
   static Scanner input = new Scanner(System.in);

  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));

     int first = inFile.nextInt();
     inFile.nextLine();

    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }
</code>```

This is my SingleParty Class:

```<code>public class SingleParty
{
    private String name;
    private int tickets;

    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    }
</code>```

Can someone explain to me how could I approach this error?

Thank you

答:
You could create a HashMap and put all the options into that during your iteration.

```<code>HashMap<String, Integer> hmap = new HashMap<>();

while (sc.hasNext()) {
      String name = sc.nextLine();
      int tickets = Integer.parseInt(sc.nextLine());
      hmap.put(name, tickets);
}
</code>```

You can now do what you need with each entry in the HashMap.

Note: this assumes you've done something with the first line of the text file, the 4 in your example.

Body:
I working on a project that is based on reading a text from a file and putting it as objects in my code.

My file has the following elements:
(ignore the bullet points)

4

Christmas Party

20

Valentine

12

Easter

5

Halloween

8

The first line declares how many "parties" I have in my text file (its 4 btw)
Every party has two lines - the first line is the name and the second one is the number of places available.

So for example, Christmas Party has 20 places available

Here's my code for saving the information from the file as objects.

public class Parties
{
   static Scanner input = new Scanner(System.in);

  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt"));

     int first = inFile.nextInt();
     inFile.nextLine();

    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }

This is my SingleParty Class:

public class SingleParty
{
    private String name;
    private int tickets;

    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    }

Can someone explain to me how could I approach this error?

Thank you

Body:
You could create a HashMap and put all the options into that during your iteration.

HashMap<String, Integer> hmap = new HashMap<>();

while (sc.hasNext()) {
      String name = sc.nextLine();
      int tickets = Integer.parseInt(sc.nextLine());
      hmap.put(name, tickets);
}

You can now do what you need with each entry in the HashMap.

Note: this assumes you've done something with the first line of the text file, the 4 in your example.


问:
Choose an image from gallery and show it using an ImageView
```<code>private static int RESULT_LOAD = 1;
String img_Decodable_Str;

ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            img_Decodable_Str = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            // Set the Image in ImageView after decoding the String
            imageView.setImageBitmap(BitmapFactory
                    .decodeFile(img_Decodable_Str));

        } else {
            Toast.makeText(this, "Hey pick your image first",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went embrassing", Toast.LENGTH_LONG)
                .show();
    }

}}
</code>```

I have an ImageView. If the user clicks on the ImageView he will be able to add an image of his choice to it. When i click on the ImageView I'm redirected to gallery but when i choose an image, that image isn't showing in the ImageView. where have i gone wrong?

答:
In the short term, replace:

```<code>        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        img_Decodable_Str = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.Gallery);
        // Set the Image in ImageView after decoding the String
        imageView.setImageBitmap(BitmapFactory
                .decodeFile(img_Decodable_Str));
</code>```

with:

```<code>        Uri selectedImage = data.getData();
        imageView.setImageURI(selectedImage);
</code>```

Later, use an image-loading library, such as Picasso or Glide, as setImageURI() loads the image on the main application thread, which will freeze your UI for as long as that work takes.

Body:
private static int RESULT_LOAD = 1;
String img_Decodable_Str;

ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            img_Decodable_Str = cursor.getString(columnIndex);
            cursor.close();
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            // Set the Image in ImageView after decoding the String
            imageView.setImageBitmap(BitmapFactory
                    .decodeFile(img_Decodable_Str));

        } else {
            Toast.makeText(this, "Hey pick your image first",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went embrassing", Toast.LENGTH_LONG)
                .show();
    }

}}

I have an ImageView. If the user clicks on the ImageView he will be able to add an image of his choice to it. When i click on the ImageView I'm redirected to gallery but when i choose an image, that image isn't showing in the ImageView. where have i gone wrong?

Body:
In the short term, replace:

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        img_Decodable_Str = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.Gallery);
        // Set the Image in ImageView after decoding the String
        imageView.setImageBitmap(BitmapFactory
                .decodeFile(img_Decodable_Str));

with:

        Uri selectedImage = data.getData();
        imageView.setImageURI(selectedImage);

Later, use an image-loading library, such as Picasso or Glide, as setImageURI() loads the image on the main application thread, which will freeze your UI for as long as that work takes.


问:
Max size in array 2-dimentional in C++
I want to execute large computational program in 3 and 2 dimension with size of array[40000][40000] or more ,this code can explain my problem a bit,I comment vector because it have same problem when I run it it goes to lib of vector, how to increase memory of compiler or delete(clean) some part of it when program running?

```<code>#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
int main(){
    float array[40000][40000];
    //vector< vector<double> > array(1000,1000);
    cout<<"bingo"<<endl;
    return 0;
}
</code>```

答:
A slightly better option than vector (and far better than vector-of-vector1), which like vector, uses dynamic allocation for the contents (and therefore doesn't overflow the stack), but doesn't invite resizing:

```<code>std::unique_ptr<float[][40000]> array{ new float[40000][40000] };
</code>```

Conveniently, float[40000][40000] still appears, making it fairly obvious what is going on here even to a programmer unfamiliar with incomplete array types.

1 vector<vector<T> > is very bad, since it would have many different allocations, which all have to be separately initialized, and the resulting storage would be discontiguous.  Slightly better is a combination of vector<T> with vector<T*>, with the latter storing pointers created one row apart into a single large buffer managed by the former.

Title: Max size in array 2-dimentional in C++

Body:
I want to execute large computational program in 3 and 2 dimension with size of array[40000][40000] or more ,this code can explain my problem a bit,I comment vector because it have same problem when I run it it goes to lib of vector, how to increase memory of compiler or delete(clean) some part of it when program running?

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
int main(){
    float array[40000][40000];
    //vector< vector<double> > array(1000,1000);
    cout<<"bingo"<<endl;
    return 0;
}

Body:
A slightly better option than vector (and far better than vector-of-vector1), which like vector, uses dynamic allocation for the contents (and therefore doesn't overflow the stack), but doesn't invite resizing:

std::unique_ptr<float[][40000]> array{ new float[40000][40000] };

Conveniently, float[40000][40000] still appears, making it fairly obvious what is going on here even to a programmer unfamiliar with incomplete array types.

1 vector<vector<T> > is very bad, since it would have many different allocations, which all have to be separately initialized, and the resulting storage would be discontiguous.  Slightly better is a combination of vector<T> with vector<T*>, with the latter storing pointers created one row apart into a single large buffer managed by the former.


问:
How do I create a list with numbers between two values?
How do I create an ascending list between two values? For example, a list between 11 and 16:</p>
```<code>[11, 12, 13, 14, 15, 16]
</code>```

答:
Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

```<code>def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result
</code>```

For instance, standard command list(range(1,-3)) returns empty list [], while this function will return [-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.

Body:
How do I create an ascending list between two values? For example, a list between 11 and 16:

[11, 12, 13, 14, 15, 16]

Body:
Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result

For instance, standard command list(range(1,-3)) returns empty list [], while this function will return [-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.


问:
Understanding Hibernate Fetch
I know hibernate has lazy as default fetching strategy, but there are some things unclear to me so i hope you can explain it to me. What i want to do is to get a tile marked as start tile.

Query:

```<code>@NamedQuery(name = "Tile.findStartTileByGame",
  query = "SELECT t FROM Tile t WHERE t.game = :game " +
    "and t.startTile = true and t.blockWalkable = false")
</code>```

Tile:

```<code> public class Tile{

 @OneToOne(mappedBy="tile")
 private GameCharacter character;

 @OneToOne(mappedBy="tile")
 private GameObject gameObject;
</code>```

Game:

```<code> @OneToMany(mappedBy="game")
 private List<Tile> tiles;
</code>```

When i run my query and never use the object hibernate still joins me character and gameobject. So i have 3 Queries. I know i can solve this by a fetch join, but my question is why does hibernate fetch both entites at all? Even when i annotate them with fetch=FetchType.LAZY it will be queried.

My DAO:

```<code>  public static Tile getFreeStartTile(EntityManager em, Game game) {
   TypedQuery<Tile> query = em.createNamedQuery("Tile.findStartTileByGame", Tile.class);
   query.setParameter("game", game);
  List<Tile> result = query.getResultList();
  ...
</code>```

Before i fix this i would like to understand why it happens.
Thanks in advance
m

答:
I found my answer her:
http://community.jboss.org/wiki/HibernateFAQ-AdvancedProblems#Hibernate_ignores_my_outerjointrue_or_fetchjoin_setting_and_fetches_an_association_lazily_using_n1_selects

This is also a good question i have missed before which explains it very good:
JPA eager fetch does not join

Greetings

Title: Understanding Hibernate Fetch

Body:
I know hibernate has lazy as default fetching strategy, but there are some things unclear to me so i hope you can explain it to me. What i want to do is to get a tile marked as start tile.

Query:

@NamedQuery(name = "Tile.findStartTileByGame",
  query = "SELECT t FROM Tile t WHERE t.game = :game " +
    "and t.startTile = true and t.blockWalkable = false")

Tile:

 public class Tile{

 @OneToOne(mappedBy="tile")
 private GameCharacter character;

 @OneToOne(mappedBy="tile")
 private GameObject gameObject;

Game:

 @OneToMany(mappedBy="game")
 private List<Tile> tiles;

When i run my query and never use the object hibernate still joins me character and gameobject. So i have 3 Queries. I know i can solve this by a fetch join, but my question is why does hibernate fetch both entites at all? Even when i annotate them with fetch=FetchType.LAZY it will be queried.

My DAO:

  public static Tile getFreeStartTile(EntityManager em, Game game) {
   TypedQuery<Tile> query = em.createNamedQuery("Tile.findStartTileByGame", Tile.class);
   query.setParameter("game", game);
  List<Tile> result = query.getResultList();
  ...

Before i fix this i would like to understand why it happens.
Thanks in advance
m


问:
Regex match alphabetic/numeric that is not x
Assume I want to extract all strings starting in either ftp or ftpk (example made up).

I currently have a solution:

Get all the strings starting with ftp but not those starting in
  ftpx or ftpc.

I wonder how I can make it more general (because right now I'm listing the exceptions which can become tedious), something like:

Get all the strings starting with ftp but not those starting in
  ftpX where X is any alphabetic/numeric that is not k.

```<code># Data:
vec <- c("ftp:ladpmxqgvt", "ftpx:xfiwyoloqu", "ftpk:yol.qdsrehn",
         "ftpc:krjqdzsuhb", "ftpk:yolo.taxukj", "ftp:qvxarpkjid",
         "ebutlngqkr", "yolx.vhznja")

# Current solution (desired output)
grep("^ftp[^xc]", vec, value = TRUE)
"ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"
</code>```

答:
Code

See regex in use here

```<code>^ftpk?:
</code>```

If you don't know if : will follow ftp you can use the following, which simply ensures ftp or ftpk is followed by a non-word character:

```<code>^ftpk?\b
</code>```

Results

Input

```<code>ftp:ladpmxqgvt
ftpx:xfiwyoloqu
ftpk:yol.qdsrehn
ftpc:krjqdzsuhb
ftpk:yolo.taxukj
ftp:qvxarpkjid
ebutlngqkr
yolx.vhznja
</code>```

Output

Below lists only matches

```<code>ftp:ladpmxqgvt
ftpk:yol.qdsrehn
ftpk:yolo.taxukj
ftp:qvxarpkjid
</code>```

Explanation

^ Assert position at the start of the line

ftp Match this literally

k? Match k literally zero or once

: Match this literally

Body:
Assume I want to extract all strings starting in either ftp or ftpk (example made up).

I currently have a solution:

Get all the strings starting with ftp but not those starting in
  ftpx or ftpc.

I wonder how I can make it more general (because right now I'm listing the exceptions which can become tedious), something like:

Get all the strings starting with ftp but not those starting in
  ftpX where X is any alphabetic/numeric that is not k.

# Data:
vec <- c("ftp:ladpmxqgvt", "ftpx:xfiwyoloqu", "ftpk:yol.qdsrehn",
         "ftpc:krjqdzsuhb", "ftpk:yolo.taxukj", "ftp:qvxarpkjid",
         "ebutlngqkr", "yolx.vhznja")

# Current solution (desired output)
grep("^ftp[^xc]", vec, value = TRUE)
"ftp:ladpmxqgvt"   "ftpk:yol.qdsrehn" "ftpk:yolo.taxukj" "ftp:qvxarpkjid"

Body:
Code

See regex in use here

^ftpk?:

If you don't know if : will follow ftp you can use the following, which simply ensures ftp or ftpk is followed by a non-word character:

^ftpk?\b

Results

Input

ftp:ladpmxqgvt
ftpx:xfiwyoloqu
ftpk:yol.qdsrehn
ftpc:krjqdzsuhb
ftpk:yolo.taxukj
ftp:qvxarpkjid
ebutlngqkr
yolx.vhznja

Output

Below lists only matches

ftp:ladpmxqgvt
ftpk:yol.qdsrehn
ftpk:yolo.taxukj
ftp:qvxarpkjid

Explanation

^ Assert position at the start of the line

ftp Match this literally

k? Match k literally zero or once

: Match this literally


问:
Jacoco code coverage show 0% coverage on Jenkins
I have read most of the answers available for similar questions but none of those fit to answer my question.

My profile in pom file looks like this:

```<code>            <plugins>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.7.201606060606</version>
                    <executions>
                        <!-- Prepares the property pointing to the JaCoCo runtime agent which
                            is passed as VM argument when Maven the Surefire plugin is executed. -->
                        <execution>
                            <id>pre-unit-test</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                            <configuration>
                                <!-- Sets the path to the file which contains the execution data. -->
                                <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
                                <!-- Sets the name of the property containing the settings for JaCoCo
                                    runtime agent. -->
                                <propertyName>surefireArgLine</propertyName>
                            </configuration>
                        </execution>
                        <!-- Ensures that the code coverage report for unit tests is created
                            after unit tests have been run. -->
                        <execution>
                            <id>post-unit-test</id>
                            <phase>test</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                            <configuration>
                                <!-- Sets the path to the file which contains the execution data. -->
                                <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                                <!-- Sets the output directory for the code coverage report. -->
                                <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                    <executions>
                        <execution>
                            <id>surefire-unit-tests</id>
                            <phase>test</phase>
                            <goals>
                                <goal>test</goal>
                            </goals>
                            <configuration>
                                <!-- Sets the VM argument line used when unit tests are run. -->
                                <argLine>${surefireArgLine}</argLine>
                                <!-- Skips unit tests if the value of skip.unit.tests property is
                                    true -->
                                <skipTests>${skip.unit.tests}</skipTests>
                                <!-- Excludes integration tests when unit tests are run. -->
                                <skip>false</skip>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <version>2.19.1</version>
                    <executions>
                        <!-- Ensures that both integration-test and verify goals of the Failsafe
                            Maven plugin are executed. -->
                        <execution>
                            <id>integration-tests</id>
                            <goals>
                                <goal>integration-test</goal>
                                <goal>verify</goal>
                            </goals>
                            <configuration>
                                <!-- Sets the VM argument line used when integration tests are run. -->
                                <argLine>${failsafeArgLine}</argLine>
                                <!-- Skips integration tests if the value of skip.integration.tests
                                    property is true -->
                                <skipTests>${skip.integration.tests}</skipTests>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
</code>```

When I run my jenkins job with maven goal clean install -P test-coverage

I See this in my Jenkins log:

```<code>`[JaCoCo plugin] Collecting JaCoCo coverage data...
[JaCoCo plugin] **/target/coverage-reports/jacoco-ut.exec;**/target/classes;**/src/main/java; locations are configured
[JaCoCo plugin] Number of found exec files for pattern **/target/coverage-reports/jacoco-ut.exec: 0
[JaCoCo plugin] Saving matched execfiles:
[JaCoCo plugin] Saving matched class directories for class-pattern: **/target/classes:
[JaCoCo plugin] Saving matched source directories for source-pattern: **/src/main/java:
[JaCoCo plugin] Loading inclusions files..
[JaCoCo plugin] inclusions: []
[JaCoCo plugin] exclusions: []
[JaCoCo plugin] Thresholds: JacocoHealthReportThresholds [minClass=0, maxClass=0, minMethod=0, maxMethod=0, minLine=0, maxLine=0, minBranch=0, maxBranch=0, minInstruction=0, maxInstruction=0, minComplexity=0, maxComplexity=0]
[JaCoCo plugin] Publishing the results..
[JaCoCo plugin] Loading packages..
[JaCoCo plugin] Done.
[JaCoCo plugin] Overall coverage: class: 0, method: 0, line: 0, branch: 0, instruction: 0`
</code>```

This is how my Jenkins configuration for Jacoco looks like:

答:
In my case, Jacoco plugin is 1.0.19, but I am using Jacoco-maven-plugin 0.7.9 , which it is not compatible.

So, after change Jacoco-maven-plugin to 0.7.4.x. I get correct coverage on Jenkins

Body:
I have read most of the answers available for similar questions but none of those fit to answer my question.

My profile in pom file looks like this:

            <plugins>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.7.201606060606</version>
                    <executions>

                        <execution>
                            <id>pre-unit-test</id>
                            <goals>
                                <goal>prepare-agent</goal>
                            </goals>
                            <configuration>

                                <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>

                                <propertyName>surefireArgLine</propertyName>
                            </configuration>
                        </execution>

                        <execution>
                            <id>post-unit-test</id>
                            <phase>test</phase>
                            <goals>
                                <goal>report</goal>
                            </goals>
                            <configuration>

                                <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>

                                <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.19.1</version>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                    <executions>
                        <execution>
                            <id>surefire-unit-tests</id>
                            <phase>test</phase>
                            <goals>
                                <goal>test</goal>
                            </goals>
                            <configuration>

                                <argLine>${surefireArgLine}</argLine>

                                <skipTests>${skip.unit.tests}</skipTests>

                                <skip>false</skip>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <version>2.19.1</version>
                    <executions>

                        <execution>
                            <id>integration-tests</id>
                            <goals>
                                <goal>integration-test</goal>
                                <goal>verify</goal>
                            </goals>
                            <configuration>

                                <argLine>${failsafeArgLine}</argLine>

                                <skipTests>${skip.integration.tests}</skipTests>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>

When I run my jenkins job with maven goal clean install -P test-coverage

I See this in my Jenkins log:

`[JaCoCo plugin] Collecting JaCoCo coverage data...
[JaCoCo plugin] **/target/coverage-reports/jacoco-ut.exec;**/target/classes;**/src/main/java; locations are configured
[JaCoCo plugin] Number of found exec files for pattern **/target/coverage-reports/jacoco-ut.exec: 0
[JaCoCo plugin] Saving matched execfiles:
[JaCoCo plugin] Saving matched class directories for class-pattern: **/target/classes:
[JaCoCo plugin] Saving matched source directories for source-pattern: **/src/main/java:
[JaCoCo plugin] Loading inclusions files..
[JaCoCo plugin] inclusions: []
[JaCoCo plugin] exclusions: []
[JaCoCo plugin] Thresholds: JacocoHealthReportThresholds [minClass=0, maxClass=0, minMethod=0, maxMethod=0, minLine=0, maxLine=0, minBranch=0, maxBranch=0, minInstruction=0, maxInstruction=0, minComplexity=0, maxComplexity=0]
[JaCoCo plugin] Publishing the results..
[JaCoCo plugin] Loading packages..
[JaCoCo plugin] Done.
[JaCoCo plugin] Overall coverage: class: 0, method: 0, line: 0, branch: 0, instruction: 0`

This is how my Jenkins configuration for Jacoco looks like: