问:
How to authenticate an insert or return error
im implementing a simple API CRUD using Django + Django rest and have a doubt.
I have two models:

```<code>class Shoe(models.Model):
    _id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=100, null=False, blank=False)
    provider = models.CharField(max_length=100, null=False, blank=False)
    type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False)
    cost_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo',
            null=False, blank=False
            )
    sale_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda',
            null=False, blank=False
            )

class Stock(models.Model):
    _id = models.AutoField(primary_key=True)
    id_shoe = models.ForeignKey(
            Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)
</code>```

What I am wanting is, when someone tries to make an insertion of stock of a size (of a certain shoe) that already exists it returns error. I can not just be 'unique' in the parameters of size. Any suggestions on how to do this?

答:
Since you want only one Stock item for each unique combination of shoe and size, you can use unique_together [Django-doc] here:

```<code>class Stock(models.Model):
    shoe = models.ForeignKey(Shoe, on_delete=models.CASCADE, verbose_name='shoe', related_name='stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)

    class Meta:
        <b>unique_together = ('shoe', 'size')</b></code>```

Note the name of a ForeignKey is usually not prefixed or suffixed with id_ or _id, Django automatically creates a "twin" field with the _id suffix that stores the primary key of the referenced value.

Note: If you do not specify a primary key, Django will automatically make one named id, so here it is probably better to let Django implement the logic.

Body:
im implementing a simple API CRUD using Django + Django rest and have a doubt.
I have two models:

class Shoe(models.Model):
    _id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=100, null=False, blank=False)
    provider = models.CharField(max_length=100, null=False, blank=False)
    type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False)
    cost_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo',
            null=False, blank=False
            )
    sale_price = models.DecimalField(
            max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda',
            null=False, blank=False
            )

class Stock(models.Model):
    _id = models.AutoField(primary_key=True)
    id_shoe = models.ForeignKey(
            Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)

What I am wanting is, when someone tries to make an insertion of stock of a size (of a certain shoe) that already exists it returns error. I can not just be 'unique' in the parameters of size. Any suggestions on how to do this?

Body:
Since you want only one Stock item for each unique combination of shoe and size, you can use unique_together [Django-doc] here:

class Stock(models.Model):
    shoe = models.ForeignKey(Shoe, on_delete=models.CASCADE, verbose_name='shoe', related_name='stock')
    size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False)
    amount = models.IntegerField(null=False, default=0)

    class Meta:
        unique_together = ('shoe', 'size')

Note the name of a ForeignKey is usually not prefixed or suffixed with id_ or _id, Django automatically creates a "twin" field with the _id suffix that stores the primary key of the referenced value.

Note: If you do not specify a primary key, Django will automatically make one named id, so here it is probably better to let Django implement the logic.


来源: stackexchange

问:
Can't get result outside the query function in express nodejs
I am trying to get the value of variable w_name outside query even I have defined w_name before query but cannot getting it after query. Please check the code and help:

```<code>connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                        w_name = res[0].name;
                });
                console.log(w_name);
</code>```

console.log showing undefined but if I am putting console.log inside the query after w_name it is showing proper result. What's wrong in it?

答:
NodeJs is asynchronous, It uses callback for the results.
The best solution as far as i know about your problem is given below:

```<code>async function myQuery(){
     return new Promise((resolve,reject)=>{
            connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                    resolve(res[0].name)
            });

     })
}
</code>```

Now you can use then to get the value or use async await to get the value like this.

```<code>//this is where you would like to call that function.

async function index(){
    let w_name = await myQuery()
    console.log(w_name)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get the value of variable w_name outside query even I have defined w_name before query but cannot getting it after query. Please check the code and help:

connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                        w_name = res[0].name;
                });
                console.log(w_name);

console.log showing undefined but if I am putting console.log inside the query after w_name it is showing proper result. What's wrong in it?

Body:
NodeJs is asynchronous, It uses callback for the results.
The best solution as far as i know about your problem is given below:

async function myQuery(){
     return new Promise((resolve,reject)=>{
            connection.query('SELECT * FROM workstations WHERE id=?',[results[0].w_id],function(err,res,field){
                    resolve(res[0].name)
            });

     })
}

Now you can use then to get the value or use async await to get the value like this.

//this is where you would like to call that function.

async function index(){
    let w_name = await myQuery()
    console.log(w_name)
}


问:
beta regression vs. linear regression for strictly bounded outcome variable [0,1]
So I am trying to explain my strictly bounded variable (percentage) with some predictors - categorical as well as numerical. I have read quite a bit about the topic, but I am still confused about some of the arguments. The purpose of my regression is explaining, not predicting.

What are the consequences of running a linear regression on a strictly bounded outcome variable?

答:
A linear regression does not have a bounded output. It's a linear transformation of the input, so if the input is twice as large, the output will be twice as large. That way, it will always be possible to find an input that exceeds the boundaries of the output.

You can apply a sigmoid function to the output of the linear regression (this is called "logistic regression"), but this will model a binary variable and give you the probability of the variable being 1. In your case, your variable isn't binary, it can have any value between 0 and 1. For that problem, you need to apply a beta regression, which will give you a bounded output between 0 and 1.


问:
How to make more precise the reading of AnalogPins in Arduino?
I'm new here so, if I make any mistake, sorry. Well, I'm working with Arduino (Mega2560) to construct an Ammeter and found out a little problem... Arduino Mega measures voltage from 0 to 5V, and the AnalogPins return a 10-bit value according with the reading (that is, 1 bit represents 5/(2^10)=4mV (approximately)). But, in the case of ammeter, I need to use a resistor with small resistance so that my circuit don't get changes. So my objective is read the voltage drop and from V = R.I, calculate the current. But, as the voltage drop is such as slowly, the pin can't read any value.
Eg.: there is a current flowing from 2mA in the region that I would like to measure. With a resistance of 0.3 ohms (the lower value I found here) , would be: V = 2m . 0.3 = 0.6mV.
As I said, the lower posssible value of reading in analogPins is 4mV.
Thus, how to improve my precision of reading? For example, instead of 1023 represents only 5V, the same value represents around of 30 or 40mV...
                                    0     -  0 V
                                    1023  -  30/40 mV</p>

答:
You can use 1.1V internal voltage reference, or some more precise external one (This can be archieved by analogReference). BTW with such a small currents it would be more convenient to use bigger resistor.

Or, forget about limited functionality of analogRead and do it directly. For example 2.56V reference, differential input with 10x or 200x gain (but you'll get range -512 to 511 ->  2.56/512).


问:
MySQL procedure with complex SELECT gives "Undeclared Variable" on table names
I'm trying to create my first set of MySQL procedures. In this case, I want to have a simple call collate relevant information from 4 tables into a single result and return a discrete selection of fields as the result. To this end, I've written this:

```<code>CREATE PROCEDURE `DatabaseName.GetCityIdentity`
(
IN  CityId BIGINT(20) UNSIGNED,
OUT
    `id`            BIGINT(20) UNSIGNED,
    `provId`        BIGINT(20) UNSIGNED,
    `countryId`     BIGINT(20) UNSIGNED,
    `currencyId`    BIGINT(20) UNSIGNED,
    `cityName`      VARCHAR(64),
    `latitude`      DECIMAL(10,6),
    `longitude`     DECIMAL(10,6),
    `provName`      VARCHAR(64),
    `provAbbr`      VARCHAR(4),
    `countryName`   VARCHAR(64),
    `countryAbbr`   VARCHAR(4),
    `currencyName`  VARCHAR(64),
    `currencySymbol`VARCHAR(8),
    `fullName`      VARCHAR(256),
    `abbrName`      VARCHAR(80)
)
BEGIN
    SELECT
        `c`.`id` INTO `id`, `c`.`name` INTO `cityName`, `c`.`provId` INTO `provId`, `c`.`latitude` INTO`latitude`, `c`.`longitude` INTO `longitude`,
        `p`.`name` INTO `provName`, `p`.`abbr` INTO `provAbbr`, `p`.`countryId` INTO `countryId`,
        `y`.`name` INTO `countryName`, `y`.`abbr` INTO `countryAbbr`, `y`.`defaultCurrency` INTO `currencyId`,
        `d`.`name` INTO `currencyName`, `d`.`symbol` INTO `currencySymbol`,
        CONCAT(`c`.`name`, ', ', `p`.`name`, ', ', `y`.`Name`) INTO `fullName`,
        CONCAT(`c`.`name`, ', ', `p`.`abbr`, ', ', `y`.`abbr`) INTO `abbrName`
    FROM `cities` AS `c`
        LEFT JOIN `provinces` AS `p` ON `c`.`provId` = `p`.`id`
        LEFT JOIN `countries` AS `y` ON `p`.`countryId` = `y`.`id`
        LEFT JOIN `currencies` AS `d` ON `y`.`defaultCurrency` = `d`.`id`
    WHERE (`c`.`id` = CityId) LIMIT 1
END;
</code>```

Unfortunately, I'm getting errors on the Table names in the SELECT query ("Error: 1327: Undeclared variable: c"). So how am I supposed to build this SELECT such that it works as intended, without referencing the table names?

I tried removing all the "AS x" statements, and using just the actual table names instead, but, of course, I get the exact same error, just with the variable name replaced by the table name...

I'm sure that this is an obvious/simple thing to a regular (My)SQL developer, but it seems extraordinarily contra-intuitive to me so far..

PS: If it matters, I'm using MySQL Workbench to do this.

答:
I believe your syntax is incorrect; please try placing the INTO below the select as follows;</p>

```<code>DELIMITER //

CREATE PROCEDURE `DatabaseName.GetCityIdentity`
(
IN  CityId bigint(20) unsigned,
OUT
    `id`            BIGINT(20) UNSIGNED,
    `provId`        BIGINT(20) UNSIGNED,
    `countryId`     BIGINT(20) UNSIGNED,
    `currencyId`    BIGINT(20) UNSIGNED,
    `cityName`      VARCHAR(64),
    `latitude`      DECIMAL(10,6),
    `longitude`     DECIMAL(10,6),
    `provName`      VARCHAR(64),
    `provAbbr`      VARCHAR(4),
    `countryName`   VARCHAR(64),
    `countryAbbr`   VARCHAR(4),
    `currencyName`  VARCHAR(64),
    `currencySymbol`VARCHAR(8),
    `fullName`      VARCHAR(256),
    `abbrName`      VARCHAR(80)
)
BEGIN
    SELECT
        `cities`.`id`,
        `cities`.`name`,
        `cities`.`provId`,
        `cities`.`latitude`,
        `cities`.`longitude`,
        `provinces`.`name`,
        `provinces`.`abbr`,
        `provinces`.`countryId`,
        `countries`.`name`,
        `countries`.`abbr`,
        `countries`.`defaultCurrency`,
        `currencies`.`name`,
        `currencies`.`symbol`,
        CONCAT(`cities`.`name`, ', ', `provinces`.`name`, ', ', `country`.`Name`),
        CONCAT(`cities`.`name`, ', ', `provinces`.`abbr`, ', ', `country`.`abbr`)
    INTO `id`, `cityName`, `provId`, `latitude`, `longitude`, `provName`,
          `provAbbr`, `countryId`, `countryName`, `countryAbbr`,
          `currencyId`, `currencyName`, `currencySymbol`, `fullName`,
          `abbrName`
    FROM `cities`
        LEFT JOIN `provinces` ON `cities`.`provId` = `provinces`.`id`
        LEFT JOIN `countries` ON `provinces`.`countryId` = `countries`.`id`
        LEFT JOIN `currencies` ON `countries`.`defaultCurrency` = `currencies`.`id`
    WHERE (`cities`.`id` = CityId) LIMIT 1;
END //

DELIMITER ;
</code>```

Body:
I'm trying to create my first set of MySQL procedures. In this case, I want to have a simple call collate relevant information from 4 tables into a single result and return a discrete selection of fields as the result. To this end, I've written this:

CREATE PROCEDURE `DatabaseName.GetCityIdentity`
(
IN  CityId BIGINT(20) UNSIGNED,
OUT
    `id`            BIGINT(20) UNSIGNED,
    `provId`        BIGINT(20) UNSIGNED,
    `countryId`     BIGINT(20) UNSIGNED,
    `currencyId`    BIGINT(20) UNSIGNED,
    `cityName`      VARCHAR(64),
    `latitude`      DECIMAL(10,6),
    `longitude`     DECIMAL(10,6),
    `provName`      VARCHAR(64),
    `provAbbr`      VARCHAR(4),
    `countryName`   VARCHAR(64),
    `countryAbbr`   VARCHAR(4),
    `currencyName`  VARCHAR(64),
    `currencySymbol`VARCHAR(8),
    `fullName`      VARCHAR(256),
    `abbrName`      VARCHAR(80)
)
BEGIN
    SELECT
        `c`.`id` INTO `id`, `c`.`name` INTO `cityName`, `c`.`provId` INTO `provId`, `c`.`latitude` INTO`latitude`, `c`.`longitude` INTO `longitude`,
        `p`.`name` INTO `provName`, `p`.`abbr` INTO `provAbbr`, `p`.`countryId` INTO `countryId`,
        `y`.`name` INTO `countryName`, `y`.`abbr` INTO `countryAbbr`, `y`.`defaultCurrency` INTO `currencyId`,
        `d`.`name` INTO `currencyName`, `d`.`symbol` INTO `currencySymbol`,
        CONCAT(`c`.`name`, ', ', `p`.`name`, ', ', `y`.`Name`) INTO `fullName`,
        CONCAT(`c`.`name`, ', ', `p`.`abbr`, ', ', `y`.`abbr`) INTO `abbrName`
    FROM `cities` AS `c`
        LEFT JOIN `provinces` AS `p` ON `c`.`provId` = `p`.`id`
        LEFT JOIN `countries` AS `y` ON `p`.`countryId` = `y`.`id`
        LEFT JOIN `currencies` AS `d` ON `y`.`defaultCurrency` = `d`.`id`
    WHERE (`c`.`id` = CityId) LIMIT 1
END;

Unfortunately, I'm getting errors on the Table names in the SELECT query ("Error: 1327: Undeclared variable: c"). So how am I supposed to build this SELECT such that it works as intended, without referencing the table names?

I tried removing all the "AS x" statements, and using just the actual table names instead, but, of course, I get the exact same error, just with the variable name replaced by the table name...

I'm sure that this is an obvious/simple thing to a regular (My)SQL developer, but it seems extraordinarily contra-intuitive to me so far..

PS: If it matters, I'm using MySQL Workbench to do this.

Body:
I believe your syntax is incorrect; please try placing the INTO below the select as follows;

DELIMITER //

CREATE PROCEDURE `DatabaseName.GetCityIdentity`
(
IN  CityId bigint(20) unsigned,
OUT
    `id`            BIGINT(20) UNSIGNED,
    `provId`        BIGINT(20) UNSIGNED,
    `countryId`     BIGINT(20) UNSIGNED,
    `currencyId`    BIGINT(20) UNSIGNED,
    `cityName`      VARCHAR(64),
    `latitude`      DECIMAL(10,6),
    `longitude`     DECIMAL(10,6),
    `provName`      VARCHAR(64),
    `provAbbr`      VARCHAR(4),
    `countryName`   VARCHAR(64),
    `countryAbbr`   VARCHAR(4),
    `currencyName`  VARCHAR(64),
    `currencySymbol`VARCHAR(8),
    `fullName`      VARCHAR(256),
    `abbrName`      VARCHAR(80)
)
BEGIN
    SELECT
        `cities`.`id`,
        `cities`.`name`,
        `cities`.`provId`,
        `cities`.`latitude`,
        `cities`.`longitude`,
        `provinces`.`name`,
        `provinces`.`abbr`,
        `provinces`.`countryId`,
        `countries`.`name`,
        `countries`.`abbr`,
        `countries`.`defaultCurrency`,
        `currencies`.`name`,
        `currencies`.`symbol`,
        CONCAT(`cities`.`name`, ', ', `provinces`.`name`, ', ', `country`.`Name`),
        CONCAT(`cities`.`name`, ', ', `provinces`.`abbr`, ', ', `country`.`abbr`)
    INTO `id`, `cityName`, `provId`, `latitude`, `longitude`, `provName`,
          `provAbbr`, `countryId`, `countryName`, `countryAbbr`,
          `currencyId`, `currencyName`, `currencySymbol`, `fullName`,
          `abbrName`
    FROM `cities`
        LEFT JOIN `provinces` ON `cities`.`provId` = `provinces`.`id`
        LEFT JOIN `countries` ON `provinces`.`countryId` = `countries`.`id`
        LEFT JOIN `currencies` ON `countries`.`defaultCurrency` = `currencies`.`id`
    WHERE (`cities`.`id` = CityId) LIMIT 1;
END //

DELIMITER ;


问:
Generate Logs in a new directory daily according to each hour in log4j2?
I want to create a directory {date}.dir and inside this directory, I need logs for each hour in a new separate file as 0000.log, 0100.log ...2300.log.

I used rolling file appender, but it only work to create a single log file and compressed the last one. I'm using time-based triggering policy with interval = 1, which gives me a new file every day and compress the last day's.

<RollingFile name="eventLogger" fileName="/Log/webservices/linpub.log" filePattern="/Log/webservices/linpub-%d{MM-dd-yyyy}.log.gz">
        <PatternLayout>
                <Pattern>%d{MM/dd/yy HH:mm:ss.SSS} %-5p [%t] %c{1} %X{trioOperation} - %m %throwable %n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
</RollingFile>
```

I want to create a new file with name as linpub-{date}.dir and inside the file, there should be a log file for each hour.

I'm using log4j2 2.3 version.

答:
In case of <TimeBasedTriggeringPolicy interval="1" modulate="true"/>, here interval="1" means 1 day not 1 hour. If you want to achieve 1 hour basis, you have to use CronTrigger base policy. Find below the code.

```<code><CronTriggeringPolicy schedule="0 0 0/1 1/1 * ? *" evaluateOnStartup="true"/>
</code>```

Replace the following line with the above one.

```<code><TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</code>```

Also change the file name patten with this yyyy-MM-dd-HH so that you will be able to know for hourly basic. Please check and test it.

Body:
I want to create a directory {date}.dir and inside this directory, I need logs for each hour in a new separate file as 0000.log, 0100.log ...2300.log.

I used rolling file appender, but it only work to create a single log file and compressed the last one. I'm using time-based triggering policy with interval = 1, which gives me a new file every day and compress the last day's.

<RollingFile name="eventLogger" fileName="/Log/webservices/linpub.log" filePattern="/Log/webservices/linpub-%d{MM-dd-yyyy}.log.gz">
        <PatternLayout>
                <Pattern>%d{MM/dd/yy HH:mm:ss.SSS} %-5p [%t] %c{1} %X{trioOperation} - %m %throwable %n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>
</RollingFile>

I want to create a new file with name as linpub-{date}.dir and inside the file, there should be a log file for each hour.

I'm using log4j2 2.3 version.

Body:
In case of <TimeBasedTriggeringPolicy interval="1" modulate="true"/>, here interval="1" means 1 day not 1 hour. If you want to achieve 1 hour basis, you have to use CronTrigger base policy. Find below the code.

<CronTriggeringPolicy schedule="0 0 0/1 1/1 * ? *" evaluateOnStartup="true"/>

Replace the following line with the above one.

<TimeBasedTriggeringPolicy interval="1" modulate="true"/>

Also change the file name patten with this yyyy-MM-dd-HH so that you will be able to know for hourly basic. Please check and test it.


问:
PHP json_decode notation issue
I am having an issue dealing with the notation used in a JSON file I am trying parse. Some of the nodes have . (periods) in the names which escapes object-notation
($json = $article->rssFeed.url;)

How would I go about selecting the nodes. Do I need to str_replace the .(periods), or is there some other notation I can use? Here is a snippet of the JSON:

```<code>"docs": [{"rssFeed.type": "news", "rssFeed.url": "http://www.example.com/",  "score": 1.0 }]
</code>```

答:
@eWolf: you are still right, php is almost like javascript as its C like nature.

```<code>$object = json_decode('{"docs": [{"rssFeed.type": "news",
                                  "rssFeed.url": "http://www.example.com/",
                                  "score": 1.0 }]}', TRUE);
</code>```

Note: the 2nd argument to json_decode(), TRUE. It forces the function to return an associative array.

Now $object['rssFeed.type'] can be used.

ContentLicense: CC BY-SA 2.5

Title: PHP json_decode notation issue

Body:
I am having an issue dealing with the notation used in a JSON file I am trying parse. Some of the nodes have . (periods) in the names which escapes object-notation
($json = $article->rssFeed.url;)

How would I go about selecting the nodes. Do I need to str_replace the .(periods), or is there some other notation I can use? Here is a snippet of the JSON:

"docs": [{"rssFeed.type": "news", "rssFeed.url": "http://www.example.com/",  "score": 1.0 }]

Body:
@eWolf: you are still right, php is almost like javascript as its C like nature.

$object = json_decode('{"docs": [{"rssFeed.type": "news",
                                  "rssFeed.url": "http://www.example.com/",
                                  "score": 1.0 }]}', TRUE);

Note: the 2nd argument to json_decode(), TRUE. It forces the function to return an associative array.

Now $object['rssFeed.type'] can be used.

ContentLicense: CC BY-SA 3.0


问:
Getting 'relation "schemaversions" does not exist error'
Im trying to use the example code from dbup converted to postgres.

Below is the code.

```<code>using System;
using System.Linq;
using System.Reflection;
using DbUp;

namespace GeoServerDbManager
{
    //"Host = 1.1.1.1; User Id = postgres; Password = postgres; Database = osmdev; Port = 5432"
    class Program
    {
        static int Main(string[] args)
        {
            var connectionString =
                args.FirstOrDefault()
                ?? "Host = 1.1.1.1; User Id = postgres; Password = postgres; Database = osmdev; Port = 5432";
            EnsureDatabase.For.PostgresqlDatabase(connectionString);
            var upgrader =
                DeployChanges.To
                    .PostgresqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
#if DEBUG
                Console.ReadLine();
#endif
                return -1;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return 0;
        }
    }
}
</code>```

The database doesnt exist when I run this.
I keep getting the error:

```<code>Script block number: 0; Message: 42P01: relation "schemaversions" does not exist
Npgsql.PostgresException (0x80004005): 42P01: relation "schemaversions" does not exist
</code>```

The tables do get created and so does the schemaversions table but the schemaversions table is empty at the end of the script.

答:
I know this is an old question but today I ran into the same problem and since there is no answer yet I'm answering for future reference:

I found that DbUp is trying to create a "schemaversions" but there is no default schema set. This results in the error:

Getting 'relation "schemaversions" does not exist error'

Setting the default schema fixed the problem for me:

builder.JournalToPostgresqlTable("SCHEMA_NAME", "schemaversions")

Body:
Im trying to use the example code from dbup converted to postgres.

Below is the code.

using System;
using System.Linq;
using System.Reflection;
using DbUp;

namespace GeoServerDbManager
{
    //"Host = 1.1.1.1; User Id = postgres; Password = postgres; Database = osmdev; Port = 5432"
    class Program
    {
        static int Main(string[] args)
        {
            var connectionString =
                args.FirstOrDefault()
                ?? "Host = 1.1.1.1; User Id = postgres; Password = postgres; Database = osmdev; Port = 5432";
            EnsureDatabase.For.PostgresqlDatabase(connectionString);
            var upgrader =
                DeployChanges.To
                    .PostgresqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
#if DEBUG
                Console.ReadLine();
#endif
                return -1;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return 0;
        }
    }
}

The database doesnt exist when I run this.
I keep getting the error:

Script block number: 0; Message: 42P01: relation "schemaversions" does not exist
Npgsql.PostgresException (0x80004005): 42P01: relation "schemaversions" does not exist

The tables do get created and so does the schemaversions table but the schemaversions table is empty at the end of the script.


问:
Devise: Duplicate routing entries despite my custom entries
When I run rake routes | grep sessions I'm getting duplicate entries despite already having my own settings.

Here's my output: (these aren't all of the duplicates btw.)

```<code>    new_user_session GET    /users/sign_in(.:format)  devise/sessions#new
        user_session POST   /users/sign_in(.:format)  devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
               login GET    /login(.:format)          devise/sessions#new
                     POST   /login(.:format)          devise/sessions#create
              logout DELETE /logout(.:format)         devise/sessions#destroy
</code>```

The top three are the default routing settings from Devise and the bottom three are the ones I've added in config/routes.rb.

Here is sample of my config/routes.rb file pertaining to Devise:

```<code>Rails.application.routes.draw do
  root to: 'pages#index'

  # Users
  devise_for :users, controllers: {
     # I override a few actions in my own controller so I needed this
     registrations: 'users/registrations',
  }

  # FYI: as is an alias for devise_scope
  as :user do
    # devise/sessions_controller handlers
    get    'login',           to: 'devise/sessions#new'
    post   'login',           to: 'devise/sessions#create'
    delete 'logout',          to: 'devise/sessions#destroy'

    #.... other registrations controller settings that are also getting duplicated
  end

  # .... all my other application routes
end
</code>```

I guess what I'm asking is, how to I suppress the default routes from Devise since I've created my own? If you need more of my rake routes output or config/routes.rb file I can submit the whole thing.

EDIT:

Ok looks like I need to add a :path_names hash to my devise_for :users block. From https://devhints.io/devise, I can see a selection of options for the paths at the end of the page. Also removing the :path option altogether gives me an unaliased version which matches what I wanted.

Here's what I had to do to get it (mostly) right:

```<code>devise_for :users, :path => '',
  :path_names => {
    :sign_in => 'sign-in',
    :sign_out => 'sign-out',
    :password => '',
    :confirmation => 'verification',
    :unlock => 'unblock',
    :registration => 'register',
    :sign_up => '' },
    # ignore this, changing this probably wont fix anything plus I need it.
    controllers: {
     registrations: 'users/registrations'
  }
</code>```

Its not totally perfect so Ill give the answer to anyone who can show me how to get:

```<code>                    root GET    /                          pages#index
        new_user_session GET    /sign-in(.:format)         devise/sessions#new
            user_session POST   /sign-in(.:format)         devise/sessions#create
    destroy_user_session DELETE /sign-out(.:format)        devise/sessions#destroy
cancel_user_registration GET    /register/cancel(.:format) users/registrations#cancel
   new_user_registration GET    /register(.:format)        users/registrations#new
  edit_user_registration GET    /register/edit(.:format)   users/registrations#edit
       user_registration PATCH  /register(.:format)        users/registrations#update
                          PUT    /register(.:format)       users/registrations#update
                          DELETE /register(.:format)       users/registrations#destroy
                          POST   /register(.:format)       users/registrations#create
                 password GET    /password(.:format)       devise/passwords#new
           reset_password GET    /reset-password(.:format) devise/passwords#edit
                          PATCH  /reset-password(.:format) devise/passwords#update
                          PUT    /reset-password(.:format) devise/passwords#update
                          POST   /password(.:format)       devise/passwords#create

 I DONT WANT THE FOLLOWING IN MY ROUTES:
       new_user_password GET    /new(.:format)             devise/passwords#new
      edit_user_password GET    /edit(.:format)            devise/passwords#edit
           user_password PATCH  /                          devise/passwords#update
                         PUT    /                          devise/passwords#update
                         POST   /                          devise/passwords#create
</code>```

I could change :password => '' to :password => 'reset-password' but then I get these:

```<code> new_user_password GET  /reset-password/new(.:format)  devise/passwords#new
edit_user_password GET  /reset-password/edit(.:format) devise/passwords#edit
                   POST /reset-password(.:format)      devise/passwords#create
</code>```

When what I want is this:

```<code> new_user_password GET  /password(.:format)       devise/passwords#new
edit_user_password GET  /reset-password(.:format) devise/passwords#edit
                   POST /password(.:format)       devise/passwords#create
</code>```

答:
Ok looks like I need to add a :path_names hash to my devise_for :users block. From https://devhints.io/devise, I can see a selection of options for the paths at the end of the page. Also removing the :path option altogether gives me an unaliased version which matches what I wanted.

EDIT:

On top of what I found (and included in my question) I also found the :skip option. Someone has already asked a similar question that I have and the perfect answer to this (telling Devise not to generate ANY of the routes I want to override) is here:

https://stackoverflow.com/a/46900434/43792

Body:
When I run rake routes | grep sessions I'm getting duplicate entries despite already having my own settings.

Here's my output: (these aren't all of the duplicates btw.)

    new_user_session GET    /users/sign_in(.:format)  devise/sessions#new
        user_session POST   /users/sign_in(.:format)  devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
               login GET    /login(.:format)          devise/sessions#new
                     POST   /login(.:format)          devise/sessions#create
              logout DELETE /logout(.:format)         devise/sessions#destroy

The top three are the default routing settings from Devise and the bottom three are the ones I've added in config/routes.rb.

Here is sample of my config/routes.rb file pertaining to Devise:

Rails.application.routes.draw do
  root to: 'pages#index'

  # Users
  devise_for :users, controllers: {
     # I override a few actions in my own controller so I needed this
     registrations: 'users/registrations',
  }

  # FYI: as is an alias for devise_scope
  as :user do
    # devise/sessions_controller handlers
    get    'login',           to: 'devise/sessions#new'
    post   'login',           to: 'devise/sessions#create'
    delete 'logout',          to: 'devise/sessions#destroy'

    #.... other registrations controller settings that are also getting duplicated
  end

  # .... all my other application routes
end

I guess what I'm asking is, how to I suppress the default routes from Devise since I've created my own? If you need more of my rake routes output or config/routes.rb file I can submit the whole thing.

EDIT:

Ok looks like I need to add a :path_names hash to my devise_for :users block. From https://devhints.io/devise, I can see a selection of options for the paths at the end of the page. Also removing the :path option altogether gives me an unaliased version which matches what I wanted.

Here's what I had to do to get it (mostly) right:

devise_for :users, :path => '',
  :path_names => {
    :sign_in => 'sign-in',
    :sign_out => 'sign-out',
    :password => '',
    :confirmation => 'verification',
    :unlock => 'unblock',
    :registration => 'register',
    :sign_up => '' },
    # ignore this, changing this probably wont fix anything plus I need it.
    controllers: {
     registrations: 'users/registrations'
  }

Its not totally perfect so Ill give the answer to anyone who can show me how to get:

                    root GET    /                          pages#index
        new_user_session GET    /sign-in(.:format)         devise/sessions#new
            user_session POST   /sign-in(.:format)         devise/sessions#create
    destroy_user_session DELETE /sign-out(.:format)        devise/sessions#destroy
cancel_user_registration GET    /register/cancel(.:format) users/registrations#cancel
   new_user_registration GET    /register(.:format)        users/registrations#new
  edit_user_registration GET    /register/edit(.:format)   users/registrations#edit
       user_registration PATCH  /register(.:format)        users/registrations#update
                          PUT    /register(.:format)       users/registrations#update
                          DELETE /register(.:format)       users/registrations#destroy
                          POST   /register(.:format)       users/registrations#create
                 password GET    /password(.:format)       devise/passwords#new
           reset_password GET    /reset-password(.:format) devise/passwords#edit
                          PATCH  /reset-password(.:format) devise/passwords#update
                          PUT    /reset-password(.:format) devise/passwords#update
                          POST   /password(.:format)       devise/passwords#create

 I DONT WANT THE FOLLOWING IN MY ROUTES:
       new_user_password GET    /new(.:format)             devise/passwords#new
      edit_user_password GET    /edit(.:format)            devise/passwords#edit
           user_password PATCH  /                          devise/passwords#update
                         PUT    /                          devise/passwords#update
                         POST   /                          devise/passwords#create

I could change :password => '' to :password => 'reset-password' but then I get these:

 new_user_password GET  /reset-password/new(.:format)  devise/passwords#new
edit_user_password GET  /reset-password/edit(.:format) devise/passwords#edit
                   POST /reset-password(.:format)      devise/passwords#create

When what I want is this:

 new_user_password GET  /password(.:format)       devise/passwords#new
edit_user_password GET  /reset-password(.:format) devise/passwords#edit
                   POST /password(.:format)       devise/passwords#create


问:
why form_for does not work for me
(ruby 1.9.2 rails 3.0.6)

I am new to ROR, sorry for my simple question.

I have a form and a controller, when i launch my app, i can see the log have been displayed.. however there are exception when rendering the view...

Everything should look just fine.. what is the problem? how can I fix it?

Thanks.

```<code>undefined method `users_path' for #<#<Class:0x47c7678>:0x47c6118>
Extracted source (around line #2):

1: <h1>Welcome Aboard</h1>
2: <%= form_for(@user) do |f| %>
3:   <table>
4:     <tr>
5:       <td><%= f.label :username %></td>

class RegisterController < ApplicationController

  def sign_up
    logger.debug("sign_up inoked")

    @user = User.new

    logger.debug("sign_up finished")
  end

end
</code>```

views/register/sign_up.html.erb

```<code><%= form_for(@user) do |f| %>
  <table>
    <tr>
      <td><%= f.label :username %></td>
      <td><%= f.text_field :username %></td>
    </tr>
    <tr>
      <td><%= f.label :password %></td>
      <td><%= f.password_field :password %></td>
    </tr>
    <tr>
      <td><%= f.label :password_confirmation %></td>
      <td><%= f.password_field :password_confirmation %></td>
    </tr>
    <tr>
      <td colspan="2"></td>
    </tr>
    <tr>
      <td colspan="2"><%= f.submit "Sign up" %></td>
    </tr>
  </table>
<% end %>
</code>```

答:
It seems that you do not have the appropriate routes. Do you have a line like :

```<code>resources :users
</code>```

in your routes.rb file ? If not try adding that please. Or just create the particular users_path named route.

Title: why form_for does not work for me

Body:
(ruby 1.9.2 rails 3.0.6)

I am new to ROR, sorry for my simple question.

I have a form and a controller, when i launch my app, i can see the log have been displayed.. however there are exception when rendering the view...

Everything should look just fine.. what is the problem? how can I fix it?

Thanks.

undefined method `users_path' for #<#<Class:0x47c7678>:0x47c6118>
Extracted source (around line #2):

1:
Welcome Aboard

2: <%= form_for(@user) do |f| %>
3:

4:

5:       <%= f.label :username %>

class RegisterController < ApplicationController

  def sign_up
    logger.debug("sign_up inoked")

    @user = User.new

    logger.debug("sign_up finished")
  end

end

views/register/sign_up.html.erb

<%= form_for(@user) do |f| %>

      <%= f.label :username %>
      <%= f.text_field :username %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation %>
      <%= f.password_field :password_confirmation %>

      <%= f.submit "Sign up" %>

<% end %>

Body:
It seems that you do not have the appropriate routes. Do you have a line like :

resources :users

in your routes.rb file ? If not try adding that please. Or just create the particular users_path named route.


问:
TypeError: Cannot read property 'push' of undefined in node-red function node
I am using node-red, the function node to generate some random matrix. However, every time when I deploy the node, the error "TypeError: Cannot read property 'push' of undefined" will appear, can someone help me to take a look at the code?</p>

```<code>// Generate some random data
// See https://www.patrick-wied.at/static/heatmapjs/example-minimal-config.html

var len = 200;

msg.payload = [];

while (len--) {
  var value = Math.floor(Math.random() * 100);
  msg.payload.push(value);
}

return msg;
</code>```

答:
Initialise msg before </p>

```<code>var len = 200;
var msg = {};
msg.payload = [];
</code>```

Body:
I am using node-red, the function node to generate some random matrix. However, every time when I deploy the node, the error "TypeError: Cannot read property 'push' of undefined" will appear, can someone help me to take a look at the code?

// Generate some random data
// See https://www.patrick-wied.at/static/heatmapjs/example-minimal-config.html

var len = 200;

msg.payload = [];

while (len--) {
  var value = Math.floor(Math.random() * 100);
  msg.payload.push(value);
}

return msg;

Body:
Initialise msg before

var len = 200;
var msg = {};
msg.payload = [];


问:
ag: search exact string, not a pattern

My Problem

I'm searching for Application(service) in my files using ag. Since ag treats strings as regular expression patterns, I have to escape the parens and use:

```<code>ag 'Application\(service\)'
</code>```

This is cumbersome and easy to miss, especially when there are multiple regex symbols in my search.

What have I tried

Search the manual

Escape the regex chars (works, but error-prone)

My Question

How can I instruct ag to treat the search term as a literal string, instead of a regex pattern?

答:
The option you're looking for is

-Q --literal: Do not parse PATTERN as a regular expression. Try to match it literally.

@ https://github.com/ggreer/the_silver_searcher/blob/master/doc/ag.1.md:

Title: ag: search exact string, not a pattern

Body:
My Problem

I'm searching for Application(service) in my files using ag. Since ag treats strings as regular expression patterns, I have to escape the parens and use:

ag 'Application\(service\)'

This is cumbersome and easy to miss, especially when there are multiple regex symbols in my search.

What have I tried

Search the manual

Escape the regex chars (works, but error-prone)

My Question

How can I instruct ag to treat the search term as a literal string, instead of a regex pattern?


问:
Need a regex for URL check?
I need a regex for a URL string.

My URL string goes like

https colon // string dot string / string (It does not contain any space in between)

Title: Need a regex for URL check?

Body:
From https://gist.github.com/jacksonfdam/3000275
I found :

^http(s)?:\/\/((\d+\.\d+\.\d+\.\d+)|(([\w-]+\.)+([a-z,A-Z][\w-]*)))(:[1-9][0-9]*)?(\/([\w-.\/:%+@&=]+[\w- .\/?:%+@&=]*)?)?(#(.*))?$/i


问:
Writing Scrapy Python Output to JSON file
I'm new to Python and web scraping. In this program I want to write final output (product name and price from all 3 links) to JSON file. Please help!</p>

```<code>    import scrapy
    from time import sleep
    import csv, os, json
    import random

    class spider1(scrapy.Spider):
        name = "spider1"

        def start_requests(self):
            list = [
                "https://www. example.com/item1",
                "https://www. example.com/item2",
                "https://www. example.com/item3"]

            for i in list:
                yield scrapy.Request(i, callback=self.parse)
                sleep(random.randint(0, 5))

        def parse(self, response):
            product_name = response.css('#pd-h1-cartridge::text')[0].extract()
            product_price = response.css(
                '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
                '::text')[3].extract()

            name = str(product_name).strip()
            price = str(product_price).replace('\n', "")

data = {name, price}

yield data

extracted_data = []
    while i < len(data):

        extracted_data.append()
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)
</code>```

答:
There is actually a scrapy command to do this (Read):

```<code>scrapy crawl <spidername> -o <outputname>.<format>
scrapy crawl quotes -o quotes.json

</code>```

But since you asked for the python code, I came up with this:

```<code>    def parse(self, response):
        with open("data_file.json", "w") as filee:
            filee.write('[')
            for index, quote in enumerate(response.css('div.quote')):
                json.dump({
                    'text': quote.css('span.text::text').extract_first(),
                    'author': quote.css('.author::text').get(),
                    'tags': quote.css('.tag::text').getall()
                }, filee)
                if index < len(response.css('div.quote')) - 1:
                    filee.write(',')
            filee.write(']')
</code>```

Which simply does the same thing as the scrapy output command for json files.

Body:
I'm new to Python and web scraping. In this program I want to write final output (product name and price from all 3 links) to JSON file. Please help!

    import scrapy
    from time import sleep
    import csv, os, json
    import random

    class spider1(scrapy.Spider):
        name = "spider1"

        def start_requests(self):
            list = [
                "https://www. example.com/item1",
                "https://www. example.com/item2",
                "https://www. example.com/item3"]

            for i in list:
                yield scrapy.Request(i, callback=self.parse)
                sleep(random.randint(0, 5))

        def parse(self, response):
            product_name = response.css('#pd-h1-cartridge::text')[0].extract()
            product_price = response.css(
                '.product-price .is-current, .product-price_total .is-current, .product-price_total ins, .product-price ins').css(
                '::text')[3].extract()

            name = str(product_name).strip()
            price = str(product_price).replace('\n', "")

data = {name, price}

yield data

extracted_data = []
    while i < len(data):

        extracted_data.append()
        sleep(5)
    f = open('data.json', 'w')
    json.dump(extracted_data, f, indent=4)

Body:
There is actually a scrapy command to do this (Read):

scrapy crawl <spidername> -o <outputname>.<format>
scrapy crawl quotes -o quotes.json

But since you asked for the python code, I came up with this:

    def parse(self, response):
        with open("data_file.json", "w") as filee:
            filee.write('[')
            for index, quote in enumerate(response.css('div.quote')):
                json.dump({
                    'text': quote.css('span.text::text').extract_first(),
                    'author': quote.css('.author::text').get(),
                    'tags': quote.css('.tag::text').getall()
                }, filee)
                if index < len(response.css('div.quote')) - 1:
                    filee.write(',')
            filee.write(']')

Which simply does the same thing as the scrapy output command for json files.


问:
Finding the running median
I have to find the running median as per this problem:
https://www.hackerrank.com/challenges/ctci-find-the-running-median

I am trying to implement two heaps. A min heap which stores the elements lesser than the current median and a max heap which stores items greater than the current median.

The median keeps changing, and the difference in number of elements in both heaps does not exceed 1.

My code however is not being accepted. However it has passed test cases I could think of.

Please only read the main function and the update median function!
Any help is appreciated.

```<code>#include<bits/stdc++.h>
#define pb push_back
using namespace std;

class max_heap{
private:
vector<int> items;
int size;

public:
max_heap(){
    size=0;
}
int left(int parent){   return (parent*2 + 1);  }
int right(int parent){  return (parent*2 + 2);  }
int parent(int pos){    return pos<=0 ? 0 : (pos-1)/2;      }
int getmax(){           return items[0];            }
int peek(int pos){  return items[pos];}
int length(){           return items.size();}

void swap(int pos1, int pos2){
    int tmp=items[pos1];
    items[pos1]=items[pos2];
    items[pos2]=tmp;
    return;
}
void insert(int key)
{

    if(items.size()==size)
        items.pb(key);
    else
        items[size]=key;

    //fixing items property
    int tmp=size;
    while(items[0]!=key && items[parent(tmp)] < key ){
        swap( parent(tmp), tmp);

        tmp=parent(tmp);
    }
    size++;

}

int pop(){

    if(size==0)
        return 0;
    int ans=getmax();
    size--;
    items[0]=items[size];

    //fix items
    int i=0;
    while(i<size-1){
        bool a = items[i] < items[right(i)];
        bool b = items[i] < items[left(i)];

        if( a && b)
        {
            if( items[left(i)] < items[right(i)] )
                swap(i,left(i));
            else swap(i,right(i));

        }
        else if(a)
            swap(i,right(i));
        else if(b)
            swap(i,left(i));
        else break;

    }
    return ans;
}

void print(){
    for (int i = 0; i < items.size(); ++i)
            cout<<items[i]<<" ";
    cout<<endl;
}
};

class min_heap{
private:
vector<int> items;
int size;

public:
min_heap(){
    size=0;
}
int left(int parent){   return (parent*2 + 1);  }
int right(int parent){  return (parent*2 + 2);  }
int parent(int pos){    return pos<=0 ? 0 : (pos-1)/2;      }
int getmin(){           return items[0];            }
int peek(int pos){  return items[pos];}
int length(){           return items.size();}

void swap(int pos1, int pos2){
    int tmp=items[pos1];
    items[pos1]=items[pos2];
    items[pos2]=tmp;
    return;
}
void insert(int key)
{

    if(items.size()==size)
        items.pb(key);
    else
        items[size]=key;

    //fixing items property
    int tmp=size;
    while(items[0]!=key && items[parent(tmp)] > key ){
        swap( parent(tmp), tmp);

        tmp=parent(tmp);
    }
    size++;

}

int pop(){

    if(size==0)
        return 0;
    int ans=getmin();
    size--;
    items[0]=items[size];

    //fix items
    int i=0;
    while(i<size-1){
        bool a = items[i] > items[right(i)];
        bool b = items[i] > items[left(i)];

        if( a && b)
        {
            if( items[left(i)] < items[right(i)] )
                swap(i,left(i));
            else swap(i,right(i));

        }
        else if(a)
            swap(i,right(i));
        else if(b)
            swap(i,left(i));
        else break;

    }
    return ans;
}

void print(){
    for (int i = 0; i < items.size(); ++i)
            cout<<items[i]<<" ";
    cout<<endl;
}
};

double update_median(int element, int median, min_heap &mn_heap, max_heap &mx_heap)
{

int path = mx_heap.length() - mn_heap.length();
    double ans=0.0;

switch(path){

    case 0:

    if( element >  median ){
        //push to right heap..ie the min heap
        mn_heap.insert(element);
        ans= mn_heap.getmin();
    }
    else
    {
        //push to left heap....ie max heap
        mx_heap.insert(element);
        ans= mx_heap.getmax();
    }

    break;

    case 1:     //max heap is greater ie left

    if( element >  median )
    {   //push to right heap...min heap

        mn_heap.insert(element);
        ans=(mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    else
    {
        mn_heap.insert(mx_heap.pop());
        mx_heap.insert(element);
        ans= (mn_heap.getmin() + mx_heap.getmax()) / 2.0;
    }

    break;

    case -1: // min heap greater ie right

    if( element >  median )
    {   //push to right heap...min heap

        mx_heap.insert(mn_heap.pop());
        mn_heap.insert(element);
        ans=(mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    else
    {

        mx_heap.insert(element);
        ans= (mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    break;

}

return ans;

}

int main(){

    cout.sync_with_stdio(false);
    int el;
    cin>>el;

    double median=0.0;

    min_heap *a = new min_heap(); //items less than median
    max_heap *b = new max_heap(); //items more than median

    while(el--){
        int element;
        cin>>element;

        median= update_median(element,median,*a,*b);

        printf("%.1lf\n", median);
    }
}
</code>```

答:
Find the Running Median using Java - Hackerrank Solution

```<code>package com.syed.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Solution {

    static double[] runningMedian(int[] a) {

        int[] temp = new int[a.length];
        double[] resultArray = new double[a.length];
        int counter = 0;

        for (int i = 0; i < a.length; i++) {
            temp[i] = a[i];
            counter++;

            if (i == 0) {
                resultArray[i] = (double) temp[i];
                System.out.println("i : " + i + "  " + Arrays.toString(temp));
            } else {

                Arrays.sort(temp, 0, i + 1);
                System.out.println("i : " + i + "  " + Arrays.toString(temp));

                int val = counter / 2;

                if (counter % 2 == 0)
                    resultArray[i] = (temp[val] + temp[val - 1]) / 2.0;
                else
                    resultArray[i] = temp[val];
            }
        }
        System.out.println("\n Result Array : " + Arrays.toString(resultArray));
        return resultArray;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("d://output.txt"));

        int aCount = Integer.parseInt(scanner.nextLine().trim());

        int[] a = new int[aCount];

        for (int aItr = 0; aItr < aCount; aItr++) {
            int aItem = Integer.parseInt(scanner.nextLine().trim());
            a[aItr] = aItem;
        }

        double[] result = runningMedian(a);

        for (int resultItr = 0; resultItr < result.length; resultItr++) {
            bufferedWriter.write(String.valueOf(result[resultItr]));

            if (resultItr != result.length - 1) {
                bufferedWriter.write("\n");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();
    }
}
</code>```

input:

```<code>6
12
4
5
3
8
7
</code>```

output:

```<code>Result Array : [12.0, 8.0, 5.0, 4.5, 5.0, 6.0]
</code>```

Title: Finding the running median

Body:
I have to find the running median as per this problem:
https://www.hackerrank.com/challenges/ctci-find-the-running-median

I am trying to implement two heaps. A min heap which stores the elements lesser than the current median and a max heap which stores items greater than the current median.

The median keeps changing, and the difference in number of elements in both heaps does not exceed 1.

My code however is not being accepted. However it has passed test cases I could think of.

Please only read the main function and the update median function!
Any help is appreciated.

#include<bits/stdc++.h>
#define pb push_back
using namespace std;

class max_heap{
private:
vector<int> items;
int size;

public:
max_heap(){
    size=0;
}
int left(int parent){   return (parent*2 + 1);  }
int right(int parent){  return (parent*2 + 2);  }
int parent(int pos){    return pos<=0 ? 0 : (pos-1)/2;      }
int getmax(){           return items[0];            }
int peek(int pos){  return items[pos];}
int length(){           return items.size();}

void swap(int pos1, int pos2){
    int tmp=items[pos1];
    items[pos1]=items[pos2];
    items[pos2]=tmp;
    return;
}
void insert(int key)
{

    if(items.size()==size)
        items.pb(key);
    else
        items[size]=key;

    //fixing items property
    int tmp=size;
    while(items[0]!=key && items[parent(tmp)] < key ){
        swap( parent(tmp), tmp);

        tmp=parent(tmp);
    }
    size++;

}

int pop(){

    if(size==0)
        return 0;
    int ans=getmax();
    size--;
    items[0]=items[size];

    //fix items
    int i=0;
    while(i<size-1){
        bool a = items[i] < items[right(i)];
        bool b = items[i] < items[left(i)];

        if( a && b)
        {
            if( items[left(i)] < items[right(i)] )
                swap(i,left(i));
            else swap(i,right(i));

        }
        else if(a)
            swap(i,right(i));
        else if(b)
            swap(i,left(i));
        else break;

    }
    return ans;
}

void print(){
    for (int i = 0; i < items.size(); ++i)
            cout<<items[i]<<" ";
    cout<<endl;
}
};

class min_heap{
private:
vector<int> items;
int size;

public:
min_heap(){
    size=0;
}
int left(int parent){   return (parent*2 + 1);  }
int right(int parent){  return (parent*2 + 2);  }
int parent(int pos){    return pos<=0 ? 0 : (pos-1)/2;      }
int getmin(){           return items[0];            }
int peek(int pos){  return items[pos];}
int length(){           return items.size();}

void swap(int pos1, int pos2){
    int tmp=items[pos1];
    items[pos1]=items[pos2];
    items[pos2]=tmp;
    return;
}
void insert(int key)
{

    if(items.size()==size)
        items.pb(key);
    else
        items[size]=key;

    //fixing items property
    int tmp=size;
    while(items[0]!=key && items[parent(tmp)] > key ){
        swap( parent(tmp), tmp);

        tmp=parent(tmp);
    }
    size++;

}

int pop(){

    if(size==0)
        return 0;
    int ans=getmin();
    size--;
    items[0]=items[size];

    //fix items
    int i=0;
    while(i<size-1){
        bool a = items[i] > items[right(i)];
        bool b = items[i] > items[left(i)];

        if( a && b)
        {
            if( items[left(i)] < items[right(i)] )
                swap(i,left(i));
            else swap(i,right(i));

        }
        else if(a)
            swap(i,right(i));
        else if(b)
            swap(i,left(i));
        else break;

    }
    return ans;
}

void print(){
    for (int i = 0; i < items.size(); ++i)
            cout<<items[i]<<" ";
    cout<<endl;
}
};

double update_median(int element, int median, min_heap &mn_heap, max_heap &mx_heap)
{

int path = mx_heap.length() - mn_heap.length();
    double ans=0.0;

switch(path){

    case 0:

    if( element >  median ){
        //push to right heap..ie the min heap
        mn_heap.insert(element);
        ans= mn_heap.getmin();
    }
    else
    {
        //push to left heap....ie max heap
        mx_heap.insert(element);
        ans= mx_heap.getmax();
    }

    break;

    case 1:     //max heap is greater ie left

    if( element >  median )
    {   //push to right heap...min heap

        mn_heap.insert(element);
        ans=(mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    else
    {
        mn_heap.insert(mx_heap.pop());
        mx_heap.insert(element);
        ans= (mn_heap.getmin() + mx_heap.getmax()) / 2.0;
    }

    break;

    case -1: // min heap greater ie right

    if( element >  median )
    {   //push to right heap...min heap

        mx_heap.insert(mn_heap.pop());
        mn_heap.insert(element);
        ans=(mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    else
    {

        mx_heap.insert(element);
        ans= (mn_heap.getmin() + mx_heap.getmax()) / 2.0;

    }

    break;

}

return ans;

}

int main(){

    cout.sync_with_stdio(false);
    int el;
    cin>>el;

    double median=0.0;

    min_heap *a = new min_heap(); //items less than median
    max_heap *b = new max_heap(); //items more than median

    while(el--){
        int element;
        cin>>element;

        median= update_median(element,median,*a,*b);

        printf("%.1lf\n", median);
    }
}

Body:
Find the Running Median using Java - Hackerrank Solution

package com.syed.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Solution {

    static double[] runningMedian(int[] a) {

        int[] temp = new int[a.length];
        double[] resultArray = new double[a.length];
        int counter = 0;

        for (int i = 0; i < a.length; i++) {
            temp[i] = a[i];
            counter++;

            if (i == 0) {
                resultArray[i] = (double) temp[i];
                System.out.println("i : " + i + "  " + Arrays.toString(temp));
            } else {

                Arrays.sort(temp, 0, i + 1);
                System.out.println("i : " + i + "  " + Arrays.toString(temp));

                int val = counter / 2;

                if (counter % 2 == 0)
                    resultArray[i] = (temp[val] + temp[val - 1]) / 2.0;
                else
                    resultArray[i] = temp[val];
            }
        }
        System.out.println("\n Result Array : " + Arrays.toString(resultArray));
        return resultArray;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("d://output.txt"));

        int aCount = Integer.parseInt(scanner.nextLine().trim());

        int[] a = new int[aCount];

        for (int aItr = 0; aItr < aCount; aItr++) {
            int aItem = Integer.parseInt(scanner.nextLine().trim());
            a[aItr] = aItem;
        }

        double[] result = runningMedian(a);

        for (int resultItr = 0; resultItr < result.length; resultItr++) {
            bufferedWriter.write(String.valueOf(result[resultItr]));

            if (resultItr != result.length - 1) {
                bufferedWriter.write("\n");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();
    }
}

input:

6
12
4
5
3
8
7

output:

Result Array : [12.0, 8.0, 5.0, 4.5, 5.0, 6.0]


问:
Observe LiveData from ListView current Item
Basically i want to retrieve a int(score) generated from the current ListViewItem and assign it back to concrete TextView in my ListView.I am using SharedViewModel with LiveData but when i observe nothing happens.I am using Nav Architecture Component with Single activity.I'll be glad if someone helps.Thank u , here's some code.

public class ListFrag extends Fragment {

```<code>@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

    model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer s) {

            for (int i = 0; i < myListView.getAdapter().getCount(); i++) {

                v =  myListView.getAdapter().getView(i,null, myListView);

                finalScore = v.findViewById(R.id.finalScoreView);

                    if (s != null) {
    itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
                        myListView.setAdapter(itemAdapter);
                       finalScore.setText(String.valueOf(s));

                    }
      ((BaseAdapter)myListView.getAdapter()).notifyDataSetChanged();
            }
        }
    });
}
</code>```

public class SharedViewModel extends ViewModel
{

```<code>private MutableLiveData<Integer> currentScore = new MutableLiveData<>();

public LiveData<Integer> getCurrentScore(){
    return currentScore;
}

public void setCurrentScore(Integer finito) {
    currentScore.setValue(finito);

}
</code>```

}

public class ItemAdapter extends BaseAdapter {

```<code>LayoutInflater mInflater;
String[] items;
String[] bushido;
String[] description;
 TextView finalscorre;
Integer scr;

public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
    items = i;
    bushido = p;
    description = d;
    finalscorre = sc;
    scr = scc;
    mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return items.length;
}

@Override
public Object getItem(int i) {
    return items[i];
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View convertView, ViewGroup parent) {
    View v = mInflater.inflate(R.layout.my_listview_detail, null);
    TextView nameTextView = v.findViewById(R.id.NameTextView);
    TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
    TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
    finalscorre = v.findViewById(R.id.finalScoreView);

    String name = items[i];
    String desc = description[i];
    String bush = bushido[i];

    finalscorre.setText("Waat");
    nameTextView.setText(name);
    descriptionTextView.setText(desc);
    bushidoTextView.setText(bush);

    ItemAdapter.this.notifyDataSetChanged();

    return v;
}
</code>```

}

When i try to assign the LiveData in TextView out of the ListView it works.But when i try this ,nothings happen (no errors and no result).

答: inside adapter you are doing nothing that will update your LiveData</p>

Body:
Basically i want to retrieve a int(score) generated from the current ListViewItem and assign it back to concrete TextView in my ListView.I am using SharedViewModel with LiveData but when i observe nothing happens.I am using Nav Architecture Component with Single activity.I'll be glad if someone helps.Thank u , here's some code.

public class ListFrag extends Fragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);

    model.getCurrentScore().observe(getViewLifecycleOwner(), new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer s) {

            for (int i = 0; i < myListView.getAdapter().getCount(); i++) {

                v =  myListView.getAdapter().getView(i,null, myListView);

                finalScore = v.findViewById(R.id.finalScoreView);

                    if (s != null) {
    itemAdapter = new ItemAdapter(getActivity(),items,bushido,description,s,finalScore);
                        myListView.setAdapter(itemAdapter);
                       finalScore.setText(String.valueOf(s));

                    }
      ((BaseAdapter)myListView.getAdapter()).notifyDataSetChanged();
            }
        }
    });
}

public class SharedViewModel extends ViewModel
{

private MutableLiveData<Integer> currentScore = new MutableLiveData<>();

public LiveData<Integer> getCurrentScore(){
    return currentScore;
}

public void setCurrentScore(Integer finito) {
    currentScore.setValue(finito);

}

}

public class ItemAdapter extends BaseAdapter {

LayoutInflater mInflater;
String[] items;
String[] bushido;
String[] description;
 TextView finalscorre;
Integer scr;

public ItemAdapter(Context c,String[] i ,String [] p ,String[] d, Integer scc,TextView sc) {
    items = i;
    bushido = p;
    description = d;
    finalscorre = sc;
    scr = scc;
    mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return items.length;
}

@Override
public Object getItem(int i) {
    return items[i];
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View convertView, ViewGroup parent) {
    View v = mInflater.inflate(R.layout.my_listview_detail, null);
    TextView nameTextView = v.findViewById(R.id.NameTextView);
    TextView bushidoTextView = v.findViewById(R.id.bushidoTextView);
    TextView descriptionTextView = v.findViewById(R.id.descriptionTextView);
    finalscorre = v.findViewById(R.id.finalScoreView);

    String name = items[i];
    String desc = description[i];
    String bush = bushido[i];

    finalscorre.setText("Waat");
    nameTextView.setText(name);
    descriptionTextView.setText(desc);
    bushidoTextView.setText(bush);

    ItemAdapter.this.notifyDataSetChanged();

    return v;
}

}

When i try to assign the LiveData in TextView out of the ListView it works.But when i try this ,nothings happen (no errors and no result).


问:
jQuery UI Autocomplete: Load from Array of Objects: Filtering is broken
I'm following the JSFiddle given in this thread as the solution to loading jQuery UI AutoComplete from a simple Array of Objects:

http://jsfiddle.net/khsbme4k/

The filtering is broken here. There are 2 data rows with a First_Name string, "Will" and "Willem", but if you type anything else e.g. "WA" you still get the full selection of 2 items, where there should be none.

```<code>  var data = [
        {
            "id": 1,
            "first_name": "Will",
            "last_name": "Smith",
            "created_at": "2015-01-27T13:09:20.243Z",
            "updated_at": "2015-01-27T13:09:20.243Z"
        },
        {
            "id": 2,
            "first_name": "Willem",
            "last_name": "Dafoe",
            "created_at": "2015-01-27T13:17:23.479Z",
            "updated_at": "2015-01-27T13:17:23.479Z"
        }
    ];

$('#search').autocomplete({
        // This shows the min length of charcters that must be typed before the autocomplete looks for a match.
        minLength: 2,
source: function (request, response) {
           response($.map(data, function (value, key) {
                return {
                    label: value.first_name,
                    value: value.id
                }
            }));

    },
        focus: function(event, ui) {
            $('#search').val(ui.item.first_name);
            return false;
        },
        // Once a value in the drop down list is selected, do the following:
        select: function(event, ui) {
            // place the person.given_name value into the textfield called 'select_origin'...
            $('#search').val(ui.item.first_name);
            // and place the person.id into the hidden textfield called 'link_origin_id'.
            $('#link_origin_id').val(ui.item.id);
                return false;
        }
</code>```

答:
Consider the following code example of your source:

```<code>source: function(request, response) {
  var results;
  var aData = $.map(data, function(value, key) {
    return {
      label: value.first_name,
      value: value.id
    }
  });
  results = $.ui.autocomplete.filter(aData, request.term);
  response(results);
}
</code>```

First we map your data to { label, value } pairs that Autocomplete is expecting. We then use $.ui.autocomplete.filter() to perform the expected filtering like Autocomplete does. This gives us our results array that we can send to response() to display.

Working example: https://jsfiddle.net/Twisty/svnbw2uj/3/

Hope that helps.

Body:
I'm following the JSFiddle given in this thread as the solution to loading jQuery UI AutoComplete from a simple Array of Objects:

http://jsfiddle.net/khsbme4k/

The filtering is broken here. There are 2 data rows with a First_Name string, "Will" and "Willem", but if you type anything else e.g. "WA" you still get the full selection of 2 items, where there should be none.

  var data = [
        {
            "id": 1,
            "first_name": "Will",
            "last_name": "Smith",
            "created_at": "2015-01-27T13:09:20.243Z",
            "updated_at": "2015-01-27T13:09:20.243Z"
        },
        {
            "id": 2,
            "first_name": "Willem",
            "last_name": "Dafoe",
            "created_at": "2015-01-27T13:17:23.479Z",
            "updated_at": "2015-01-27T13:17:23.479Z"
        }
    ];

$('#search').autocomplete({
        // This shows the min length of charcters that must be typed before the autocomplete looks for a match.
        minLength: 2,
source: function (request, response) {
           response($.map(data, function (value, key) {
                return {
                    label: value.first_name,
                    value: value.id
                }
            }));

    },
        focus: function(event, ui) {
            $('#search').val(ui.item.first_name);
            return false;
        },
        // Once a value in the drop down list is selected, do the following:
        select: function(event, ui) {
            // place the person.given_name value into the textfield called 'select_origin'...
            $('#search').val(ui.item.first_name);
            // and place the person.id into the hidden textfield called 'link_origin_id'.
            $('#link_origin_id').val(ui.item.id);
                return false;
        }

Body:
Consider the following code example of your source:

source: function(request, response) {
  var results;
  var aData = $.map(data, function(value, key) {
    return {
      label: value.first_name,
      value: value.id
    }
  });
  results = $.ui.autocomplete.filter(aData, request.term);
  response(results);
}

First we map your data to { label, value } pairs that Autocomplete is expecting. We then use $.ui.autocomplete.filter() to perform the expected filtering like Autocomplete does. This gives us our results array that we can send to response() to display.

Working example: https://jsfiddle.net/Twisty/svnbw2uj/3/

Hope that helps.


问:
read the col in the csv file and write a a row in another
I want to read the column wise content of the csv file and write it row wise.

I have tried it, but I cant add the second column to second row, it is getting merged in first row itself.

```<code>import csv
col ={}
 with open('C:/Users/upadh/Desktop/north.csv', 'r') as f,
  open('current.csv', 'w') as f_out:
for line in f:
 cols = line.split(',', 4)
  if len(cols) >= 4:

  col = cols[0].strip()+","
 # col = col +"\n"
  f_out.write(col)
</code>```

1,2,3
welcome, to, Delhi

as:
1,welcome
2,to
3,Delhi

答:
Did you try transpose?. It may suit your requirements.</p>

```<code>d1 = {'col1': [1, 2], 'col2': [3, 4]}
   col1  col2
0     1     3
1     2     4

df1_transposed = df1.transpose()
      0  1
col1  1  2
col2  3  4
</code>```

Body:
I want to read the column wise content of the csv file and write it row wise.

I have tried it, but I cant add the second column to second row, it is getting merged in first row itself.

import csv
col ={}
 with open('C:/Users/upadh/Desktop/north.csv', 'r') as f,
  open('current.csv', 'w') as f_out:
for line in f:
 cols = line.split(',', 4)
  if len(cols) >= 4:

  col = cols[0].strip()+","
 # col = col +"\n"
  f_out.write(col)

1,2,3
welcome, to, Delhi

as:
1,welcome
2,to
3,Delhi

Body:
Did you try transpose?. It may suit your requirements.

d1 = {'col1': [1, 2], 'col2': [3, 4]}
   col1  col2
0     1     3
1     2     4

df1_transposed = df1.transpose()
      0  1
col1  1  2
col2  3  4


问:
Import table from website with BeautifulSoup
I am trying to import a table from a website and afterwards transform the data into a pandas dataframe.

The website is: https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M

Thats my code so far:

```<code>import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup

website_url = requests.get(
'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M').text

soup = BeautifulSoup(website_url,'lxml')

My_table = soup.find('table',{'class':'wikitable sortable'})

for x in soup.find_all('table',{'class':'wikitable sortable'}):
    table = x.text

print(My_table)
print(table)
</code>```

Output of print(My_table)

Output of print(table)

How do I convert this webpage table to a panda dataframe?
panda dataframe

答:
have you tried

```<code>pd.read_html()
</code>```

?

Also, since the table is very standard, why not directly copy the table into excel and import it as DataFrame?

Body:
I am trying to import a table from a website and afterwards transform the data into a pandas dataframe.

The website is: https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M

Thats my code so far:

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup

website_url = requests.get(
'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M').text

soup = BeautifulSoup(website_url,'lxml')

My_table = soup.find('table',{'class':'wikitable sortable'})

for x in soup.find_all('table',{'class':'wikitable sortable'}):
    table = x.text

print(My_table)
print(table)

Output of print(My_table)

Output of print(table)

How do I convert this webpage table to a panda dataframe?
panda dataframe

Body:
have you tried

pd.read_html()

?

Also, since the table is very standard, why not directly copy the table into excel and import it as DataFrame?


问:
XPages Pager with Last and lots of pages
I am looking at a way to bypass a bug in the standard pager with views that contain a large numbers of documents.  When I use the code below, the "Last" won't show up:

```<code><xp:this.facets>
    <xp:pager layout="First Previous Group Next Last" xp:key="header"
        id="pager1" for="myView" partialRefresh="true">
</xp:pager>
</code>```

Anyone got around this, or has an alternate solution?

答: Set the alwaysCalculateLast property on the xp:pager to true to calculate the last document in the view. There can be a performance hit when this is set to true, though.

Body:
I am looking at a way to bypass a bug in the standard pager with views that contain a large numbers of documents.  When I use the code below, the "Last" won't show up:

<xp:this.facets>
    <xp:pager layout="First Previous Group Next Last" xp:key="header"
        id="pager1" for="myView" partialRefresh="true">
</xp:pager>

Anyone got around this, or has an alternate solution?


问:
Dynamically change an image in a Crystal Report at runtime
I'm using the Crystal Reports included with VisualStudio 2005. I would like to change the image that is displayed on the report at runtime ideally by building a path to the image file and then have that image displayed on the report.

Has anyone been able to accomplish this with this version of Crystal Reports?

答:
[I have since found a solution using a byte array via a C# Object property - see separate Answer. Leaving this answer here for reference...]

Here's what I have seen suggested (but I tried and failed in both C#-2005 and C#-2008).

Choose a directory and place a BMP there (e.g., "C:\Temp\image.bmp").

From the CR-Designer a) Right-click->Insert->OLE Object... b) Select "Create from File" c) Check the "Link" checkbox d) Browse and pick the bmp defined in step 1 e) Click OK f) Place the image on the form.

Overwrite/update the image at runtime in your C# code. In theory, since you inserted a Link to an image file, it will be updated when the form is refreshed.

I had no luck with this approach. The image appears when I first design the form (step 2). But at runtime, the image does not update for me. From this point forward, things get really odd. It seems that CR caches some sort of image that just won't go away. I can delete the OLE object link in CR-Designer, but if I recreate it, I always get a black box the same size as the original image (even if I change the size of image.bmp).

OwnerDisplayName: Keith

LastEditorDisplayName: Phillip Wells


问:
Add A City To An Existing Country In EF(Entity Framework)
Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

```<code>City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
</code>```

What's wrong with this code?
I want to insert a city of for a country to database. "(vs2008sp1)"
The country already exist.

```<code>Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
</code>```

definition is

```<code>City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))
</code>```

Id in City and Country table in Identity(Auto Increment)

Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

答:
Like Sergi mentioned you should first retrieve the Country from your context and then add the new City to it.

In pseudo code:

```<code>using (YourEntities context = getYourContextHere())
{
var countryEntity = context.CountryEntitySet.FirstOrDefault(country => country.id == newCityCountryId);

if (countryEntity == null)
  throw new InvalidOperationException();

CityEntity newCity = createYourCityEntity();
newCity.Country = countryEntity;

context.SaveChanges();
}
</code>```

Something like that should work.

Body:
Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();

What's wrong with this code?
I want to insert a city of for a country to database. "(vs2008sp1)"
The country already exist.

Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}

definition is

City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))

Id in City and Country table in Identity(Auto Increment)

Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.

Body:
Like Sergi mentioned you should first retrieve the Country from your context and then add the new City to it.

In pseudo code:

using (YourEntities context = getYourContextHere())
{
var countryEntity = context.CountryEntitySet.FirstOrDefault(country => country.id == newCityCountryId);

if (countryEntity == null)
  throw new InvalidOperationException();

CityEntity newCity = createYourCityEntity();
newCity.Country = countryEntity;

context.SaveChanges();
}

Something like that should work.


问:
module['test'] isn't equal to module.test?
I'm currently creating a discord bot in which I use the mechanism of modules and I want to access from the modules imported with classes integrated the informations that are set in the beginning of the class. However when i try to go into the module
https://pastebin.com/ygLAgaWB
and try to access the class into it doing the following "module.help" works but not "module['help']". Since i'm replacing the "help" with a variable like : module[var], i can' t use module.var. So how can i solve this problem ? I want to access the 'help' class in the 'module' module using a variable where 'help' is stored in.

I've tried nothing because i don't know what to do.

    module = self.Modules
    var = tmp[0]
    class_ = module[var][var]
```

I expect that it return the class object.

答:
Yes, Python isn't JavaScript, module["help"] and module.help are two different concepts. Square brackets take indices or keys, attributes are retrieved with dot notation.

If you need to access an attribute using a variable you can use

```<code>getattr(module, var)
</code>```

Body:
I'm currently creating a discord bot in which I use the mechanism of modules and I want to access from the modules imported with classes integrated the informations that are set in the beginning of the class. However when i try to go into the module
https://pastebin.com/ygLAgaWB
and try to access the class into it doing the following "module.help" works but not "module['help']". Since i'm replacing the "help" with a variable like : module[var], i can' t use module.var. So how can i solve this problem ? I want to access the 'help' class in the 'module' module using a variable where 'help' is stored in.

I've tried nothing because i don't know what to do.

    module = self.Modules
    var = tmp[0]
    class_ = module[var][var]

I expect that it return the class object.

Body:
Yes, Python isn't JavaScript, module["help"] and module.help are two different concepts. Square brackets take indices or keys, attributes are retrieved with dot notation.

If you need to access an attribute using a variable you can use

getattr(module, var)


问:
Cannot open (GPIO) Pin 6 in Windows 10 Iot Core
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

```<code>private static readonly int GPIO_NUMBER_RED = 22;
</code>```

Called in the constructor:

```<code>    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);
</code>```

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

```<code>    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.
</code>```

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

```<code>    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>
</code>```

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.

答:
Solution

If do not call the gpioController in the Constructor but in another method that will be called after the Init, everything works fine.

Now, the question is, why is it not possible to do it in the init?

Body:
I want to let the red LED of my RainbowHAT shine. That requires that I send a high signal to the BCM 6 pin.

(Shortend) Source

Class constant:

private static readonly int GPIO_NUMBER_RED = 22;

Called in the constructor:

    var gpioController = GpioController.GetDefault();

    redPin = gpioController.OpenPin(GPIO_NUMBER_RED);
    redPin.Write(GpioPinValue.High);
    redPin.SetDriveMode(GpioPinDriveMode.Output);

I tried the values 6 (BCM), 31 (Pin number) and 22 (Wiring pin number) for my class global constant GPIO_NUMBER_RED but I get always the error:

    WinRT information: Pin ' is not available. It is reserved by the system or in use for another function.

Pin layout

https://pinout.xyz/pinout/rainbow_hat

Full source

GitHub

Package Info

    <Capabilities>
        <Capability Name="internetClient" />
        <DeviceCapability Name="lowLevel"/>
    </Capabilities>

I also restarted the Pi to "reset" maybe other application that access this Pin - without success.


问:
Data not updating on array
I tried this http endpoint to update data on array call userArr, But any data wouldn't be updated

```<code>app.put('/update/:Id',function (req, res) {

try{
const index = userArr.findIndex(instence => instence.id == req.params.Id);
userArr[index].firstName = req.body.fName;
userArr[index].lastName = req.body.lName;
userArr[index].birthDay = req.body.bDay;
res.status(200).send(userArr[index]);
}catch(e){
res.status(500).send({message:e});
}
</code>```

Expected output is status 200 actual output is 500

答:
Thats because you are not sending the Id value to the API call. You are sending the string 'ID'
It should be like </p>

```<code>var Id = "your id value";
app.put('/update/:'+ Id,function (req, res) {

try{
const index = userArr.findIndex(instence => instence.id == req.params.Id);
userArr[index].firstName = req.body.fName;
userArr[index].lastName = req.body.lName;
userArr[index].birthDay = req.body.bDay;
res.status(200).send(userArr[index]);
}catch(e){
res.status(500).send({message:e});
}
</code>```

Title: Data not updating on array

Body:
I tried this http endpoint to update data on array call userArr, But any data wouldn't be updated

app.put('/update/:Id',function (req, res) {

try{
const index = userArr.findIndex(instence => instence.id == req.params.Id);
userArr[index].firstName = req.body.fName;
userArr[index].lastName = req.body.lName;
userArr[index].birthDay = req.body.bDay;
res.status(200).send(userArr[index]);
}catch(e){
res.status(500).send({message:e});
}

Expected output is status 200 actual output is 500

Body:
Thats because you are not sending the Id value to the API call. You are sending the string 'ID'
It should be like

var Id = "your id value";
app.put('/update/:'+ Id,function (req, res) {

try{
const index = userArr.findIndex(instence => instence.id == req.params.Id);
userArr[index].firstName = req.body.fName;
userArr[index].lastName = req.body.lName;
userArr[index].birthDay = req.body.bDay;
res.status(200).send(userArr[index]);
}catch(e){
res.status(500).send({message:e});
}


问:
Why unable to parse a string | Rust
I am making decimal to binary conversion program. Why am i unable to parse a string into a number? binary_vec[i] is a character. I applied to_string() method to convert it into a string because parse() doesn't apply to a character, but it still giving me an error.

```<code>use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin().read_line(&mut binary)
        .ok()
        .expect("Couldn't read line");
    println!("{}",to_decimal(binary));

}

fn to_decimal(mut binary_str:String) -> String {
    let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}",binary_no)
                }
    else {
        let mut bits = String::new();
        let mut binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <=binary_str.len()-2{
            let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
            i = i +1;
        }
        format!("{}",result)
        }
}
</code>```

Result:

```<code> Compiling sixteen v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\sixteen)
warning: unused variable: `bits`
  --> src\main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `result`
  --> src\main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`

warning: variable does not need to be mutable
  --> src\main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

warning: variable does not need to be mutable
  --> src\main.rs:14:9
   |
14 |     let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:19:13
   |
19 |         let mut bits = String::new();
   |             ----^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:20:13
   |
20 |         let mut binary_vec: Vec<char> = binary_str.chars().collect();
   |             ----^^^^^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:21:13
   |
21 |         let mut result = 0;
   |             ----^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:24:17
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                 ----^^^^^^
   |                 |
   |                 help: remove this `mut`

    Finished dev [unoptimized + debuginfo] target(s) in 1.04s
     Running `target\debug\sixteen.exe`
Enter a decimal:
100
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src\libcore\result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\sixteen.exe` (exit code: 101)
</code>```

Edit:
I have input 100 and I expect to get 4 at output.

答:
I would usually try to fix the code, but this one just seems way to convoluted.

Here is a simpler solution:

use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");

    io::stdin().read_line(&mut binary)
        .expect("Couldn't read line");

    match to_decimal(binary) {
        Some(num) => println!("{}", num),
        None => println!("Not a binary!")
    }
}

fn to_decimal(binary_str:String) -> Option<i64> {
    let binary_str = binary_str.trim();

    let mut out_num = 0;
    for c in binary_str.chars() {
        match c {
            '0' => out_num = out_num * 2,
            '1' => out_num = out_num * 2 + 1,
            _ => return None
        }
    }

    Some(out_num)
}
```

Title: Why unable to parse a string | Rust

Body:
I am making decimal to binary conversion program. Why am i unable to parse a string into a number? binary_vec[i] is a character. I applied to_string() method to convert it into a string because parse() doesn't apply to a character, but it still giving me an error.

use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin().read_line(&mut binary)
        .ok()
        .expect("Couldn't read line");
    println!("{}",to_decimal(binary));

}

fn to_decimal(mut binary_str:String) -> String {
    let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}",binary_no)
                }
    else {
        let mut bits = String::new();
        let mut binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <=binary_str.len()-2{
            let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
            i = i +1;
        }
        format!("{}",result)
        }
}

Result:

 Compiling sixteen v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\sixteen)
warning: unused variable: `bits`
  --> src\main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `result`
  --> src\main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`

warning: variable does not need to be mutable
  --> src\main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

warning: variable does not need to be mutable
  --> src\main.rs:14:9
   |
14 |     let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:19:13
   |
19 |         let mut bits = String::new();
   |             ----^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:20:13
   |
20 |         let mut binary_vec: Vec<char> = binary_str.chars().collect();
   |             ----^^^^^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:21:13
   |
21 |         let mut result = 0;
   |             ----^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:24:17
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                 ----^^^^^^
   |                 |
   |                 help: remove this `mut`

    Finished dev [unoptimized + debuginfo] target(s) in 1.04s
     Running `target\debug\sixteen.exe`
Enter a decimal:
100
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src\libcore\result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\sixteen.exe` (exit code: 101)

Edit:
I have input 100 and I expect to get 4 at output.


问:
CSS border is not wrapping whole div content
This is my html code which has "box" as main div and then three divs inside it
which are positioned left,middle and right respectively.

```<code><div id="box">
 <div class="left">Left</div>
 <div class="middle">Middle</div>
 <div class="right">Right</div>
</div>
</code>```

And this is my css code

```<code>#box {
    width:90%;
    height:auto;
    border:5px solid green;
}
.left {
    float:left;
    width:30%;
}
.right {
    float:right;
    width:30%;
}
.middle {
    float:left;
    width:30%;
}
</code>```

This is jsfiddle link: http://jsfiddle.net/hep9oLzn/
The border is not wrapping the content.

答:
FYI: The clearfix solution also works with the outline CSS property (which are similar to borders in that they wrap around a div / element)

```<code>.clearfix:after {
    content: ".";
    visibility: hidden;
    display: block;
    height: 0;
    clear: both; }
</code>```

Body:
This is my html code which has "box" as main div and then three divs inside it
which are positioned left,middle and right respectively.

Left

Middle

Right

And this is my css code

#box {
    width:90%;
    height:auto;
    border:5px solid green;
}
.left {
    float:left;
    width:30%;
}
.right {
    float:right;
    width:30%;
}
.middle {
    float:left;
    width:30%;
}

This is jsfiddle link: http://jsfiddle.net/hep9oLzn/
The border is not wrapping the content.

Body:
FYI: The clearfix solution also works with the outline CSS property (which are similar to borders in that they wrap around a div / element)

.clearfix:after {
    content: ".";
    visibility: hidden;
    display: block;
    height: 0;
    clear: both; }