问:
Java using scanner enter key pressed
I am programming using Java.

I am trying write code which can recognize if the user presses the enter key in a console based program.

How can I do this using java. I have been told that this can be done using either Scanner or, buffered input reader. I do not understand(or know how to use) buffered input reader.

I tried to do do this using scanner but after pressing enter twice the program terminates, and it doesn't work

```<code>    Scanner readinput = new Scanner(System.in);

    String enterkey = "Hola";
    System.out.print(enterkey);

    enterkey = readinput.nextLine();
     System.out.print(enterkey);

    if(enterkey == ""){

        System.out.println("It works!");
</code>```

Thanks

-- edit --
the following code works using the equals method for the string instead of ==

```<code>    Scanner readinput = new Scanner(System.in);

    String enterkey = "Hola";
    System.out.print(enterkey);

    enterkey = readinput.nextLine();
     System.out.print(enterkey);

    if(enterkey.equals("")){

        System.out.println("It works!");
</code>```

how can this be done, and what are the pros to doing this using the buffered input reader?

答:
```<code>Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();

        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) {
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);
</code>```

This code works fine

Title: Java using scanner enter key pressed

Body:
I am programming using Java.

I am trying write code which can recognize if the user presses the enter key in a console based program.

How can I do this using java. I have been told that this can be done using either Scanner or, buffered input reader. I do not understand(or know how to use) buffered input reader.

I tried to do do this using scanner but after pressing enter twice the program terminates, and it doesn't work

    Scanner readinput = new Scanner(System.in);

    String enterkey = "Hola";
    System.out.print(enterkey);

    enterkey = readinput.nextLine();
     System.out.print(enterkey);

    if(enterkey == ""){

        System.out.println("It works!");

Thanks

-- edit --
the following code works using the equals method for the string instead of ==

    Scanner readinput = new Scanner(System.in);

    String enterkey = "Hola";
    System.out.print(enterkey);

    enterkey = readinput.nextLine();
     System.out.print(enterkey);

    if(enterkey.equals("")){

        System.out.println("It works!");

how can this be done, and what are the pros to doing this using the buffered input reader?

Body:
Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();

        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) {
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine


来源: stackexchange

问:
C3JS - Cannot read property 'category10' of undefined
I tried this c3.js code from jsfiddle (https://jsfiddle.net/varunoberoi/mcd6ucge) but it doesn't seem to work in my localhost.

I'm using uniserver as my server. I copy-paste everything but it's not working.

```<code><html>
    <head>
        <!-- CSS -->
        <link href="css/c3.css" rel="stylesheet" type="text/css" />

        <!-- JAVASCRIPT -->
        <script src="js/d3.min.js" type="text/javascript"></script>
        <script src="js/c3.js" type="text/javascript"></script>

        <script type="text/javascript">
            window.onload=function(){
                var chart = c3.generate({
                    data: {
                        columns: [
                            ['data1', 300, 350, 300, 0, 0, 0],
                            ['data2', 130, 100, 140, 200, 150, 50]
                        ],
                        types: {
                            data1: 'area',
                            data2: 'area-spline'
                        }
                    },
                    axis: {
                        y: {
                            padding: {bottom: 0},
                            min: 0
                        },
                        x: {
                            padding: {left: 0},
                            min: 0,
                            show: false
                        }
                    }

                });
            }
        </script>
    </head>
    <body>
        <div id="chart"></div>
    </body>
</html>
</code>```

What I got when I check the Developer Tools' console is this:

```<code>c3.js:5783 Uncaught TypeError: Cannot read property 'category10' of undefined
</code>```

I tried different versions of c3.js but nothing. It's weird because it's working in jsfiddle and not in my local.

答:
It's because, C3.js is based on D3 v3, and the error occurs when try to run with D3 v4.

The error occurs on below line of code:

```<code>pattern = notEmpty(config.color_pattern) ?
    config.color_pattern : d3.scale.category10().range()
</code>```

https://github.com/c3js/c3/blob/master/src/color.js#L7

On D3 v4, d3.scale.category10().range() should be used as d3.scaleOrdinal(d3.schemeCategory10), but as C3.js can't be ran on D3 v4 it's meaningless changing this part of code only.

If anyone need working with D3 v4+, try https://naver.github.io/billboard.js/.

billboard.js is a forked project of C3.js, having same interface with D3 v4+ support.

ContentLicense: CC BY-SA 3.0

Body:
I tried this c3.js code from jsfiddle (https://jsfiddle.net/varunoberoi/mcd6ucge) but it doesn't seem to work in my localhost.

I'm using uniserver as my server. I copy-paste everything but it's not working.

        <link href="css/c3.css" rel="stylesheet" type="text/css" />

What I got when I check the Developer Tools' console is this:

c3.js:5783 Uncaught TypeError: Cannot read property 'category10' of undefined

I tried different versions of c3.js but nothing. It's weird because it's working in jsfiddle and not in my local.

Body:
It's because, C3.js is based on D3 v3, and the error occurs when try to run with D3 v4.

The error occurs on below line of code:

pattern = notEmpty(config.color_pattern) ?
    config.color_pattern : d3.scale.category10().range()

https://github.com/c3js/c3/blob/master/src/color.js#L7

On D3 v4, d3.scale.category10().range() should be used as d3.scaleOrdinal(d3.schemeCategory10), but as C3.js can't be ran on D3 v4 it's meaningless changing this part of code only.

If anyone need working with D3 v4+, try https://naver.github.io/billboard.js/.

billboard.js is a forked project of C3.js, having same interface with D3 v4+ support.


问:
Setting Attributes using Hash in RUby
I'm currently completely stuck on a school problem and figured I'd reach out for some guidance.

Define a class named User. Its initialize method should take a Hash as an argument. We'll name the argument config and set a default value for the argument to an empty Hash:

```<code>class User
  def initialize(config = {})
  end
end
</code>```

This config = {} the syntax supplies a "default argument" for initialize. If someone initializes a User instance without a config argument, the config variable in the method will automatically be set to the default we gave it--an empty Hash.

The config argument should be used to set any of the following attributes on a user: name, email, bio, age, and sex. If an attribute is not provided in the Hash argument, the initialize method should default it to a value to "n/a". For example:

```<code>class User
  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    ...
  end
end
</code>```

Setting default values is a very common task in Ruby. A basic way to do this is by using the || assignment operator, which means "or". Consider the following examples:

```<code>a = 3
a = a || 6
a #=> 3
b = b || 9
b #=> 9
</code>```

Decode the logic in the conditional assignments above.

We'll also need to access the instance variables set in our initialize method. To do this, we can use the attr_accessor method declaration. The attr_accessor method also lets us declare multiple attributes on one line. For example:

```<code>class User
  attr_accessor :name, :email

  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    # ...
  end
end
</code>```

Finish writing the User class and initialize method to handle all of the required attributes.

I am entirely lost at this point. Thanks in advance.

答:
It looks as if you've copied your assignment directly. I'm not going to do the work for you, but I will give you some hints on a few lines of code:

```<code>def initialize(config = {})
</code>```

This is using a default parameter value while defining the method. If the user doesn't provide a config hash, the method will use an empty hash by default.

```<code>@name = config[:name] || "n/a"
</code>```

This statement is using || for flow control. If config[:name] is set, the value is assigned to @name. Otherwise, it defaults to "n/a".

```<code>attr_accessor :name, :email
</code>```

This is a shortcut to create getters and setters for :name and :email. It looks like your assignment is to add bio, age, and sex as instance variables and set them up with appropriate defaults.

Title: Setting Attributes using Hash in RUby

Body:
I'm currently completely stuck on a school problem and figured I'd reach out for some guidance.

Define a class named User. Its initialize method should take a Hash as an argument. We'll name the argument config and set a default value for the argument to an empty Hash:

class User
  def initialize(config = {})
  end
end

This config = {} the syntax supplies a "default argument" for initialize. If someone initializes a User instance without a config argument, the config variable in the method will automatically be set to the default we gave it--an empty Hash.

The config argument should be used to set any of the following attributes on a user: name, email, bio, age, and sex. If an attribute is not provided in the Hash argument, the initialize method should default it to a value to "n/a". For example:

class User
  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    ...
  end
end

Setting default values is a very common task in Ruby. A basic way to do this is by using the || assignment operator, which means "or". Consider the following examples:

a = 3
a = a || 6
a #=> 3
b = b || 9
b #=> 9

Decode the logic in the conditional assignments above.

We'll also need to access the instance variables set in our initialize method. To do this, we can use the attr_accessor method declaration. The attr_accessor method also lets us declare multiple attributes on one line. For example:

class User
  attr_accessor :name, :email

  def initialize(config = {})
    @name = config[:name] || "n/a"
    @email = config[:email] || "n/a"
    # ...
  end
end

Finish writing the User class and initialize method to handle all of the required attributes.

I am entirely lost at this point. Thanks in advance.

Body:
It looks as if you've copied your assignment directly. I'm not going to do the work for you, but I will give you some hints on a few lines of code:

def initialize(config = {})

This is using a default parameter value while defining the method. If the user doesn't provide a config hash, the method will use an empty hash by default.

@name = config[:name] || "n/a"

This statement is using || for flow control. If config[:name] is set, the value is assigned to @name. Otherwise, it defaults to "n/a".

attr_accessor :name, :email

This is a shortcut to create getters and setters for :name and :email. It looks like your assignment is to add bio, age, and sex as instance variables and set them up with appropriate defaults.


问:
Nuget restore continuous integration
I have a web application where a script folder is getting created when I execute the nuget command via console, where as from my visualstudio.com I have added the step Nuget restore with installation type as restore. I continued with default setting for that, now after that step is getting passed I am not seeing any scripts folder getting created in my agent. I am referring to few of the scripts as follows

But while adding my project to GIT I didn't included my scripts folder thinking that nuget restore will take care. Due to this my build is getting failed so can some one help me how to over come this issue

答:
The reason is that the script folder is created when install the package in Visual Studio. Restore or install package through Nuget.exe tool doesn’t generate script folder and files. So you can’t deal this issue with Nuget.exe tool.

I recommend that you can use bower to manage these packages (Install Bower extension for build or release).

Another way it that you can copy related files to your project (files are in packages folder) through Copy Files task or you can include these files to the repo directly.

Title: Nuget restore continuous integration


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
One (maybe overkill) option could be use a compiler for a reduced SQL language. Something like using JavaCC with a modified SQL grammar that only allows SELECT statements, then you might receive the query, compile it and if it compiles you can run it.

For C# i know Irony but never used it.

OwnerDisplayName: Yaakov Ellis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Paulo Lopes


问:
BLE Frequent disconnection and not connecting automatically when in range
Hi i am developing an app to read heart rate from bracelet (Band) and displaying in application using bluetooth but the bluetooth connection is getting disconnected frequently and also not connecting automatically when in range. Any reference please. </p>

答:
If you are using Android you should look for Bluetooth Auto Connect app which connects near by bluetooth device automatically

can be found here

https://play.google.com/store/apps/details?id=org.myklos.btautoconnect&hl=en


问:
Replacing specific characters in python string
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

```<code>string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"
</code>```

I'm trying to use replace function. But failed to get the exact result.

答:
You can use regex:</p>

```<code>>>> import re
>>> re.sub(r"'([^']+)': '([^']*)'", r"%\1%: '\2'", string)
"create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"
</code>```

Body:
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

I'm trying to use replace function. But failed to get the exact result.

Body:
You can use regex:

>>> import re
>>> re.sub(r"'([^']+)': '([^']*)'", r"%\1%: '\2'", string)
"create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"


问:
SQLSyntaxErrorException: data type exception due to `COALESCE` in HSQLDB
I had to upgrade the org.hsqldb library version from 2.2.9 to 2.4.0, in order to support schemas with NOT EXIST keyword as suggested in another question at this site, but then I encountered lots of JUnit tests which fails with

```<code>Caused by: java.sql.SQLSyntaxErrorException:
data type cast needed for parameter or null literal in statement
[INSERT INTO xxx(y) VALUES (COALESCE(?,?))]
</code>```

my hsqldb looks like:

```<code>CREATE TABLE xxx (
    y VARCHAR (32) NOT NULL
)
</code>```

they only thing that worked for me is to move the COALESCE logic to my Java sources before inserting.

Questions:

it makes me think that the requirement NOT NULL in the schema didn't worked until the version 2.4.0, and that's why my tests fails only now. beside deleting this requirement, there is anything I can do to avoid that restriction?

is there a function like COALESCE which insert default value if all the parameters are null?

答:
You can fix it with a cast:</p>

```<code>INSERT INTO xxx(y) VALUES (COALESCE(CAST(? AS VARCHAR(32)),?)
</code>```

Body:
I had to upgrade the org.hsqldb library version from 2.2.9 to 2.4.0, in order to support schemas with NOT EXIST keyword as suggested in another question at this site, but then I encountered lots of JUnit tests which fails with

Caused by: java.sql.SQLSyntaxErrorException:
data type cast needed for parameter or null literal in statement
[INSERT INTO xxx(y) VALUES (COALESCE(?,?))]

my hsqldb looks like:

CREATE TABLE xxx (
    y VARCHAR (32) NOT NULL
)

they only thing that worked for me is to move the COALESCE logic to my Java sources before inserting.

Questions:

it makes me think that the requirement NOT NULL in the schema didn't worked until the version 2.4.0, and that's why my tests fails only now. beside deleting this requirement, there is anything I can do to avoid that restriction?

is there a function like COALESCE which insert default value if all the parameters are null?

Body:
You can fix it with a cast:

INSERT INTO xxx(y) VALUES (COALESCE(CAST(? AS VARCHAR(32)),?)


问:
Date picker and list picker (multiple time zones) to create a scheduled date string
On the UI side of this project, there is a date picker and list picker intended to allow users to select a future time and date for specific time zones to schedule an alert to be broadcasted by voice, SMS, email, etc. Unfortunately, though, the GMT offset does not correctly adjust. For instance, an alert scheduled for Berlin, Germany (GMT+0200) for June 7, 2017, 17:33 actually yields the next day at 02:30 Berlin time.

2017-06-08 00:33:00 +0200

1. Would anyone know what may cause this discrepancy and how to
    correct it for all time zones?

2. What steps are necessary to adjust all the scheduled
    times to Central Daylight Time?

Screenshot of New Alert View Controller

In the NewAlertTableViewController.m, this function updates the date picker label:

```<code>- (void) updateDateLabel {
    NSDate *now                  = [NSDate date];
    NSDate *scheduledDate        = self.datePicker.date;
    if ([scheduledDate isToday] && scheduledDate.hour <= now.hour && scheduledDate.minute <= now.minute) {
        self.dateLabel.text      = NSLocalizedString(@"Now", @"label for time an alert is scheduled to be sent");
        self.sendButton.title    = NSLocalizedString(@"Send Alert", @"button label for sending an alert");
        self.alert.sendNow       = YES;
    } else if ([scheduledDate isToday]) {
        self.dateLabel.text      = [NSString stringWithFormat: NSLocalizedString(@"Today, %@", @"label for time an alert is scheduled to be sent"), [scheduledDate stringWithDateStyle: NSDateFormatterNoStyle                                                                                timeStyle: NSDateFormatterShortStyle]];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    } else {
        self.dateLabel.text      = [scheduledDate stringWithDateStyle: NSDateFormatterShortStyle
                                                            timeStyle: NSDateFormatterShortStyle];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    }
    self.alert.scheduledDate     = scheduledDate;
    DDLogInfo(@"Date Picker: %@", scheduledDate);
}
</code>```

Also in the NewAlertTableViewController.m, we have this delegate to handle the time zone picker view:

```<code>- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZone;
    NSString *timeZoneCity;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"Z";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZone     = (@"GMT%@", systemTimeZoneOffset);
            timeZoneCity = @"Device Default";
            break;
        case 1:
            timeZone     = @"GMT+02:00";
            timeZoneCity = @"Berlin";
            break;
        case 2:
            timeZone     = @"GMT+01:00";
            timeZoneCity = @"London";
            break;
        case 3:
            timeZone     = @"GMT-04:00";
            timeZoneCity = @"New York";
            break;
        case 4:
            timeZone     = @"GMT-05:00";
            timeZoneCity = @"Chicago";
            break;
        case 5:
            timeZone     = @"GMT-06:00";
            timeZoneCity = @"Denver";
            break;
        case 6:
            timeZone     = @"GMT-07:00";
            timeZoneCity = @"Los Angeles";
            break;
        case 7:
            timeZone     = @"GMT-08:00";
            timeZoneCity = @"Anchorage";
            break;
        case 8:
            timeZone     = @"GMT-10:00";
            timeZoneCity = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZone];
    [[NSUserDefaults standardUserDefaults] setObject: timeZone forKey: @"timeZonePreference"];
    DDLogInfo(@"Time Zone Picker: %@, %@", timeZone, timeZoneCity);
    _timeZoneLabel.text = timeZoneCity;
}
</code>```

Yet again in the NewAlertTableViewController.m, this function updates the time zone:

```<code>- (void) updateTimeZone: (id)timeZone {
    self.now                     = [NSDate date];
    self.calendar                = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    [self.calendar setTimeZone: [NSTimeZone timeZoneWithName: timeZone]];
    NSCalendarUnit units         = NSCalendarUnitHour;
    NSDateComponents *components = [self.calendar components: units fromDate: self.now];
    self.hours                   = (int)[components hour];
    self.alert.calendar          = self.calendar;
}
</code>```

In the Alert.m, we have this string that gets sent as a parameter to our CreateAlert.aspx endpoint. Ideally, we'd prefer all strings adjusted to Central Daylight Time (to match our server in Houston, TX) or at least Coordinated Universal Time (UTC).

```<code>- (NSString *)scheduledDateString { // This method solely uses the scheduledDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat       = @"yyyy-MM-dd HH:mm:ss Z";
    dateFormatter.timeZone         = self.calendar.timeZone;
    NSString *dateString           = [dateFormatter stringFromDate: self.scheduledDate];
    DDLogInfo(@"Scheduled Date: %@", dateString);
    return dateString;
}
</code>```

答:
Thanks to savvy suggestions from @DonMag, I'm in the home stretch! Got perfect NSDates now with this new NewAlertTableViewController.m time zone picker view delegate:

```<code>- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZoneName;
    NSString *timeZoneLabel;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"VVVV";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZoneName  = ("%@", systemTimeZoneOffset);
            timeZoneLabel = @"Device Default";
            break;
        case 1:
            timeZoneName  = @"Europe/Berlin";
            timeZoneLabel = @"Berlin";
            break;
        case 2:
            timeZoneName  = @"Europe/London";
            timeZoneLabel = @"London";
            break;
        case 3:
            timeZoneName  = @"America/New_York";
            timeZoneLabel = @"New York";
            break;
        case 4:
            timeZoneName  = @"America/Chicago";
            timeZoneLabel = @"Chicago";
            break;
        case 5:
            timeZoneName  = @"America/Denver";
            timeZoneLabel = @"Denver";
            break;
        case 6:
            timeZoneName  = @"America/Los_Angeles";
            timeZoneLabel = @"Los Angeles";
            break;
        case 7:
            timeZoneName  = @"America/Anchorage";
            timeZoneLabel = @"Anchorage";
            break;
        case 8:
            timeZoneName  = @"Pacific/Honolulu";
            timeZoneLabel = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZoneName];
    _timeZoneLabel.text                  = timeZoneLabel;
    NSTimeZone *timeZone                 = [NSTimeZone timeZoneWithName: timeZoneName];
    DDLogInfo(@"Time Zone Picker: %@", timeZoneName);
    NSDate *datePickerSelection          = _datePicker.date;
    NSCalendar *calendar                 = [NSCalendar currentCalendar];
    NSDateComponents *localComponents    = [calendar components: -1 fromDate: datePickerSelection];
    [calendar setTimeZone: timeZone];
    NSDateComponents *timeZoneComponents = [[NSDateComponents alloc] init];
    [timeZoneComponents setYear:    [localComponents year]];
    [timeZoneComponents setMonth:   [localComponents month]];
    [timeZoneComponents setDay:     [localComponents day]];
    [timeZoneComponents setHour:    [localComponents hour]];
    [timeZoneComponents setMinute:  [localComponents minute]];
    [timeZoneComponents setSecond:  [localComponents second]];
    _desiredDateTime                     = [calendar dateFromComponents: timeZoneComponents];
    DDLogInfo(@"Desired Date: %@", _desiredDateTime);
}
</code>```

Body:
On the UI side of this project, there is a date picker and list picker intended to allow users to select a future time and date for specific time zones to schedule an alert to be broadcasted by voice, SMS, email, etc. Unfortunately, though, the GMT offset does not correctly adjust. For instance, an alert scheduled for Berlin, Germany (GMT+0200) for June 7, 2017, 17:33 actually yields the next day at 02:30 Berlin time.

2017-06-08 00:33:00 +0200

1. Would anyone know what may cause this discrepancy and how to
    correct it for all time zones?

2. What steps are necessary to adjust all the scheduled
    times to Central Daylight Time?

Screenshot of New Alert View Controller

In the NewAlertTableViewController.m, this function updates the date picker label:

- (void) updateDateLabel {
    NSDate *now                  = [NSDate date];
    NSDate *scheduledDate        = self.datePicker.date;
    if ([scheduledDate isToday] && scheduledDate.hour <= now.hour && scheduledDate.minute <= now.minute) {
        self.dateLabel.text      = NSLocalizedString(@"Now", @"label for time an alert is scheduled to be sent");
        self.sendButton.title    = NSLocalizedString(@"Send Alert", @"button label for sending an alert");
        self.alert.sendNow       = YES;
    } else if ([scheduledDate isToday]) {
        self.dateLabel.text      = [NSString stringWithFormat: NSLocalizedString(@"Today, %@", @"label for time an alert is scheduled to be sent"), [scheduledDate stringWithDateStyle: NSDateFormatterNoStyle                                                                                timeStyle: NSDateFormatterShortStyle]];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    } else {
        self.dateLabel.text      = [scheduledDate stringWithDateStyle: NSDateFormatterShortStyle
                                                            timeStyle: NSDateFormatterShortStyle];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    }
    self.alert.scheduledDate     = scheduledDate;
    DDLogInfo(@"Date Picker: %@", scheduledDate);
}

Also in the NewAlertTableViewController.m, we have this delegate to handle the time zone picker view:

- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZone;
    NSString *timeZoneCity;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"Z";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZone     = (@"GMT%@", systemTimeZoneOffset);
            timeZoneCity = @"Device Default";
            break;
        case 1:
            timeZone     = @"GMT+02:00";
            timeZoneCity = @"Berlin";
            break;
        case 2:
            timeZone     = @"GMT+01:00";
            timeZoneCity = @"London";
            break;
        case 3:
            timeZone     = @"GMT-04:00";
            timeZoneCity = @"New York";
            break;
        case 4:
            timeZone     = @"GMT-05:00";
            timeZoneCity = @"Chicago";
            break;
        case 5:
            timeZone     = @"GMT-06:00";
            timeZoneCity = @"Denver";
            break;
        case 6:
            timeZone     = @"GMT-07:00";
            timeZoneCity = @"Los Angeles";
            break;
        case 7:
            timeZone     = @"GMT-08:00";
            timeZoneCity = @"Anchorage";
            break;
        case 8:
            timeZone     = @"GMT-10:00";
            timeZoneCity = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZone];
    [[NSUserDefaults standardUserDefaults] setObject: timeZone forKey: @"timeZonePreference"];
    DDLogInfo(@"Time Zone Picker: %@, %@", timeZone, timeZoneCity);
    _timeZoneLabel.text = timeZoneCity;
}

Yet again in the NewAlertTableViewController.m, this function updates the time zone:

- (void) updateTimeZone: (id)timeZone {
    self.now                     = [NSDate date];
    self.calendar                = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    [self.calendar setTimeZone: [NSTimeZone timeZoneWithName: timeZone]];
    NSCalendarUnit units         = NSCalendarUnitHour;
    NSDateComponents *components = [self.calendar components: units fromDate: self.now];
    self.hours                   = (int)[components hour];
    self.alert.calendar          = self.calendar;
}

In the Alert.m, we have this string that gets sent as a parameter to our CreateAlert.aspx endpoint. Ideally, we'd prefer all strings adjusted to Central Daylight Time (to match our server in Houston, TX) or at least Coordinated Universal Time (UTC).

- (NSString *)scheduledDateString { // This method solely uses the scheduledDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat       = @"yyyy-MM-dd HH:mm:ss Z";
    dateFormatter.timeZone         = self.calendar.timeZone;
    NSString *dateString           = [dateFormatter stringFromDate: self.scheduledDate];
    DDLogInfo(@"Scheduled Date: %@", dateString);
    return dateString;
}

Body:
Thanks to savvy suggestions from @DonMag, I'm in the home stretch! Got perfect NSDates now with this new NewAlertTableViewController.m time zone picker view delegate:

- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZoneName;
    NSString *timeZoneLabel;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"VVVV";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZoneName  = ("%@", systemTimeZoneOffset);
            timeZoneLabel = @"Device Default";
            break;
        case 1:
            timeZoneName  = @"Europe/Berlin";
            timeZoneLabel = @"Berlin";
            break;
        case 2:
            timeZoneName  = @"Europe/London";
            timeZoneLabel = @"London";
            break;
        case 3:
            timeZoneName  = @"America/New_York";
            timeZoneLabel = @"New York";
            break;
        case 4:
            timeZoneName  = @"America/Chicago";
            timeZoneLabel = @"Chicago";
            break;
        case 5:
            timeZoneName  = @"America/Denver";
            timeZoneLabel = @"Denver";
            break;
        case 6:
            timeZoneName  = @"America/Los_Angeles";
            timeZoneLabel = @"Los Angeles";
            break;
        case 7:
            timeZoneName  = @"America/Anchorage";
            timeZoneLabel = @"Anchorage";
            break;
        case 8:
            timeZoneName  = @"Pacific/Honolulu";
            timeZoneLabel = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZoneName];
    _timeZoneLabel.text                  = timeZoneLabel;
    NSTimeZone *timeZone                 = [NSTimeZone timeZoneWithName: timeZoneName];
    DDLogInfo(@"Time Zone Picker: %@", timeZoneName);
    NSDate *datePickerSelection          = _datePicker.date;
    NSCalendar *calendar                 = [NSCalendar currentCalendar];
    NSDateComponents *localComponents    = [calendar components: -1 fromDate: datePickerSelection];
    [calendar setTimeZone: timeZone];
    NSDateComponents *timeZoneComponents = [[NSDateComponents alloc] init];
    [timeZoneComponents setYear:    [localComponents year]];
    [timeZoneComponents setMonth:   [localComponents month]];
    [timeZoneComponents setDay:     [localComponents day]];
    [timeZoneComponents setHour:    [localComponents hour]];
    [timeZoneComponents setMinute:  [localComponents minute]];
    [timeZoneComponents setSecond:  [localComponents second]];
    _desiredDateTime                     = [calendar dateFromComponents: timeZoneComponents];
    DDLogInfo(@"Desired Date: %@", _desiredDateTime);
}


问:
vb.net in InDesign Scripting - Grouping TextFrames
I want to group textframes in my InDesign CS3 vb.net script. It worked for InDesign 2.0 but it does not work with InDesign CS3. Here is my code:

```<code>Dim myDoc As InDesign.Document = Nothing
Dim myGroup As InDesign.Group = Nothing
Dim myObjectList(2)

myObjectList.SetValue(myOuterTextFrame, 0)
myObjectList.SetValue(myInnerTextFrame, 1)
myObjectList.SetValue(myContentTextFrame, 2)

myGroup = myDoc.Groups.Add(myObjectList)
</code>```

Getting error "Unable to cast object of type 'System.Object[]' to type 'InDesign.Objects'."

答:
I know you asked for this a long time ago so I'm mostly answering for future searches. I haven't found a fully managed way to do this using the .Net Framework and believe me, I've searched for it. I've tried a million different casts, subclassing, reflection, you name it. What ultimately worked in the end was JavaScript. Below is a method that takes an InDesign.Document object and two or more integers that represent InDesign item IDs. It then creates some JavaScript and has InDesign execute it. Finally it returns an InDesign.Group created from those objects.

```<code>Public Function GroupObjects(ByVal indesignDocument As InDesign.Document, ByVal ParamArray objectIds() As Integer) As InDesign.Group
    'Sanity checks
    If indesignDocument Is Nothing Then Throw New ArgumentNullException("indesignDocument")
    If objectIds Is Nothing OrElse objectIds.Count < 2 Then Throw New ArgumentException("You must pass at least 2 object ids")

    'We'll assign a unique label to the group that we create in JavaScript so that we can find it in managed code later
    Dim GID = Guid.NewGuid().ToString()

    'Create the JavaScript
    Dim Buf As New StringBuilder()
    Buf.AppendLine("var items = new Array();")
    For Each ID In objectIds
        Buf.AppendFormat("items.push(app.activeWindow.activePage.pageItems.itemByID({0}));", ID)
        Buf.AppendLine()
    Next
    Buf.AppendLine("var g = app.activeWindow.activePage.groups.add(items);")
    Buf.AppendFormat("g.label='{0}';", GID)

    Dim IA = indesignDocument.Parent
    IA.DoScript(Buf.ToString(), InDesign.idScriptLanguage.idJavascript)

    'Loop through all document groups looking for the object with the label created above
    For Each G As InDesign.Group In indesignDocument.Groups
        If Not String.IsNullOrWhiteSpace(G.Label) AndAlso G.Label = GID Then Return G
    Next
    Return Nothing
End Function
</code>```

To use it in your code you'd say:

```<code>Dim MyGroup = GroupObjects(myOuterTextFrame, myInnerTextFrame, myContentTextFrame)
</code>```

Body:
I want to group textframes in my InDesign CS3 vb.net script. It worked for InDesign 2.0 but it does not work with InDesign CS3. Here is my code:

Dim myDoc As InDesign.Document = Nothing
Dim myGroup As InDesign.Group = Nothing
Dim myObjectList(2)

myObjectList.SetValue(myOuterTextFrame, 0)
myObjectList.SetValue(myInnerTextFrame, 1)
myObjectList.SetValue(myContentTextFrame, 2)

myGroup = myDoc.Groups.Add(myObjectList)

Getting error "Unable to cast object of type 'System.Object[]' to type 'InDesign.Objects'."

Body:
I know you asked for this a long time ago so I'm mostly answering for future searches. I haven't found a fully managed way to do this using the .Net Framework and believe me, I've searched for it. I've tried a million different casts, subclassing, reflection, you name it. What ultimately worked in the end was JavaScript. Below is a method that takes an InDesign.Document object and two or more integers that represent InDesign item IDs. It then creates some JavaScript and has InDesign execute it. Finally it returns an InDesign.Group created from those objects.

Public Function GroupObjects(ByVal indesignDocument As InDesign.Document, ByVal ParamArray objectIds() As Integer) As InDesign.Group
    'Sanity checks
    If indesignDocument Is Nothing Then Throw New ArgumentNullException("indesignDocument")
    If objectIds Is Nothing OrElse objectIds.Count < 2 Then Throw New ArgumentException("You must pass at least 2 object ids")

    'We'll assign a unique label to the group that we create in JavaScript so that we can find it in managed code later
    Dim GID = Guid.NewGuid().ToString()

    'Create the JavaScript
    Dim Buf As New StringBuilder()
    Buf.AppendLine("var items = new Array();")
    For Each ID In objectIds
        Buf.AppendFormat("items.push(app.activeWindow.activePage.pageItems.itemByID({0}));", ID)
        Buf.AppendLine()
    Next
    Buf.AppendLine("var g = app.activeWindow.activePage.groups.add(items);")
    Buf.AppendFormat("g.label='{0}';", GID)

    Dim IA = indesignDocument.Parent
    IA.DoScript(Buf.ToString(), InDesign.idScriptLanguage.idJavascript)

    'Loop through all document groups looking for the object with the label created above
    For Each G As InDesign.Group In indesignDocument.Groups
        If Not String.IsNullOrWhiteSpace(G.Label) AndAlso G.Label = GID Then Return G
    Next
    Return Nothing
End Function

To use it in your code you'd say:

Dim MyGroup = GroupObjects(myOuterTextFrame, myInnerTextFrame, myContentTextFrame)


问:
CSS: style nth sibling
Is it possible to style the nth sibling in pure CSS?

For example, can we style 4-th or 5-th .child when hover on 1-st .child?

```<code><div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div>
</code>```

update I guess my question was not correct a bit. Excuse me for that.

I meant can I style nth sibling of a .child that I hovered on?

I.e. style 4-th .child when hover on 1-st .child; style 5-th .child when hover on 2-nd, etc.

答:
Sure we can

.child:nth-child(1):hover ~ .child:nth-child(4),
.child:nth-child(1):hover ~ .child:nth-child(5) {
  background-color: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div></code>```

Title: CSS: style nth sibling

Body:
Is it possible to style the nth sibling in pure CSS?

For example, can we style 4-th or 5-th .child when hover on 1-st .child?

 1

 2

 3

 4

 5

update I guess my question was not correct a bit. Excuse me for that.

I meant can I style nth sibling of a .child that I hovered on?

I.e. style 4-th .child when hover on 1-st .child; style 5-th .child when hover on 2-nd, etc.

Body:
Sure we can

.child:nth-child(1):hover ~ .child:nth-child(4),
.child:nth-child(1):hover ~ .child:nth-child(5) {
  background-color: orange;
}

<div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div>


问:
Function with variable parameter type
I have these two functions which are basically the same:

```<code>private Order getOrder( List<Order> orders, String gcsId )
{
    Predicate<Order> predicate = c -> c.getGcsId().equals( gcsId );
    Order obj = orders.stream().filter( predicate ).findFirst().get();
    return obj;
}

private OrderLine getOrderLine( List<OrderLine> orderLines, String gcsId )
{
    Predicate<OrderLine> predicate = c -> c.getGcsId().equals( gcsId );
    OrderLine obj = orderLines.stream().filter( predicate ).findFirst().get();
    return obj;
}
</code>```

The only difference is the type of the first parameter. How can I create a single function with the first parameter having a variable type?

Edit: This is how I call those functions in another method of the same class:

```<code>Order order = getOrder( orders, orderId );
OrderLine orderLine = getOrderLine( order.getOrderLines(), orderLineId );
</code>```

答:
If you give a List of Order you return an Ornder, if you give an define a generic method instead:

```<code>private <T extends Foo> T getOrder(List<T > orders, String gcsId) {
    Predicate<T> predicate = c -> c.getGcsId().equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}
</code>```

where Foo interface is

```<code>interface Foo {
    String getGcsId();
}

class OrderLine implements Foo {

    @Override
    public String getGcsId() {
        return something;
    }

}

class Order implements Foo {

    @Override
    public String getGcsId() {
        return something;
    }

}
</code>```

Title: Function with variable parameter type

Body:
I have these two functions which are basically the same:

private Order getOrder( List<Order> orders, String gcsId )
{
    Predicate<Order> predicate = c -> c.getGcsId().equals( gcsId );
    Order obj = orders.stream().filter( predicate ).findFirst().get();
    return obj;
}

private OrderLine getOrderLine( List<OrderLine> orderLines, String gcsId )
{
    Predicate<OrderLine> predicate = c -> c.getGcsId().equals( gcsId );
    OrderLine obj = orderLines.stream().filter( predicate ).findFirst().get();
    return obj;
}

The only difference is the type of the first parameter. How can I create a single function with the first parameter having a variable type?

Edit: This is how I call those functions in another method of the same class:

Order order = getOrder( orders, orderId );
OrderLine orderLine = getOrderLine( order.getOrderLines(), orderLineId );

Body:
If you give a List of Order you return an Ornder, if you give an define a generic method instead:

private <T extends Foo> T getOrder(List<T > orders, String gcsId) {
    Predicate<T> predicate = c -> c.getGcsId().equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}

where Foo interface is

interface Foo {
    String getGcsId();
}

class OrderLine implements Foo {

    @Override
    public String getGcsId() {
        return something;
    }

}

class Order implements Foo {

    @Override
    public String getGcsId() {
        return something;
    }

}


问:
Visual studio 2015: breakpoint will not be hit, no symbols loaded for this document
This problem happened when I tried to build OpenImageIO on Windows 7 64 bit + Visual Studio 2015. There are some problems in the compiled binary of the OpenImageIO library, so I want to debug some source codes of it to locate the problem. But the breakpoint does not hit.

Specifically, the application code I used to debug OpenImageIO is Tools\iconvert and the code crashes when I execute to the line:

```<code>ImageInput *in = ImageInput::open (in_filename.c_str());
</code>```

The implementation of ImageInput::open is contained in imageinput.cpp in project OpenImageIO of the solution. I compiled both projects under Debug configuration which enables debugging information generation. But when I set a breakpoint at the definition of ImageInput::open at line 86, the breakpoint is white indicating that it is invalid, and the prompt says the breakpoint is not currently be hit, as the screenshot below shows:

I checked other places, like the reference properties which indicates clearly that the iconvert is linking to the Debug version of the OpenImageIO library:

Also, the Debug configuration is set correctly (in my understanding):

So, why the breakpoint cannot be hit? How should I fix this issue? If you need more information to troubleshoot please let me know. Thanks a lot.

答:
About one year ago, I encountered a similar problem when I tried to use PyCharm (running on Windows) to remotely debug a python script executed inside Autodesk Maya (running on Linux). Later I managed to figure out it was due to the path of Linux -- it is an old python script in one of the search paths in linux that is running instead of the script in the source folder I assumed to be running. So I think the problem here should be the same.

OpenImageIO depends on a lot of 3rd party libraries in dll form, so yesterday, I put all of them into C:\Windows\system32 to ease searching. But since there are some problems, today I changed the settings of CMake and rebuild, and I changed my mind during the rebuild by putting newly compiled dlls to OIIO's bin folder (I don't want to mess up the system directory). To make the change take effect, I added this folder into PATH and deleted old problematic dlls from system32. But I missed one -- OpenImageIO.dll which is responsible for ImageInput::open! I trusted my memory too much; I should have sorted files by create date.

Of course I didn't know of it at first, so according to my previous experience, first I checked if the dll loaded is the one I just built. This was done by menu DEBUG->Windows->Modules in VS2015. Aha, that windows clearly shows it is the OpenImageIO.dll in system32 that is loaded, which reminded me of what was happening. So I deleted (with shift) that old dll and everything is working as expected now -- I finally successfully build OpenImageIO using VS2015 on Windows 7 64 bit from source from scratch, including all 3rd party libraries.

Body:
This problem happened when I tried to build OpenImageIO on Windows 7 64 bit + Visual Studio 2015. There are some problems in the compiled binary of the OpenImageIO library, so I want to debug some source codes of it to locate the problem. But the breakpoint does not hit.

Specifically, the application code I used to debug OpenImageIO is Tools\iconvert and the code crashes when I execute to the line:

ImageInput *in = ImageInput::open (in_filename.c_str());

The implementation of ImageInput::open is contained in imageinput.cpp in project OpenImageIO of the solution. I compiled both projects under Debug configuration which enables debugging information generation. But when I set a breakpoint at the definition of ImageInput::open at line 86, the breakpoint is white indicating that it is invalid, and the prompt says the breakpoint is not currently be hit, as the screenshot below shows:

I checked other places, like the reference properties which indicates clearly that the iconvert is linking to the Debug version of the OpenImageIO library:

Also, the Debug configuration is set correctly (in my understanding):

So, why the breakpoint cannot be hit? How should I fix this issue? If you need more information to troubleshoot please let me know. Thanks a lot.


问:
File Upload - Allert if occurred error without submit
I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.

 Here is my code:

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("
", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
                $("

")
                ));
    });

//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

    var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("

");

       var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

       $(this).hide();
                $("#abcd"+ abc).append($("", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
    background-color:white;
}
#maindiv{
    width:960px;
    margin:10px auto;
    padding:10px;
    font-family: 'Droid Sans', sans-serif;
}
#formdiv{
    width:500px;
    float:left;
    text-align: center;
}
form{
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;
}
h2{
    margin-left: 30px;
}
.upload{
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}
#upload{
    margin-left: 45px;
}

#noerror{
    color:green;
    text-align: left;
}
#error{
    color:red;
    text-align: left;
}

.abcd{
    text-align: center;
}

b{
    color:red;
}
#formget{
    float:right;

}</code>```

                <form action = "" enctype="multipart/form-data" action="" method="post">

<input name="file[]" type="file" id="file"/>

     <input type="text" required >
                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>

                <?php include "upload.php"; ?>

```
</div>
</div>
</p>

<p>And my php file: </p>

```<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "pdf");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').Image uploaded successfully!.

';
            } else {//if file was not moved.
                echo $j. ').please try again!.

';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').***Invalid file Size or Type***

';
        }
    }}?>
```

答:
Try something like this u will get </p>

<pre class="lang-js prettyprint-override"><code>$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
});

$("#approvedFiles").val(approvedHTML);
</code>```

Body:
I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.

 Here is my code:

var abc = 0; //Declaring and defining global increement variable

$(document).ready(function() {

//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
    $('#add_more').click(function() {
        $(this).before($("
", {id: 'filediv'}).fadeIn('slow').append(
                $("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
                $("

")
                ));
    });

//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
            if (this.files && this.files[0]) {
                 abc += 1; //increementing global variable by 1

    var z = abc - 1;
                var x = $(this).parent().find('#previewimg' + z).remove();
                $(this).before("

");

       var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);

       $(this).hide();
                $("#abcd"+ abc).append($("", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
                $(this).parent().parent().remove();
                }));
            }
        });

//To preview image
    function imageIsLoaded(e) {
        $('#previewimg' + abc).attr('src', e.target.result);
    };

    $('#upload').click(function(e) {
        var name = $(":file").val();
        if (!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});

@import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
    background-color:white;
}
#maindiv{
    width:960px;
    margin:10px auto;
    padding:10px;
    font-family: 'Droid Sans', sans-serif;
}
#formdiv{
    width:500px;
    float:left;
    text-align: center;
}
form{
    padding: 40px 20px;
    box-shadow: 0px 0px 10px;
    border-radius: 2px;
}
h2{
    margin-left: 30px;
}
.upload{
    background-color:#ff0000;
    border:1px solid #ff0000;
    color:#fff;
    border-radius:5px;
    padding:10px;
    text-shadow:1px 1px 0px green;
    box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
    cursor:pointer;
    background:#c20b0b;
    border:1px solid #c20b0b;
    box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
    color:green;
    padding:5px; border:1px dashed #123456;
    background-color: #f9ffe5;
}
#upload{
    margin-left: 45px;
}

#noerror{
    color:green;
    text-align: left;
}
#error{
    color:red;
    text-align: left;
}

.abcd{
    text-align: center;
}

b{
    color:red;
}
#formget{
    float:right;

}

                <form action = "" enctype="multipart/form-data" action="" method="post">

<input name="file[]" type="file" id="file"/>

     <input type="text" required >
                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>

                <?php include "upload.php"; ?>

And my php file:

<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png", "pdf");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').Image uploaded successfully!.

';
            } else {//if file was not moved.
                echo $j. ').please try again!.

';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').***Invalid file Size or Type***

';
        }
    }}?>

Body:
Try something like this u will get

$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
});

$("#approvedFiles").val(approvedHTML);


问:
Can you set the current running directory from the java command line?
I am running a Java application from the command line. Can I specify a command line argument to set the current running directory to something other than where the application is actually going to run?</p>

答: If you want to change the current directory, you'll have to use JNI and invoke a native API from your Java code. For example, for Windows you would use SetCurrentDirectory</p>


答:
.child {
  border: 1px solid;
  width: 3em;
  height: 3em;
  text-align: center;
  line-height: 3em;
}

.child:first-child:hover~.child:nth-child(4),
.child:first-child:hover~.child:nth-child(5) {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child"> 1 </div>
  <div class="child"> 2 </div>
  <div class="child"> 3 </div>
  <div class="child"> 4 </div>
  <div class="child"> 5 </div>
</div></code>```

Title: CSS: style nth sibling

Body:
.child {
  border: 1px solid;
  width: 3em;
  height: 3em;
  text-align: center;
  line-height: 3em;
}

.child:first-child:hover~.child:nth-child(4),
.child:first-child:hover~.child:nth-child(5) {
  background-color: red;
}

<div class="parent">
  <div class="child"> 1 </div>
  <div class="child"> 2 </div>
  <div class="child"> 3 </div>
  <div class="child"> 4 </div>
  <div class="child"> 5 </div>
</div>


问:
CSS placing an absolute div beside another div (pure CSS popover)
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

```<code><div>
    <div><figure class="figure"><img ... /></figure></div>
    //css-popover
    <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>
</code>```

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

答:
1) With Pure css.

.wrap {
   position: relative;;
}

.im {
   width: 200px;
}

img {
   width: 100%;
}

.css-popover{
   display: none;
}

.im:hover + .css-popover {
   display: block;
}

figure {
   margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
   <div class="im">
     <figure class="figure"><img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" /></figure>
   </div>
   <div class="css-popover">User detail: ... bla bla bla ...</div>
</div></code>```

2) With Jquery

$(document).ready(function(){
 $('.figure img').hover(function(){
  $('.css-popover').css('display','block');
 },function(){
  $('.css-popover').css('display','none');
   })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.css-popover {
  display: none;
}

img {
  width: 100px;
}</code>```

User detail: ... bla bla bla ...

```

Body:
I have a sidebar with a user profile picture (pink color). When the viewer hover on the image, a div (blue color) appears and it contains user details. Basically, I want an absolute positioned div appear next to its sibling.

It is functionally a popover, but I want to do it with pure CSS, is it possible?

I am using boostrap 4, it will be nice if the suggestion can co-exists with Bootstrap CSS. It will be awesome if the div can have an arrow associate with it.

My code is:

    //css-popover

User detail: ... bla bla bla ...

I tried to search in Stackoverflow, most of the question is related to float div and makes it beside, but I want something absolute positioned, and display on top of the body.

Update:

Most of the suggestions provided fulfill part of the requests. The suggested .css-popover width and height are bounded by the parents, but I wish the popover dimension be independent from the parent, i.e. just "popup" and it doesn't "change" the layout beneath.

And when the popup appear, it doesn't change the parent height too. I wish the sidebar "icon" (light pink icons) stay in place whenever a popup appear.

If it is not possible with CSS, then I just go for JS solution...

You can try your luck here. https://jsfiddle.net/byanjiong/nohno2bd/13/

(Note: the user content is long, so it height usually will exceed the profile image's height)

Update 2:
Thanks to @Gezzasa, his solution is working. ^_^

Guy, this is the working example of pure CSS popover! Amazing!

https://jsfiddle.net/byanjiong/nohno2bd/15/

Thanks, guy...

Body:
1) With Pure css.

.wrap {
   position: relative;;
}

.im {
   width: 200px;
}

img {
   width: 100%;
}

.css-popover{
   display: none;
}

.im:hover + .css-popover {
   display: block;
}

figure {
   margin: 0;
}

<div class="wrap">
   <div class="im">
     <figure class="figure"><img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" /></figure>
   </div>
   <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>

2) With Jquery

$(document).ready(function(){
 $('.figure img').hover(function(){
  $('.css-popover').css('display','block');
 },function(){
  $('.css-popover').css('display','none');
   })
})

.css-popover {
  display: none;
}

img {
  width: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
   <div>
       <figure class="figure"><img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" /></figure>
    </div>
    <div class="css-popover">User detail: ... bla bla bla ...</div>
</div>


问:
NServiceBus: System.Transactions.TransactionException: The partner transaction manager has disabled its support for remote/network transactions
I am getting this exception on my subscriber when I try to save a record to a database from within my Handle(T value) method in my IHandleMessages implementation.  Does anyone know why that would happen?  I think I remember that NServiceBus uses distributed transactions to make the handling of messages transactional, but I have no idea why it doesn't just "work" after running the "RunMeFirst.bat" file on both machines.

Any ideas?

答: Found the answer.  It looks like I needed to enable the "Allow Inbound" option under MSDTC Security settings.  Does anyone know why the RunMeFirst.bat doesn't set this?</p>


答:
Sure you can. You use the general sibling selector (~) in combination with :hover.

.child:first-of-type:hover ~ .child:nth-of-type(4) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div></code>```

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

UPDATE

update I guess my question was not correct a bit. Excuse me for that.

I meant can I style nth sibling of hovered .child?

No, since as far as I know there's no way for "counting siblings".
You could work-around the problem, say you want to highlight the second sibling of each .child when hovering.

.child:nth-of-type(1):hover ~ .child:nth-of-type(3) {
  color: red;
}

.child:nth-of-type(2):hover ~ .child:nth-of-type(4) {
  color: red;
}

.child:nth-of-type(3):hover ~ .child:nth-of-type(5) {
  color: red;
}

.child:nth-of-type(4):hover ~ .child:nth-of-type(6) {
  color: red;
}

.child:nth-of-type(5):hover ~ .child:nth-of-type(7) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div></code>```

To simplify this task, you may want to use a preprocessor like SASS:

```<code>@each $i in (1, 2, 3, 4, 5) {
  .child:nth-of-type(#{$i}):hover ~ .child:nth-of-type(#{$i + 2}) {
    color: red;
  }
}
</code>```

which would generate above CSS.

Title: CSS: style nth sibling

Body:
Sure you can. You use the general sibling selector (~) in combination with :hover.

.child:first-of-type:hover ~ .child:nth-of-type(4) {
  color: red;
}

<div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div>

The ~ combinator separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent.

UPDATE

update I guess my question was not correct a bit. Excuse me for that.

I meant can I style nth sibling of hovered .child?

No, since as far as I know there's no way for "counting siblings".
You could work-around the problem, say you want to highlight the second sibling of each .child when hovering.

.child:nth-of-type(1):hover ~ .child:nth-of-type(3) {
  color: red;
}

.child:nth-of-type(2):hover ~ .child:nth-of-type(4) {
  color: red;
}

.child:nth-of-type(3):hover ~ .child:nth-of-type(5) {
  color: red;
}

.child:nth-of-type(4):hover ~ .child:nth-of-type(6) {
  color: red;
}

.child:nth-of-type(5):hover ~ .child:nth-of-type(7) {
  color: red;
}

<div class="parent">
    <div class="child"> 1 </div>
    <div class="child"> 2 </div>
    <div class="child"> 3 </div>
    <div class="child"> 4 </div>
    <div class="child"> 5 </div>
</div>

To simplify this task, you may want to use a preprocessor like SASS:

@each $i in (1, 2, 3, 4, 5) {
  .child:nth-of-type(#{$i}):hover ~ .child:nth-of-type(#{$i + 2}) {
    color: red;
  }
}

which would generate above CSS.


问:
How to load dynamic record from database mysql in angularjs?
Here I want to load database user in select box using angular.

```<code><div ng-app="myapp" ng-controller="myctrl" class="centered">
  <label>Select User</label>
    <select ng-model="selectedItem" ng-options="item.name for item in list">
        <option value="">-- choose --</option>
    </select>
     <h2>Selected:</h2>
        {{selectedItem.name}}
</div>
<script type="text/javascript">
var app=angular.module('myapp',[]);
app.controller('myctrl', function($scope, $http) {
$http({
    method : "GET",
    url : "http://localhost/demo/angular/getdata.php"
}).then(
function (response) {
   $scope.list = response.data.records;
});
});
</script>
</code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
<title>Dynemic Select box</title>
<!---load css-->
<link href="css/style.css" type="text/css" rel="stylesheet">
<link href="css/bootstrap.css" type="text/css" rel="stylesheet">
<!---load js-->
<script src="js/jquery-2.1.4.min.js" type="text/Javascript" ></script>
<script src="js/bootstrap.js" type="text/Javascript" ></script>
<script src="js/angular.min.js" type="text/Javascript" ></script>
</head>
<body
<?php
     echo $header;
     $userdata=$this->model_user->getuser();
     $userdata =json_encode($userdata);
   ?>
 <div ng-app="myapp" ng-controller="myctrl" class="centered">
 <label>Select User</label>
 <select ng-options="x.id as x.name for x in sample" ng-model="x.id" name="selectedItem" id="selectedItem">

    <h2>Selected:</h2>
    {{selectedItem.name}}
</div>
 <script type="text/javascript">
var app=angular.module('myapp',[]);
app.controller('myctrl', function($scope) {
 $scope.sample=<?php echo $userdata;?>;
});
</script>
</body>
</htnl>
</code>```

Body:
Here I want to load database user in select box using angular.

  Select User
    <select ng-model="selectedItem" ng-options="item.name for item in list">
        <option value="">-- choose --</option>
    </select>

Selected:

        {{selectedItem.name}}


问:
How to sort a vector using sort() in c++
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

```<code>//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);
</code>```

答:
Just keeping it simple, let arr be the vector name. Write: sort(arr.beg(),arr.end());

(assuming already you have  written using namespace std;)

Body:
I want to insert an element in my already sorted vector and it'll be placed at its sorted position when it'll be sorted again.
There is a function called sort() for sorting an array.How can I use the same function to sort a vector?
Here's my code.It gives me the compilation error.

//assume g1 is already sorted with some numbers
int x;
cin >> x;
g1.push_back(x);
int s = g1.size()/g1.at(g1.begin());
//similar to int s = arr/arr[0]
sort(g1 + s,g1);


问:
Mongo - Return items that exist with one value but not another
I have a collection of documents that represent products available in different locales. Some products are available only in certain locales. If a product isn't specifically listed for a given locale, then it's not available for that locale.

Here's a tiny example, with only the pertinent bits:

```<code>{ "locale": "US", "productId": "123" }
{ "locale": "CA", "productId": "123" }
{ "locale": "FR", "productId": "123" }
{ "locale": "US", "productId": "456" }
{ "locale": "FR", "productId": "456" }
</code>```

I'd like to query for all the productIds that are available in the US, but not in CA. In this example, that'd be productId 456.

If I were doing this in SQL, I'd join the table to itself and find the answer that way. But I'm not sure how to tackle this sort of query in Mongo. What's the most appropriate way to do this sort of thing?

答:
According to description as mentioned in above question please try executing following aggregate query in MongoDB shell.

```<code>    db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
             _id:{productId:'$productId'},
             locale:{$addToSet:'$locale'}
            }
        },

        // Stage 2
        {
            $match: {
               locale:{$in:['US'],$nin:['CA']}
            }
        },

    ]
);
</code>```

The above mentioned aggregate query executes following stages of aggregation in pipeline.

$group operator groups documents according to values of productId and
push values of locale associated to productId into an array using
$addToSet operator.

$match operator filters documents having only US locale along

with excluding documents having CA locale from array of locale

values generated in group stage.

Body:
I have a collection of documents that represent products available in different locales. Some products are available only in certain locales. If a product isn't specifically listed for a given locale, then it's not available for that locale.

Here's a tiny example, with only the pertinent bits:

{ "locale": "US", "productId": "123" }
{ "locale": "CA", "productId": "123" }
{ "locale": "FR", "productId": "123" }
{ "locale": "US", "productId": "456" }
{ "locale": "FR", "productId": "456" }

I'd like to query for all the productIds that are available in the US, but not in CA. In this example, that'd be productId 456.

If I were doing this in SQL, I'd join the table to itself and find the answer that way. But I'm not sure how to tackle this sort of query in Mongo. What's the most appropriate way to do this sort of thing?

Body:
According to description as mentioned in above question please try executing following aggregate query in MongoDB shell.

    db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
             _id:{productId:'$productId'},
             locale:{$addToSet:'$locale'}
            }
        },

        // Stage 2
        {
            $match: {
               locale:{$in:['US'],$nin:['CA']}
            }
        },

    ]
);

The above mentioned aggregate query executes following stages of aggregation in pipeline.

$group operator groups documents according to values of productId and
push values of locale associated to productId into an array using
$addToSet operator.

$match operator filters documents having only US locale along

with excluding documents having CA locale from array of locale

values generated in group stage.


问:
Could not migrate and how to set mysql DB using Django python
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

```<code>Unknown command: 'migrate'
Type 'manage.py help' for usage.
</code>```

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

```<code>"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
</code>```

Please help me to resolve the above issue and connect to DB.

答:
Default database: sqlite3

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
</code>```

Change to mysql:

```<code>'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER' : 'username',
        'PASSWORD' : 'password',
        'HOST' : 'your ip',
        'PORT' : 'port',
    }
</code>```

In django new version. I have to do 3 step to migrate

```<code>python manage.py makemigrations <app_name>
python manage.py sqlmigrate svace <version of data>
python manage.py migrate
</code>```

End of answers

Body:
I am beginner of Django python. When I am running into this python manage.py migrate I am getting the following error.

Unknown command: 'migrate'
Type 'manage.py help' for usage.

Here also I am trying to create one crud application with MYSQL database which is present inside localhost means I need to connect to my localhost database .I need to also know how to connect it inside the settings.py file with all credentials. My settings.py file is given below.

settings.py:

"""
Django settings for mysite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#=0(1b4%2y!3(hs%_4v&_*(-j#c#8__s6^=1+b0eqrar7810h+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

Please help me to resolve the above issue and connect to DB.

Body:
Default database: sqlite3

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Change to mysql:

'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER' : 'username',
        'PASSWORD' : 'password',
        'HOST' : 'your ip',
        'PORT' : 'port',
    }

In django new version. I have to do 3 step to migrate

python manage.py makemigrations <app_name>
python manage.py sqlmigrate svace <version of data>
python manage.py migrate

End of answers


问:
Magento "adminhtml/system_config_backend_image_favicon" Error
I tried to install the Blank template in Magento and now get the following error printing when trying to access the Admin -> Configuration -> Design section.

```<code>Invalid config field backend model: adminhtml/system_config_backend_image_favicon

Trace:
#0 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php(310): Mage::throwException('Invalid config ...')
#1 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php(204): Mage_Adminhtml_Block_System_Config_Form->initFields(Object(Varien_Data_Form_Element_Fieldset), Object(Mage_Core_Model_Config_Element), Object(Mage_Core_Model_Config_Element))
#2 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php(92): Mage_Adminhtml_Block_System_Config_Form->initForm()
#3 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php(77): Mage_Adminhtml_Block_System_Config_Edit->initForm()
#4 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_System_ConfigController->editAction()
#5 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch('edit')
#6 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#7 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/App.php(304): Mage_Core_Controller_Varien_Front->dispatch()
#8 /home/trilight/public_html/magetest/app/Mage.php(596): Mage_Core_Model_App->run(Array)
#9 /home/trilight/public_html/magetest/index.php(80): Mage::run('', 'store')
#10 {main}
</code>```

I don't understand what the error is and a simple Google search brings nothing. I have another error when accessing the front end and that is as follows:

```<code>Invalid method Mage_Wishlist_Block_Links::addWishlistLink(Array
(
)
)

Trace:
#0 [internal function]: Varien_Object->__call('addWishlistLink', Array)
#1 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(347): Mage_Wishlist_Block_Links->addWishlistLink()
#2 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(213): Mage_Core_Model_Layout->_generateAction(Array, Array)
#3 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#4 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(209): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#5 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(343): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#6 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/Helper/Page.php(110): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#7 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage()
#8 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#9 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Cms_IndexController->indexAction(Object(Mage_Cms_IndexController), 'home')
#10 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch()
#11 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match('index')
#12 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/App.php(304): Mage_Core_Controller_Varien_Front->dispatch(Object(Mage_Core_Controller_Request_Http))
#13 /home/trilight/public_html/magetest/app/Mage.php(596): Mage_Core_Model_App->run()
#14 /home/trilight/public_html/magetest/index.php(80): Mage::run(Array)
#15 {main}
</code>```

Any help will be so much appreciated.

Thanks.

答:
It happened after installing the Yoast seo blank theme through connectmanager on a new installation of magento (1.4.2.0)

I don't know if it would make a difference if you install the theme by uploading it via FTP?

Body:
I tried to install the Blank template in Magento and now get the following error printing when trying to access the Admin -> Configuration -> Design section.

Invalid config field backend model: adminhtml/system_config_backend_image_favicon

Trace:
#0 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php(310): Mage::throwException('Invalid config ...')
#1 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php(204): Mage_Adminhtml_Block_System_Config_Form->initFields(Object(Varien_Data_Form_Element_Fieldset), Object(Mage_Core_Model_Config_Element), Object(Mage_Core_Model_Config_Element))
#2 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/Block/System/Config/Edit.php(92): Mage_Adminhtml_Block_System_Config_Form->initForm()
#3 /home/trilight/public_html/magetest/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php(77): Mage_Adminhtml_Block_System_Config_Edit->initForm()
#4 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_System_ConfigController->editAction()
#5 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch('edit')
#6 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#7 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/App.php(304): Mage_Core_Controller_Varien_Front->dispatch()
#8 /home/trilight/public_html/magetest/app/Mage.php(596): Mage_Core_Model_App->run(Array)
#9 /home/trilight/public_html/magetest/index.php(80): Mage::run('', 'store')
#10 {main}

I don't understand what the error is and a simple Google search brings nothing. I have another error when accessing the front end and that is as follows:

Invalid method Mage_Wishlist_Block_Links::addWishlistLink(Array
(
)
)

Trace:
#0 [internal function]: Varien_Object->__call('addWishlistLink', Array)
#1 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(347): Mage_Wishlist_Block_Links->addWishlistLink()
#2 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(213): Mage_Core_Model_Layout->_generateAction(Array, Array)
#3 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#4 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/Layout.php(209): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#5 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(343): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#6 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/Helper/Page.php(110): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#7 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage()
#8 /home/trilight/public_html/magetest/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#9 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Cms_IndexController->indexAction(Object(Mage_Cms_IndexController), 'home')
#10 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch()
#11 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match('index')
#12 /home/trilight/public_html/magetest/app/code/core/Mage/Core/Model/App.php(304): Mage_Core_Controller_Varien_Front->dispatch(Object(Mage_Core_Controller_Request_Http))
#13 /home/trilight/public_html/magetest/app/Mage.php(596): Mage_Core_Model_App->run()
#14 /home/trilight/public_html/magetest/index.php(80): Mage::run(Array)
#15 {main}

Any help will be so much appreciated.

Thanks.


问:
Can't figure out how to get basic ruby 'encryptor' to work
Basically want to make 'abc' into 'bcd'. I was thinking if I add the letter the follows the first to the end of the phrase and dropped the original first letter, eventually I'd get the final solution. Got kinda stuck and was hoping someone could shed some light on it for me. Thanks</p>

```<code>def encrypt(str)
  index = 0
  encrypted_str = ""
  duration = str.length
  until index == str.length
    encrypted_str = str + str[0].next
    encrypted_str = encrypted_str + encrypted_str.delete(str[index])
    index += 1
  end
  puts encrypted_str
end

#puts "What would you like to encrypt?"
message = "abc"
puts encrypt(message)
</code>```

答:
Another option, which uses more power of stdlib :)

```<code>def original
  "abcdefghijklmnopqrstuvwxyz"
end
def replacement
  "bcdefghijklmnopqrstuvwxyza"
end

def encrypt(str)
  str.tr(original, replacement)
end

def decrypt(str)
  str.tr(replacement, original)
end

encrypt('abc') # => "bcd"
decrypt('bcd') # => "abc"
</code>```

Quite flexible too (compared to succ-based approach). You can change replacement alphabet to define arbitrary transformation rules.

Body:
Basically want to make 'abc' into 'bcd'. I was thinking if I add the letter the follows the first to the end of the phrase and dropped the original first letter, eventually I'd get the final solution. Got kinda stuck and was hoping someone could shed some light on it for me. Thanks

def encrypt(str)
  index = 0
  encrypted_str = ""
  duration = str.length
  until index == str.length
    encrypted_str = str + str[0].next
    encrypted_str = encrypted_str + encrypted_str.delete(str[index])
    index += 1
  end
  puts encrypted_str
end

#puts "What would you like to encrypt?"
message = "abc"
puts encrypt(message)

Body:
Another option, which uses more power of stdlib :)

def original
  "abcdefghijklmnopqrstuvwxyz"
end
def replacement
  "bcdefghijklmnopqrstuvwxyza"
end

def encrypt(str)
  str.tr(original, replacement)
end

def decrypt(str)
  str.tr(replacement, original)
end

encrypt('abc') # => "bcd"
decrypt('bcd') # => "abc"

Quite flexible too (compared to succ-based approach). You can change replacement alphabet to define arbitrary transformation rules.