问:
Count non-holiday weekdays
I have a working symfony project that includes a Holiday class with several grouped static functions around counting non-holiday weekdays. The heart of the code was taken from several answers in this thread.

I use the static methods all around my code-base, including twig extensions, reports, chart creation, etc.

The biggest downside to these is that I periodically have to go into these methods and manually key in Holidays for the coming year (yes, I know I could do several years all at once), but there are occasional "holidays" that I add for things like off-days due to bad weather. Manually adding a holiday and pushing the code to my git repository just feels "wrong", or at least not elegant.

The solution would seem to have holidays into a database and never touch the code again. This means working with doctrine, but this means some dependency injection to get an entity manager to my static methods, and once again this does not feel so elegant.

So what's the solution??

Here's my Holiday class, although the code here works perfectly for my needs. I'm looking for an elegant way to move the $holidays array to a database.

```<code><?php
namespace App\Controller;

use DateInterval;
use DatePeriod;
use DateTime;
use Exception;

class Holiday
{
    private static $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)

    /**
     * Is submitted date a holiday?
     *
     * @param DateTime $date
     * @return bool
     */
    public static function isHoliday(DateTime $date): bool
    {
        $holidays = self::getHolidays();

        return
            in_array($date->format('Y-m-d'), $holidays) ||
            in_array($date->format('*-m-d'), $holidays);
    }

    public static function isWorkDay(DateTime $date): bool
    {
        if (!in_array($date->format('N'), self::$workingDays)) {
            return false;
        }
        if (self::isHoliday($date)) {
            return false;
        }

        return true;
    }

    /**
     * Count number of weekdays within a given date span, excluding holidays
     *
     * @param DateTime $from
     * @param DateTime $to
     * @return int
     * @throws Exception
     */
    public static function countWeekDays(DateTime $from, DateTime $to = null)
    {
        if (is_null($to)) {
            return null;
        }

        // from stackoverflow:
        // http://stackoverflow.com/questions/336127/calculate-business-days#19221403

        $from = clone($from);
        $from->setTime(0, 0, 0);
        $to = clone($to);
        $to->setTime(0, 0, 0);
        $interval = new DateInterval('P1D');
        $to->add($interval);
        $period = new DatePeriod($from, $interval, $to);

        $days = 0;
        /** @var DateTime $date */
        foreach ($period as $date) {
            if (self::isWorkDay($date)) {
                $days++;
            }
        }

        return $days;
    }

    /**
     * Return count of weekdays in given month
     *
     * @param int $month
     * @param int $year
     * @return int
     * @throws Exception
     */
    public static function countWeekDaysInMonthToDate(int $month, int $year): int
    {
        $d1 = new DateTime($year . '-' . $month . '-01');
        $d2 = new DateTime($d1->format('Y-m-t'));
        $today = new DateTime();

        return self::countWeekDays($d1, min($d2, $today));
    }

    /**
     * Returns an array of strings representing holidays in format 'Y-m-d'
     *
     * @return array
     */
    private static function getHolidays(): array
    {
        // TODO: Move holidays to database (?)

        $holidays = ['*-12-25', '*-01-01', '*-07-04',
            '2017-04-14', # Good Friday
            '2017-05-29', # Memorial day
            '2017-08-28', # Hurricane Harvey closure
            '2017-08-29', # Hurricane Harvey closure
            '2017-08-30', # Hurricane Harvey closure
            '2017-08-31', # Hurricane Harvey closure
            '2017-09-01', # Hurricane Harvey closure
            '2017-09-04', # Labor day
            '2017-11-23', # Thanksgiving
            '2017-11-24', # Thanksgiving

            #'2018-03-30', # Good Friday
            '2018-05-28', # Memorial day
            '2018-09-03', # Labor day
            '2018-11-22', # Thanksgiving
            '2018-11-23', # Thanksgiving
            '2018-12-24', # Christmas Eve
            '2018-12-31', # New Year's Eve

            '2019-04-19', # Good Friday
            '2019-05-27', # Memorial day
            '2019-09-02', # Labor day
            '2019-11-28', # Thanksgiving
            '2019-11-29', # Thanksgiving
        ]; # variable and fixed holidays

        return $holidays;
    }
}
</code>```

答:
As per my suggestion of using relative formats for observable holidays. I added the ability to use callables and date interval periods for more complex dates.
I also included easter as a holiday as a use-case, using the easter_date function from PHP's calendar extension.

I also suggest segmenting the dates by year and storing them into a static property, to determine if they have already been loaded, in order to prevent reloading them on multiple iterations.

Example: https://3v4l.org/fnj67

(Demonstrates include file usage)

```<code>class Holiday
{

    /**
     * holidays in [YYYY => [YYYY-MM-DD]] format
     * array|string[][]
     */
    private static $observableHolidays = [];

    //....

    /**
     * Is submitted date a holiday?
     *
     * @param DateTime $date
     * @return bool
     */
    public static function isHoliday(\DateTimeInterface $date): bool
    {
        $holidays = self::getHolidays($date);

        return \array_key_exists($date->format('Y-m-d'), array_flip($holidays[$date->format('Y')]));
    }

    /**
     * @see https://www.php.net/manual/en/function.easter-date.php
     * @param \DateTimeInterface $date
     * @return \DateTimeImmutable
     */
    private static function getEaster(\DateTimeInterface $date): \DateTimeImmutable
    {
        return (new \DateTimeImmutable())->setTimestamp(\easter_date($date->format('Y')));
    }

    /**
     * Returns an array of strings representing holidays in format 'Y-m-d'
     *
     * @return array|string[][]
     */
    public static function getHolidays(\DateTimeInterface $start): array
    {
        //static prevents redeclaring the variable
        static $relativeHolidays = [
            'new years day' => 'first day of January',
            'easter' => [__CLASS__, 'getEaster'],
            'memorial day' => 'second Monday of May',
            'independence day' => 'July 4th',
            'labor day' => 'first Monday of September',
            'thanksgiving' => 'fourth Thursday of November',
            'black friday' => 'fourth Thursday of November + 1 day',
            'christmas' => 'December 25th',
            'new years eve' => 'last day of December',

            //... add others like Veterans Day, MLK, Columbus Day, etc
        ];
        if (!$start instanceof \DateTimeImmutable) {
            //force using DateTimeImmutable
            $start = \DateTimeImmutable::createFromMutable($start);
        }
        //build the holidays to the specified year
        $start = $start->modify('first day of this year');

        //always generate an entire years worth of holidays
        $period = new \DatePeriod($start, new \DateInterval('P1Y'), 0);
        foreach ($period as $date) {
            $year = $date->format('Y');
            if (array_key_exists($year, self::$observableHolidays)) {
                continue;
            }
            self::$observableHolidays[$year] = [];
            foreach (self::$relativeHolidays as $relativeHoliday) {
                 if (\is_callable($relativeHoliday)) {
                    $holidayDate = $relativeHoliday($date);
                } elseif (0 === \strpos($relativeHoliday, 'P')) {
                    $holidayDate = $date->add(new \DateInterval($relativeHoliday));
                } else {
                    $holidayDate = $date->modify($relativeHoliday);
                }
                self::$observableHolidays[$year][] = $holidayDate->format('Y-m-d');
            }
        }

        return self::$observableHolidays;
    }
}

$holidays = Holiday::getHolidays(new \DateTime('2017-08-28'));
</code>```

Results:

```<code>array (
  2017 =>
  array (
    0 => '2017-01-01',
    1 => '2017-04-16',
    2 => '2017-05-08',
    3 => '2017-07-04',
    4 => '2017-09-04',
    5 => '2017-11-23',
    6 => '2017-11-24',
    7 => '2017-12-25',
    8 => '2017-12-31',
  ),
)
</code>```

Specific closure dates for your organization, that cannot be stored in a relative format, would desirably be stored in a RDBMS like MySQL or SQLite. Which can then be retrieved after the standard observable holidays, when those years are encountered.

However in the absence of a database you can use an include file, much like Symfony does in its container service declarations, which also benefits from using OPcache.
Alternatively you can use the Symfony Serializer component to generate, load and save the non-relative data in your desired formatting, (JSON, CSV, XML, YAML).

Here is an example of using an include file dictionary with your current class.

```<code>class Holiday
{
    public const CLOSURES_FILE = '/tmp/closures.php';

    //...

    public static function getHolidays(\DateTimeInterface $date): array
    {
        //...

        $holidays = self::$observableHolidays;
        if (\is_file(self::CLOSURES_FILE)) {
           foreach (include self::CLOSURES_FILE as $year => $dates) {
                if (!\array_key_exists($year, $holidays)) {
                    $holidays[$year] = [];
                }
                $holidays[$year] = array_merge($holidays[$year], $dates);
            }
        }

        return $holidays;
    }
}

$date = new \DateTime('2017-08-28');
var_export(Holiday::getHolidays($date));
var_dump(Holiday::isHoliday($date));
</code>```

Results:

```<code>array (
  2017 =>
  array (
    0 => '2017-01-01',
    1 => '2017-04-16',
    2 => '2017-05-08',
    3 => '2017-07-04',
    4 => '2017-09-04',
    5 => '2017-11-23',
    6 => '2017-11-24',
    7 => '2017-12-25',
    8 => '2017-12-31',
    9 => '2017-08-28',
    10 => '2017-08-29',
    11 => '2017-08-30',
    12 => '2017-08-31',
    13 => '2017-09-01',
  ),
)
bool(true)
</code>```

To save the include file dictionary, you can load and save these values in your application how you like, such as with a simple form $_POST values.

```<code>$dictionary_array = ['year' => ['date1', 'date2']];
file_put_contents(Holiday::CLOSURES_FILE, '<?php return ' . var_export($dictionary_array) . ';');
</code>```

As your application is version controlled, use or set the desired dictionary file path to one that is ignored in your .gitignore file, such as var/holidays/holiday_dates.php.

In my Symfony project, I add the known relative and non-relative date values as parameters from the configs to my Holiday service, such as 2001-09-11. I then use a query service to inject the unknown non-relative dates from the database into the Holiday class, such as your hurricane closures. My Holiday service is used throughout the application only using DI, including inside of Twig functions, as opposed to using static method calls, but this could be done by using a CompilerPass, on a static method to set the dates.

Since you are using static methods to directly access the results, it
  would require a major application refactor to any service that uses a Holiday
  static method in favor of using it as a Symfony service.

Title: Count non-holiday weekdays

Body:
I have a working symfony project that includes a Holiday class with several grouped static functions around counting non-holiday weekdays. The heart of the code was taken from several answers in this thread.

I use the static methods all around my code-base, including twig extensions, reports, chart creation, etc.

The biggest downside to these is that I periodically have to go into these methods and manually key in Holidays for the coming year (yes, I know I could do several years all at once), but there are occasional "holidays" that I add for things like off-days due to bad weather. Manually adding a holiday and pushing the code to my git repository just feels "wrong", or at least not elegant.

The solution would seem to have holidays into a database and never touch the code again. This means working with doctrine, but this means some dependency injection to get an entity manager to my static methods, and once again this does not feel so elegant.

So what's the solution??

Here's my Holiday class, although the code here works perfectly for my needs. I'm looking for an elegant way to move the $holidays array to a database.

<?php
namespace App\Controller;

use DateInterval;
use DatePeriod;
use DateTime;
use Exception;

class Holiday
{
    private static $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...)

    /**
     * Is submitted date a holiday?
     *
     * @param DateTime $date
     * @return bool
     */
    public static function isHoliday(DateTime $date): bool
    {
        $holidays = self::getHolidays();

        return
            in_array($date->format('Y-m-d'), $holidays) ||
            in_array($date->format('*-m-d'), $holidays);
    }

    public static function isWorkDay(DateTime $date): bool
    {
        if (!in_array($date->format('N'), self::$workingDays)) {
            return false;
        }
        if (self::isHoliday($date)) {
            return false;
        }

        return true;
    }

    /**
     * Count number of weekdays within a given date span, excluding holidays
     *
     * @param DateTime $from
     * @param DateTime $to
     * @return int
     * @throws Exception
     */
    public static function countWeekDays(DateTime $from, DateTime $to = null)
    {
        if (is_null($to)) {
            return null;
        }

        // from stackoverflow:
        // http://stackoverflow.com/questions/336127/calculate-business-days#19221403

        $from = clone($from);
        $from->setTime(0, 0, 0);
        $to = clone($to);
        $to->setTime(0, 0, 0);
        $interval = new DateInterval('P1D');
        $to->add($interval);
        $period = new DatePeriod($from, $interval, $to);

        $days = 0;
        /** @var DateTime $date */
        foreach ($period as $date) {
            if (self::isWorkDay($date)) {
                $days++;
            }
        }

        return $days;
    }

    /**
     * Return count of weekdays in given month
     *
     * @param int $month
     * @param int $year
     * @return int
     * @throws Exception
     */
    public static function countWeekDaysInMonthToDate(int $month, int $year): int
    {
        $d1 = new DateTime($year . '-' . $month . '-01');
        $d2 = new DateTime($d1->format('Y-m-t'));
        $today = new DateTime();

        return self::countWeekDays($d1, min($d2, $today));
    }

    /**
     * Returns an array of strings representing holidays in format 'Y-m-d'
     *
     * @return array
     */
    private static function getHolidays(): array
    {
        // TODO: Move holidays to database (?)

        $holidays = ['*-12-25', '*-01-01', '*-07-04',
            '2017-04-14', # Good Friday
            '2017-05-29', # Memorial day
            '2017-08-28', # Hurricane Harvey closure
            '2017-08-29', # Hurricane Harvey closure
            '2017-08-30', # Hurricane Harvey closure
            '2017-08-31', # Hurricane Harvey closure
            '2017-09-01', # Hurricane Harvey closure
            '2017-09-04', # Labor day
            '2017-11-23', # Thanksgiving
            '2017-11-24', # Thanksgiving

            #'2018-03-30', # Good Friday
            '2018-05-28', # Memorial day
            '2018-09-03', # Labor day
            '2018-11-22', # Thanksgiving
            '2018-11-23', # Thanksgiving
            '2018-12-24', # Christmas Eve
            '2018-12-31', # New Year's Eve

            '2019-04-19', # Good Friday
            '2019-05-27', # Memorial day
            '2019-09-02', # Labor day
            '2019-11-28', # Thanksgiving
            '2019-11-29', # Thanksgiving
        ]; # variable and fixed holidays

        return $holidays;
    }
}

Body:
As per my suggestion of using relative formats for observable holidays. I added the ability to use callables and date interval periods for more complex dates.
I also included easter as a holiday as a use-case, using the easter_date function from PHP's calendar extension.

I also suggest segmenting the dates by year and storing them into a static property, to determine if they have already been loaded, in order to prevent reloading them on multiple iterations.

Example: https://3v4l.org/fnj67

(Demonstrates include file usage)

class Holiday
{

    /**
     * holidays in [YYYY => [YYYY-MM-DD]] format
     * array|string[][]
     */
    private static $observableHolidays = [];

    //....

    /**
     * Is submitted date a holiday?
     *
     * @param DateTime $date
     * @return bool
     */
    public static function isHoliday(\DateTimeInterface $date): bool
    {
        $holidays = self::getHolidays($date);

        return \array_key_exists($date->format('Y-m-d'), array_flip($holidays[$date->format('Y')]));
    }

    /**
     * @see https://www.php.net/manual/en/function.easter-date.php
     * @param \DateTimeInterface $date
     * @return \DateTimeImmutable
     */
    private static function getEaster(\DateTimeInterface $date): \DateTimeImmutable
    {
        return (new \DateTimeImmutable())->setTimestamp(\easter_date($date->format('Y')));
    }

    /**
     * Returns an array of strings representing holidays in format 'Y-m-d'
     *
     * @return array|string[][]
     */
    public static function getHolidays(\DateTimeInterface $start): array
    {
        //static prevents redeclaring the variable
        static $relativeHolidays = [
            'new years day' => 'first day of January',
            'easter' => [__CLASS__, 'getEaster'],
            'memorial day' => 'second Monday of May',
            'independence day' => 'July 4th',
            'labor day' => 'first Monday of September',
            'thanksgiving' => 'fourth Thursday of November',
            'black friday' => 'fourth Thursday of November + 1 day',
            'christmas' => 'December 25th',
            'new years eve' => 'last day of December',

            //... add others like Veterans Day, MLK, Columbus Day, etc
        ];
        if (!$start instanceof \DateTimeImmutable) {
            //force using DateTimeImmutable
            $start = \DateTimeImmutable::createFromMutable($start);
        }
        //build the holidays to the specified year
        $start = $start->modify('first day of this year');

        //always generate an entire years worth of holidays
        $period = new \DatePeriod($start, new \DateInterval('P1Y'), 0);
        foreach ($period as $date) {
            $year = $date->format('Y');
            if (array_key_exists($year, self::$observableHolidays)) {
                continue;
            }
            self::$observableHolidays[$year] = [];
            foreach (self::$relativeHolidays as $relativeHoliday) {
                 if (\is_callable($relativeHoliday)) {
                    $holidayDate = $relativeHoliday($date);
                } elseif (0 === \strpos($relativeHoliday, 'P')) {
                    $holidayDate = $date->add(new \DateInterval($relativeHoliday));
                } else {
                    $holidayDate = $date->modify($relativeHoliday);
                }
                self::$observableHolidays[$year][] = $holidayDate->format('Y-m-d');
            }
        }

        return self::$observableHolidays;
    }
}

$holidays = Holiday::getHolidays(new \DateTime('2017-08-28'));

Results:

array (
  2017 =>
  array (
    0 => '2017-01-01',
    1 => '2017-04-16',
    2 => '2017-05-08',
    3 => '2017-07-04',
    4 => '2017-09-04',
    5 => '2017-11-23',
    6 => '2017-11-24',
    7 => '2017-12-25',
    8 => '2017-12-31',
  ),
)

Specific closure dates for your organization, that cannot be stored in a relative format, would desirably be stored in a RDBMS like MySQL or SQLite. Which can then be retrieved after the standard observable holidays, when those years are encountered.

However in the absence of a database you can use an include file, much like Symfony does in its container service declarations, which also benefits from using OPcache.
Alternatively you can use the Symfony Serializer component to generate, load and save the non-relative data in your desired formatting, (JSON, CSV, XML, YAML).

Here is an example of using an include file dictionary with your current class.

class Holiday
{
    public const CLOSURES_FILE = '/tmp/closures.php';

    //...

    public static function getHolidays(\DateTimeInterface $date): array
    {
        //...

        $holidays = self::$observableHolidays;
        if (\is_file(self::CLOSURES_FILE)) {
           foreach (include self::CLOSURES_FILE as $year => $dates) {
                if (!\array_key_exists($year, $holidays)) {
                    $holidays[$year] = [];
                }
                $holidays[$year] = array_merge($holidays[$year], $dates);
            }
        }

        return $holidays;
    }
}

$date = new \DateTime('2017-08-28');
var_export(Holiday::getHolidays($date));
var_dump(Holiday::isHoliday($date));

Results:

array (
  2017 =>
  array (
    0 => '2017-01-01',
    1 => '2017-04-16',
    2 => '2017-05-08',
    3 => '2017-07-04',
    4 => '2017-09-04',
    5 => '2017-11-23',
    6 => '2017-11-24',
    7 => '2017-12-25',
    8 => '2017-12-31',
    9 => '2017-08-28',
    10 => '2017-08-29',
    11 => '2017-08-30',
    12 => '2017-08-31',
    13 => '2017-09-01',
  ),
)
bool(true)

To save the include file dictionary, you can load and save these values in your application how you like, such as with a simple form $_POST values.

$dictionary_array = ['year' => ['date1', 'date2']];
file_put_contents(Holiday::CLOSURES_FILE, '<?php return ' . var_export($dictionary_array) . ';');

As your application is version controlled, use or set the desired dictionary file path to one that is ignored in your .gitignore file, such as var/holidays/holiday_dates.php.

In my Symfony project, I add the known relative and non-relative date values as parameters from the configs to my Holiday service, such as 2001-09-11. I then use a query service to inject the unknown non-relative dates from the database into the Holiday class, such as your hurricane closures. My Holiday service is used throughout the application only using DI, including inside of Twig functions, as opposed to using static method calls, but this could be done by using a CompilerPass, on a static method to set the dates.

Since you are using static methods to directly access the results, it
  would require a major application refactor to any service that uses a Holiday
  static method in favor of using it as a Symfony service.


来源: stackexchange

问:
How to only upload only the filename (not entire directly name+filename) to a google storage bucket
I have found a way to upload multiple csv files at once into a google cloud storage bucket that satisfy certain criteria.  The problem I have is that when they all upload to the google storage bucket, the entire path name of the file is uploaded with it.  I am wanting to upload only the actual file name

I have tried using the os.path.basename but it doesn't work. Is there any other way to obtain just the basename before it gets uploaded OR is there a way simply to rename the file before it gets uploaded?

```<code>import glob
import os
from pathlib import Path
from os import listdir
from google.cloud import storage

GOOGLE_APPLICATION_CREDENTIALS = "O:\My Creds\creds.json"

for file in glob.glob("O:\Team Drives\AU_A\Raw_Dauts\Dynamets\**\*.csv", recursive = True):
   filename = os.path.basename(file)  # throught this would work but doesn't
   storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
   bucket = storage_client.get_bucket('bukcetang81')
   blob = bucket.blob("Dynamic_datasets/" +filename)
   blob.upload_from_filename(filename)
</code>```

答:
I'd suggest that you remove parameter "filename", instead hard code it with the name of the file itself:</p>

```<code>for file in glob.glob("O:\Team Drives\AU_A\Raw_Dauts\Dynamets\**\*.csv", recursive = True):
       storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
       bucket = storage_client.get_bucket('bukcetang81')
       blob = bucket.blob(destination_filename)
       blob.upload_from_filename(source_filename)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have found a way to upload multiple csv files at once into a google cloud storage bucket that satisfy certain criteria.  The problem I have is that when they all upload to the google storage bucket, the entire path name of the file is uploaded with it.  I am wanting to upload only the actual file name

I have tried using the os.path.basename but it doesn't work. Is there any other way to obtain just the basename before it gets uploaded OR is there a way simply to rename the file before it gets uploaded?

import glob
import os
from pathlib import Path
from os import listdir
from google.cloud import storage

GOOGLE_APPLICATION_CREDENTIALS = "O:\My Creds\creds.json"

for file in glob.glob("O:\Team Drives\AU_A\Raw_Dauts\Dynamets\**\*.csv", recursive = True):
   filename = os.path.basename(file)  # throught this would work but doesn't
   storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
   bucket = storage_client.get_bucket('bukcetang81')
   blob = bucket.blob("Dynamic_datasets/" +filename)
   blob.upload_from_filename(filename)

Body:
I'd suggest that you remove parameter "filename", instead hard code it with the name of the file itself:

for file in glob.glob("O:\Team Drives\AU_A\Raw_Dauts\Dynamets\**\*.csv", recursive = True):
       storage_client = storage.Client.from_service_account_json(GOOGLE_APPLICATION_CREDENTIALS)
       bucket = storage_client.get_bucket('bukcetang81')
       blob = bucket.blob(destination_filename)
       blob.upload_from_filename(source_filename)


问:
Multiple value assignment
```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b
</code>```

and

```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b
</code>```

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

答:
```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b
</code>```

In above line of code - after print(a), code value in b variable will be assigned to a first and hence the value of a is updated and the updated value of a is being used in b = a+b

Lets say, a =0, b =1 . So after print(a), value of a will be 1 first and b will have 1+1 =2.

Whereas,

```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b
</code>```

In the above code, after print(a), a and b values are simultaneously assigned. In this case, whatever value of a is printed in print(a) will be used in assigning value for a in further step.

Lets say, a = 0 and b = 1 ,
after print(a) which will print 0 first,  value in a will be 1 and value in b will be 0+1 = 1 because b = a+b will use a =0 and not a =1.

Title: Multiple value assignment

Body:
a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b

and

a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

Body:
a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b

In above line of code - after print(a), code value in b variable will be assigned to a first and hence the value of a is updated and the updated value of a is being used in b = a+b

Lets say, a =0, b =1 . So after print(a), value of a will be 1 first and b will have 1+1 =2.

Whereas,

a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b

In the above code, after print(a), a and b values are simultaneously assigned. In this case, whatever value of a is printed in print(a) will be used in assigning value for a in further step.

Lets say, a = 0 and b = 1 ,
after print(a) which will print 0 first,  value in a will be 1 and value in b will be 0+1 = 1 because b = a+b will use a =0 and not a =1.


问:
determine jpeg filesize without actually saving the jpeg
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

```<code>frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;
</code>```

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

答:
You can to something like this:</p>

```<code>MemoryStream tmpMs = new MemoryStream();
frameNormal.Save(tmpMs, ImageFormat.Jpeg);
long fileSize = tmpMs.Length;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

Body:
You can to something like this:

MemoryStream tmpMs = new MemoryStream();
frameNormal.Save(tmpMs, ImageFormat.Jpeg);
long fileSize = tmpMs.Length;


问:
Release build crashing, while debug build working as expected
Getting following exception when trying to run release build on device.

```<code>   java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.IllegalStateException: com.google.android.gms.measurement.AppMeasurement#getInstance has been removed by Proguard. Add keep rule to prevent it.
            at android.app.ActivityThread.installProvider(ActivityThread.java:6419)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:5961)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5867)
            at android.app.ActivityThread.access$1100(ActivityThread.java:200)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1651)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6692)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
         Caused by: java.lang.IllegalStateException: com.google.android.gms.measurement.AppMeasurement#getInstance has been removed by Proguard. Add keep rule to prevent it.
            at com.google.firebase.FirebaseApp.zza(com.google.firebase:firebase-common@@16.0.1:766)
            at com.google.firebase.FirebaseApp.zze(com.google.firebase:firebase-common@@16.0.1:722)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:329)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:295)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:282)
            at com.google.firebase.provider.FirebaseInitProvider.onCreate(com.google.firebase:firebase-common@@16.0.1:37)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1919)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1894)
            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(com.google.firebase:firebase-common@@16.0.1:31)
            at android.app.ActivityThread.installProvider(ActivityThread.java:6414)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:5961)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5867)
            at android.app.ActivityThread.access$1100(ActivityThread.java:200)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1651)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6692)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

I am using following proguard configuration

```<code>-keepclasseswithmembers class * {
    public static com.google.firebase.auth.FirebaseAuth getInstance();
}
-keep public class com.google.firebase.**
-keep public class com.google.firebase.auth.FirebaseAuth

-keep public class com.google.android.gms.measurement.**
-keep public class com.google.firebase.provider.FirebaseInitProvider
</code>```

答:
You need to add few lines in your Pro-guard:</p>

```<code>#Firebase
-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
-dontwarn org.joda.time.**
-dontwarn org.shaded.apache.**
-dontwarn org.ietf.jgss.**

#GooglePlayServices
-keepnames class com.google.android.gms.** {*;}
</code>```

Body:
Getting following exception when trying to run release build on device.

   java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.IllegalStateException: com.google.android.gms.measurement.AppMeasurement#getInstance has been removed by Proguard. Add keep rule to prevent it.
            at android.app.ActivityThread.installProvider(ActivityThread.java:6419)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:5961)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5867)
            at android.app.ActivityThread.access$1100(ActivityThread.java:200)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1651)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6692)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
         Caused by: java.lang.IllegalStateException: com.google.android.gms.measurement.AppMeasurement#getInstance has been removed by Proguard. Add keep rule to prevent it.
            at com.google.firebase.FirebaseApp.zza(com.google.firebase:firebase-common@@16.0.1:766)
            at com.google.firebase.FirebaseApp.zze(com.google.firebase:firebase-common@@16.0.1:722)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:329)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:295)
            at com.google.firebase.FirebaseApp.initializeApp(com.google.firebase:firebase-common@@16.0.1:282)
            at com.google.firebase.provider.FirebaseInitProvider.onCreate(com.google.firebase:firebase-common@@16.0.1:37)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1919)
            at android.content.ContentProvider.attachInfo(ContentProvider.java:1894)
            at com.google.firebase.provider.FirebaseInitProvider.attachInfo(com.google.firebase:firebase-common@@16.0.1:31)
            at android.app.ActivityThread.installProvider(ActivityThread.java:6414)
            at android.app.ActivityThread.installContentProviders(ActivityThread.java:5961)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5867)
            at android.app.ActivityThread.access$1100(ActivityThread.java:200)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1651)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6692)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I am using following proguard configuration

-keepclasseswithmembers class * {
    public static com.google.firebase.auth.FirebaseAuth getInstance();
}
-keep public class com.google.firebase.**
-keep public class com.google.firebase.auth.FirebaseAuth

-keep public class com.google.android.gms.measurement.**
-keep public class com.google.firebase.provider.FirebaseInitProvider

Body:
You need to add few lines in your Pro-guard:

#Firebase
-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
-dontwarn org.joda.time.**
-dontwarn org.shaded.apache.**
-dontwarn org.ietf.jgss.**

#GooglePlayServices
-keepnames class com.google.android.gms.** {*;}


问:
How to convert a JavaScript array to an object?
I am having an array of arrays in Javascript, like </p>

```<code>[
    ["2019","abc","xyz"],
    ["2014","DEF","PQR"]
]
</code>```

<p>How can I convert the above array into array of objects like, </p>

```<code>[
    {
        date: 2019,
        name:abc,
        address:xyz
    },
    {
        date: 2014,
        name: DEF,
        address: PQR
    }
]
</code>```

答:
You can use Array.map

let arr = [["2019","abc","xyz"],["2014","DEF","PQR"]];
let result = arr.map(([data,name,address]) => ({data, name, address}));
console.log(result);```

Body:
I am having an array of arrays in Javascript, like

[
    ["2019","abc","xyz"],
    ["2014","DEF","PQR"]
]

How can I convert the above array into array of objects like,

[
    {
        date: 2019,
        name:abc,
        address:xyz
    },
    {
        date: 2014,
        name: DEF,
        address: PQR
    }
]


问:
How to use a String in Firebase Database child reference?
I'm trying to give a database reference to upload some data to my Firebase real-time database. I already have some data in the database and I'm retrieving it. I have a spinner in which the User can select a specific user to whom he wants to send the message. So I want to upload the data into the selected user's UID.

I tried retrieving the UID of the selected user directly but it didn't work, so I created a child called UID during the registration process. Now I'm able to retrieve the UID of the selected User and I'm storing it in String 'key'. I want to use 'key' as a child reference in database reference, so that I can upload my data under the selected user. I have checked the value of 'key' and it is the correct UID i.e., the UID of the selected user, but when I use this String in database reference, my app crashes.

```<code>public void onItemSelected(AdapterView<?> adapterView, View view,
                                           int position, long id) {
                    Object item = adapterView.getItemAtPosition(position);
                    NameSelected = item.toString();
                    pris = NameSelected;
                    ref = FirebaseDatabase.getInstance().getReference().child("Faculty_Database");
                    ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for(DataSnapshot datas: dataSnapshot.getChildren()){
                                key = datas.child("UID").getValue(String.class);
                            }
                        }
//

SubmitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (NameEditText.getText().toString().equals("") || PhoneNumberEditText.getText().toString().equals("") || CompanyEditText.getText().toString().equals("") || EmailEditText.getText().toString().equals("") || AppointmentEditText.getText().toString().equals("") || image.equals(null)) {
                Toast.makeText(getApplicationContext(), "Please fill all details", Toast.LENGTH_LONG).show();
            } else {
                final StudentDetails studentDetails = new StudentDetails();
                GetDataFromEditText();
                studentDetails.setName(NameHolder);
                studentDetails.setPhoneNumber(NumberHolder);
                studentDetails.setemail(EmailHolder);
                studentDetails.setCompanyName(CompanyHolder);
                studentDetails.setAppointment(AppointmentHolder);
                studentDetails.setNameSelected(NameSelected);

                // Getting the ID from firebase database.
                final String StudentRecordIDFromServer = databaseReference.push().getKey();

                filePath = FirebaseStorage.getInstance().getReference().child("Visitors");
                ByteArrayOutputStream baos =  new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] dataToUpload = baos.toByteArray();
                UploadTask uploadTask = filePath.putBytes(dataToUpload);

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }

                        // Continue with the task to get the download URL
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            downloadUri= task.getResult();
                                databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
                                Map<String, Object> mapToUpload = new HashMap<>();
                                mapToUpload.put("imageUrl", downloadUri.toString());
                                mapToUpload.put("Data", studentDetails);
                                databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
                        } else {
                            // Handle failures
                            // ...
                        }
                    }
                });
            }
            // Showing Toast message after successfully data submit.
            Toast.makeText(SecurityActivity.this, "Request Sent Successfully!", Toast.LENGTH_LONG).show();
        }
    });
</code>```

This is my database

Please let me know how I can create a child called "Receieved" under the selected User's UID to upload my data?

答:
Add the code that sets data inside the onDataChange method, since onDataChange is asynchronous meaning that the code where you are setting the data is getting executed before retrieving the key.

```<code> ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
    @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot datas: dataSnapshot.getChildren()){

       key = datas.child("UID").getValue(String.class);
      databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
      Map<String, Object> mapToUpload = new HashMap<>();
      mapToUpload.put("imageUrl", downloadUri.toString());
      mapToUpload.put("Data", studentDetails);
      databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
          }
    }
</code>```

Body:
I'm trying to give a database reference to upload some data to my Firebase real-time database. I already have some data in the database and I'm retrieving it. I have a spinner in which the User can select a specific user to whom he wants to send the message. So I want to upload the data into the selected user's UID.

I tried retrieving the UID of the selected user directly but it didn't work, so I created a child called UID during the registration process. Now I'm able to retrieve the UID of the selected User and I'm storing it in String 'key'. I want to use 'key' as a child reference in database reference, so that I can upload my data under the selected user. I have checked the value of 'key' and it is the correct UID i.e., the UID of the selected user, but when I use this String in database reference, my app crashes.

public void onItemSelected(AdapterView<?> adapterView, View view,
                                           int position, long id) {
                    Object item = adapterView.getItemAtPosition(position);
                    NameSelected = item.toString();
                    pris = NameSelected;
                    ref = FirebaseDatabase.getInstance().getReference().child("Faculty_Database");
                    ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            for(DataSnapshot datas: dataSnapshot.getChildren()){
                                key = datas.child("UID").getValue(String.class);
                            }
                        }
//

SubmitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (NameEditText.getText().toString().equals("") || PhoneNumberEditText.getText().toString().equals("") || CompanyEditText.getText().toString().equals("") || EmailEditText.getText().toString().equals("") || AppointmentEditText.getText().toString().equals("") || image.equals(null)) {
                Toast.makeText(getApplicationContext(), "Please fill all details", Toast.LENGTH_LONG).show();
            } else {
                final StudentDetails studentDetails = new StudentDetails();
                GetDataFromEditText();
                studentDetails.setName(NameHolder);
                studentDetails.setPhoneNumber(NumberHolder);
                studentDetails.setemail(EmailHolder);
                studentDetails.setCompanyName(CompanyHolder);
                studentDetails.setAppointment(AppointmentHolder);
                studentDetails.setNameSelected(NameSelected);

                // Getting the ID from firebase database.
                final String StudentRecordIDFromServer = databaseReference.push().getKey();

                filePath = FirebaseStorage.getInstance().getReference().child("Visitors");
                ByteArrayOutputStream baos =  new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] dataToUpload = baos.toByteArray();
                UploadTask uploadTask = filePath.putBytes(dataToUpload);

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                        if (!task.isSuccessful()) {
                            throw task.getException();
                        }

                        // Continue with the task to get the download URL
                        return filePath.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            downloadUri= task.getResult();
                                databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
                                Map<String, Object> mapToUpload = new HashMap<>();
                                mapToUpload.put("imageUrl", downloadUri.toString());
                                mapToUpload.put("Data", studentDetails);
                                databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
                        } else {
                            // Handle failures
                            // ...
                        }
                    }
                });
            }
            // Showing Toast message after successfully data submit.
            Toast.makeText(SecurityActivity.this, "Request Sent Successfully!", Toast.LENGTH_LONG).show();
        }
    });

This is my database

Please let me know how I can create a child called "Receieved" under the selected User's UID to upload my data?

Body:
Add the code that sets data inside the onDataChange method, since onDataChange is asynchronous meaning that the code where you are setting the data is getting executed before retrieving the key.

 ref.orderByChild("Name").equalTo(pris).addValueEventListener(new ValueEventListener(){
    @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot datas: dataSnapshot.getChildren()){

       key = datas.child("UID").getValue(String.class);
      databaseReference = FirebaseDatabase.getInstance().getReference().child("Faculty_Database").child(key).child("Received");
      Map<String, Object> mapToUpload = new HashMap<>();
      mapToUpload.put("imageUrl", downloadUri.toString());
      mapToUpload.put("Data", studentDetails);
      databaseReference.child(StudentRecordIDFromServer).setValue(mapToUpload);
          }
    }


问:
I2C PROGRAMMING ON ARM
I'm unable to use I2C on an ARM CORTEX M3 process.
What am I doing wrong? Which test could I perform to find the problem?

It is a GD32F130C8 (master) and I'm programming it with KEIL (using the GD32F1x0 Firmware Library)

The slave is a MPU-6050 (accelorometer)

I defined the variable with local address and MPU-6050 device:

```<code>      #define I2C_ACCELEROMETER_ADDRESS 0xD0 //( 0x68 + one bit)
      #define I2C_OWN_ADDRESS 0x72
</code>```

Then I initialized the I2C PIN this way:

```<code>    //Init I2C communication to accelerometer
    // enable I2C0 clock
    rcu_periph_clock_enable(RCU_I2C0);
    // connect PB8 to I2C0_SCL
    gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_8);
    // connect PB9 to I2C0_SDA
    gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_9);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP,GPIO_PIN_8);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ,GPIO_PIN_8);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP,GPIO_PIN_9);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ,GPIO_PIN_9);
</code>```

Then I initialized the I2C this way:

```<code>    void I2C_Accelerometer_init(void){
        // configure I2C0 clock
        i2c_clock_config(I2C0, 100000, I2C_DTCY_2);
        // configure I2C0 address
        i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C_OWN_ADDRESS);
        // enable I2C0
        i2c_enable(I2C0);
        // enable acknowledge
        i2c_ack_config(I2C0, I2C_ACK_ENABLE);
    }
</code>```

Then periodically (each second) I try to get the data from the accelerometer.
There is no error but the variable "accelerometer_x_high" is always zero (this is basically my problem).

The following code is executed each second. As you can see I set power management to 0, then I request register with accelerometer data, then I try to get the data from the slave device:

```<code>    extern uint8_t Accelerometer_X_High;

    //periodically called by timers in it.c
    void GetAccelerometerData(void){
        uint8_t bytesToReadIndex=0;

        //WAKE UP ACCELEROMETER (6B 00)

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);

        // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));

        // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_TRANSMITTER);

        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));

      // clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

    // send a data byte
      i2c_data_transmit(I2C0,0x6B);  //PWR MANAGEMENT
      // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));
        // send a data byte
      i2c_data_transmit(I2C0,0x00);  //WAKE UP
        // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));

    // send a stop condition to I2C bus
      i2c_stop_on_bus(I2C0);

      while(I2C_CTL0(I2C0)&0x0200);

        //REQUEST ACELEROMETER DATA (3B )

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);

        // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));

        // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_TRANSMITTER);

        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));
      // clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

    // send a data byte
      i2c_data_transmit(I2C0,0x3B);  //ACCELEROMETER REGISTER
      // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));

    // send a stop condition to I2C bus
      i2c_stop_on_bus(I2C0);

      while(I2C_CTL0(I2C0)&0x0200);

        //now reopen the bus to receive the reply

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);
      // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));
      // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_RECEIVER);
        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));

        // if we receive only one byte: reset ACKEN bit
      i2c_ack_config(I2C0, I2C_ACK_DISABLE);

      //clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

      // if we receive only one byte: send stop condition
      i2c_stop_on_bus(I2C0);

      /* wait until the RBNE bit is set */
      while(!i2c_flag_get(I2C0, I2C_FLAG_RBNE));
      //read a data from I2C_DATA
      Accelerometer_X_High = i2c_data_receive(I2C0);

      // if we receive more bytes: send a stop condition to I2C bus
      //i2c_stop_on_bus(I2C0);
      while(I2C_CTL0(I2C0)&0x0200);
      // enable acknowledge
      i2c_ack_config(I2C0, I2C_ACK_ENABLE);

    }
</code>```

acquiring signals with oscilloscope I get the following result:

this is a screenshot with entire signal:
http://www.tr3ma.com/Dati/IMG_1526.JPG

On the signal there are also strange spikes:

http://www.tr3ma.com/Dati/spike1.JPG

 http://www.tr3ma.com/Dati/spike2.JPG

 http://www.tr3ma.com/Dati/spike3.JPG

 http://www.tr3ma.com/Dati/spike4.JPG

答: It works. I created a loop to read all the registers and I was able to read the entire content of the chip. There is no error on the firmware. The only problem is that the chip is not the one that I supposed it to be. I have to find the right part number of accelerometer and find the register to wake it up.</p>

Title: I2C PROGRAMMING ON ARM

Body:
I'm unable to use I2C on an ARM CORTEX M3 process.
What am I doing wrong? Which test could I perform to find the problem?

It is a GD32F130C8 (master) and I'm programming it with KEIL (using the GD32F1x0 Firmware Library)

The slave is a MPU-6050 (accelorometer)

I defined the variable with local address and MPU-6050 device:

      #define I2C_ACCELEROMETER_ADDRESS 0xD0 //( 0x68 + one bit)
      #define I2C_OWN_ADDRESS 0x72

Then I initialized the I2C PIN this way:

    //Init I2C communication to accelerometer
    // enable I2C0 clock
    rcu_periph_clock_enable(RCU_I2C0);
    // connect PB8 to I2C0_SCL
    gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_8);
    // connect PB9 to I2C0_SDA
    gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_9);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP,GPIO_PIN_8);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ,GPIO_PIN_8);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP,GPIO_PIN_9);
    gpio_output_options_set(GPIOB, GPIO_OTYPE_OD, GPIO_OSPEED_50MHZ,GPIO_PIN_9);

Then I initialized the I2C this way:

    void I2C_Accelerometer_init(void){
        // configure I2C0 clock
        i2c_clock_config(I2C0, 100000, I2C_DTCY_2);
        // configure I2C0 address
        i2c_mode_addr_config(I2C0, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C_OWN_ADDRESS);
        // enable I2C0
        i2c_enable(I2C0);
        // enable acknowledge
        i2c_ack_config(I2C0, I2C_ACK_ENABLE);
    }

Then periodically (each second) I try to get the data from the accelerometer.
There is no error but the variable "accelerometer_x_high" is always zero (this is basically my problem).

The following code is executed each second. As you can see I set power management to 0, then I request register with accelerometer data, then I try to get the data from the slave device:

    extern uint8_t Accelerometer_X_High;

    //periodically called by timers in it.c
    void GetAccelerometerData(void){
        uint8_t bytesToReadIndex=0;

        //WAKE UP ACCELEROMETER (6B 00)

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);

        // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));

        // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_TRANSMITTER);

        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));

      // clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

    // send a data byte
      i2c_data_transmit(I2C0,0x6B);  //PWR MANAGEMENT
      // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));
        // send a data byte
      i2c_data_transmit(I2C0,0x00);  //WAKE UP
        // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));

    // send a stop condition to I2C bus
      i2c_stop_on_bus(I2C0);

      while(I2C_CTL0(I2C0)&0x0200);

        //REQUEST ACELEROMETER DATA (3B )

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);

        // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));

        // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_TRANSMITTER);

        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));
      // clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

    // send a data byte
      i2c_data_transmit(I2C0,0x3B);  //ACCELEROMETER REGISTER
      // wait until the transmission data register is empty
      while(!i2c_flag_get(I2C0, I2C_FLAG_TBE));

    // send a stop condition to I2C bus
      i2c_stop_on_bus(I2C0);

      while(I2C_CTL0(I2C0)&0x0200);

        //now reopen the bus to receive the reply

        // wait until I2C bus is idle
      while(i2c_flag_get(I2C0, I2C_FLAG_I2CBSY));
      // send a start condition to I2C bus
      i2c_start_on_bus(I2C0);
      // wait until SBSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_SBSEND));
      // send slave address to I2C bus
      i2c_master_addressing(I2C0, I2C_ACCELEROMETER_ADDRESS, I2C_RECEIVER);
        // wait until ADDSEND bit is set
      while(!i2c_flag_get(I2C0, I2C_FLAG_ADDSEND));

        // if we receive only one byte: reset ACKEN bit
      i2c_ack_config(I2C0, I2C_ACK_DISABLE);

      //clear ADDSEND bit
      i2c_flag_clear(I2C0, I2C_FLAG_ADDSEND);

      // if we receive only one byte: send stop condition
      i2c_stop_on_bus(I2C0);

      /* wait until the RBNE bit is set */
      while(!i2c_flag_get(I2C0, I2C_FLAG_RBNE));
      //read a data from I2C_DATA
      Accelerometer_X_High = i2c_data_receive(I2C0);

      // if we receive more bytes: send a stop condition to I2C bus
      //i2c_stop_on_bus(I2C0);
      while(I2C_CTL0(I2C0)&0x0200);
      // enable acknowledge
      i2c_ack_config(I2C0, I2C_ACK_ENABLE);

    }

acquiring signals with oscilloscope I get the following result:

this is a screenshot with entire signal:
http://www.tr3ma.com/Dati/IMG_1526.JPG

On the signal there are also strange spikes:

http://www.tr3ma.com/Dati/spike1.JPG

 http://www.tr3ma.com/Dati/spike2.JPG

 http://www.tr3ma.com/Dati/spike3.JPG

 http://www.tr3ma.com/Dati/spike4.JPG


答:
You can use Array.map to build desired format, here i am Destructuring element from each array as date, name, and address and than returning an object with these key/value pair

let data =  [["2019","abc","xyz"],["2014","DEF","PQR"]]

let op = data.map(([date, name, address]) => ({date, name, address}))

console.log(op)```

Title: How to convert a JavaScript array to an object?


问:
Wpf RichTextBox change key to line break;
I can use Enter key to start a new line but can I use Ctrl+Enter instead?

I want to use Enter key to do other thing.

The KeyDown event I tried not work.

it is always start a new line when I press Enter.

答:
You can set the value for property AcceptsReturn to false and handle the ctrl + enter key by creating an event handler for PreviewKeyDown event like this:

(rtb is name of the RichTextBox)

```<code>private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter && Keyboard.IsKeyDown(Key.LeftCtrl))
    {
        // do whatever you want
        // if u want to add a new line just uncomment the next lines
        // rtb.AppendText(Environment.NewLine);
        // rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
        e.Handled = true;
    }
}
</code>```

Body:
You can set the value for property AcceptsReturn to false and handle the ctrl + enter key by creating an event handler for PreviewKeyDown event like this:

(rtb is name of the RichTextBox)

private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter && Keyboard.IsKeyDown(Key.LeftCtrl))
    {
        // do whatever you want
        // if u want to add a new line just uncomment the next lines
        // rtb.AppendText(Environment.NewLine);
        // rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
        e.Handled = true;
    }
}


问:
readQuery from cache results in Can't find field <field> on object undefined
I'm getting started with graphQL and apollo. I'm doing some simple queries and mutations fine but when I try to access data from apollo cache I keep getting "Can't find field me on object undefined" but when using apollo chrome plugin it returns data correct.

When logged into my app I run a simple query that fetches the user object from the server. It logs correct, I can see in chome dev apollo under queries and cache that my user data is there.

```<code>const ME_QUERY = gql`
query {
    me {
    _id
    username
    password
    exchanges {
        name
        active
        }
    }
}
`;

<Query query={ME_QUERY}>
  {({loading, error, data}) => {
    if (error) {
      return <Error error={error.message} />;
    }
    if (data) {
      console.log(data, 'data');
    }
    return <div>asdf</div>
  }}
</Query>
</code>```

I have wrapped withApollo and I can log the client object fine in the component where I'm trying to query. I run the following code:

```<code>componentDidMount() {
    console.log(this.props.client.readQuery, 'propps');
    const  user = this.props.client.readQuery({
        query: gql`
{
  me {
    _id
    username
    password
    exchanges {
      name
      active
    }
  }
}
      `
});
console.log(user, 'user');
</code>```

And that results in Uncaught Error: Can't find field me on object undefined Ive also tried with adding variables but it doesn't help.

Which object is undefined? Any idea why my query fails?

答:
You are probably using Apollo Client > 2.5 which handles state locally.
Read the migration guide for more information.

Use the default client resolver to resolve your local state

Use cache.write to write default data into your cache. This is the part of the migration that causes your crash.

Body:
I'm getting started with graphQL and apollo. I'm doing some simple queries and mutations fine but when I try to access data from apollo cache I keep getting "Can't find field me on object undefined" but when using apollo chrome plugin it returns data correct.

When logged into my app I run a simple query that fetches the user object from the server. It logs correct, I can see in chome dev apollo under queries and cache that my user data is there.

const ME_QUERY = gql`
query {
    me {
    _id
    username
    password
    exchanges {
        name
        active
        }
    }
}
`;

<Query query={ME_QUERY}>
  {({loading, error, data}) => {
    if (error) {
      return <Error error={error.message} />;
    }
    if (data) {
      console.log(data, 'data');
    }
    return
asdf

  }}
</Query>

I have wrapped withApollo and I can log the client object fine in the component where I'm trying to query. I run the following code:

componentDidMount() {
    console.log(this.props.client.readQuery, 'propps');
    const  user = this.props.client.readQuery({
        query: gql`
{
  me {
    _id
    username
    password
    exchanges {
      name
      active
    }
  }
}
      `
});
console.log(user, 'user');

And that results in Uncaught Error: Can't find field me on object undefined Ive also tried with adding variables but it doesn't help.

Which object is undefined? Any idea why my query fails?


问:
OpenMP GPU offloading math library?
I am trying to offload code the GPU using OpenMP 4+ directives.  I am using ubuntu 16.04 with GCC 7.2 and for general cases it is working fine.  My problem comes when I am trying to offload a code that has a call to the sqrtf function that is defined in "math.h". The troubeling code is this:

```<code>#pragma omp target teams distribute \
map(to:posx[:n],posy[:n],posz[:n]) \
map(from:frcx[:n],frcy[:n],frcz[:n])
for (int i = 0; i < n; i++) {
  frcx[i] = 0.0f;
  frcy[i] = 0.0f;
  frcz[i] = 0.0f;

  for (int j = 0; j < n; j++) {
    float dx = posx[j] - posx[i];
    float dy = posy[j] - posy[i];
    float dz = posz[j] - posz[i];
    float distSqr = dx*dx + dy*dy + dz*dz + SOFTENING;
    float invDist = 1.0f / sqrtf(distSqr);
    float invDist3 = invDist * invDist * invDist;

    frcx[i] += dx * invDist3;
    frcy[i] += dy * invDist3;
    frcz[i] += dz * invDist3;
  }
}
</code>```

When I try to compile it with:

```<code>$ gcc -Wall -O2 -march=native -mtune=native -fopenmp -o nbody_cpu_arrays_parallel_gpu common_funcs.c nbody_cpu_arrays_parallel_gpu.c -lm
unresolved symbol sqrtf
collect2: error: ld returned 1 exit status
mkoffload: fatal error: x86_64-linux-gnu-accel-nvptx-none-gcc-7 returned 1 exit status
compilation terminated.
lto-wrapper: fatal error: /usr/lib/gcc/x86_64-linux-gnu/7//accel/nvptx-none/mkoffload returned 1 exit status
compilation terminated.
/usr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
</code>```

How can I make use of square root operations (or other mathematical functions) when offloading OMP code to GPUs?

答:
clang 9.0 now has the feature that replace the standard math library function with equivelant version of ptx code (nvidia gpu ), which is not yet supported by gcc 9.0.

Compile and run: https://www.hahnjo.de/blog/2018/10/08/clang-7.0-openmp-offloading-nvidia.html

commit of clang : https://reviews.llvm.org/D61399

Title: OpenMP GPU offloading math library?

Body:
I am trying to offload code the GPU using OpenMP 4+ directives.  I am using ubuntu 16.04 with GCC 7.2 and for general cases it is working fine.  My problem comes when I am trying to offload a code that has a call to the sqrtf function that is defined in "math.h". The troubeling code is this:

#pragma omp target teams distribute \
map(to:posx[:n],posy[:n],posz[:n]) \
map(from:frcx[:n],frcy[:n],frcz[:n])
for (int i = 0; i < n; i++) {
  frcx[i] = 0.0f;
  frcy[i] = 0.0f;
  frcz[i] = 0.0f;

  for (int j = 0; j < n; j++) {
    float dx = posx[j] - posx[i];
    float dy = posy[j] - posy[i];
    float dz = posz[j] - posz[i];
    float distSqr = dx*dx + dy*dy + dz*dz + SOFTENING;
    float invDist = 1.0f / sqrtf(distSqr);
    float invDist3 = invDist * invDist * invDist;

    frcx[i] += dx * invDist3;
    frcy[i] += dy * invDist3;
    frcz[i] += dz * invDist3;
  }
}

When I try to compile it with:

$ gcc -Wall -O2 -march=native -mtune=native -fopenmp -o nbody_cpu_arrays_parallel_gpu common_funcs.c nbody_cpu_arrays_parallel_gpu.c -lm
unresolved symbol sqrtf
collect2: error: ld returned 1 exit status
mkoffload: fatal error: x86_64-linux-gnu-accel-nvptx-none-gcc-7 returned 1 exit status
compilation terminated.
lto-wrapper: fatal error: /usr/lib/gcc/x86_64-linux-gnu/7//accel/nvptx-none/mkoffload returned 1 exit status
compilation terminated.
/usr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status

How can I make use of square root operations (or other mathematical functions) when offloading OMP code to GPUs?


问:
Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

```<code> var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error
</code>```

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

答:
Unlike in objective C, you can not do operation on 2-different type of variables (as Swift Language is Type-Safe).

To do any arithmetic calculation the type of both operand must be same.

If you do not specify the type of the variable then swift inferences the type from its value.

For eg.

```<code>let a = 10    //Swift consider it -> Int type
let b = 20.0  //Swift consider it -> Double type

let result = a * b  //Gives compile time error for the operand type

let result = Double(a) * b  //No error, as Int is converted to Double
</code>```

Body:
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

 var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

Body:
Unlike in objective C, you can not do operation on 2-different type of variables (as Swift Language is Type-Safe).

To do any arithmetic calculation the type of both operand must be same.

If you do not specify the type of the variable then swift inferences the type from its value.

For eg.

let a = 10    //Swift consider it -> Int type
let b = 20.0  //Swift consider it -> Double type

let result = a * b  //Gives compile time error for the operand type

let result = Double(a) * b  //No error, as Int is converted to Double


答:
a simple routine

var arr = [["2019","abc","xyz"],["2014","DEF","PQR"]];

var output = [];

arr.forEach(function(el){

    output.push({
        date: el[0],
        name: el[1],
        address: el[2]
    });
});

console.log(output)```


问:
How to unit test a method with enum parameters?
I'm using junit and EasyMock to do unit testing on a project I'm working on. However, I've run into a problem. I have a good handful of methods that have a parameter that is an enumeration.

I ran into the java.lang.NullPointerException when attempting to mock the enum, and it seems enums just cannot be mocked. More information I found on it here:

http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html

Is there any good way to unit test this method without mocking the enum??

Thanks!

EDIT: Péter Török was right! I was completely looking over the fact that I could just plug in something for the enum. For example:

public void methodName(String description, Location buildingLocation) {

where Location is my enum, I can call the method as:

methodName("here is my description", Location.DENVER);

答:
What does your enum contain that you need to mock it? Why can't you just simply use the available values themselves?

Since enums are (supposed to be) stateless and immutable, they should be readily available for unit testing, you should have no problems in instantiating them, they should hold no (mutable) global state and should have no external dependencies which make them hard to use in unit tests.

Failing any of the above would be a sign of a design problem to me rather than a unit testing problem.


问:
How can I individually replace each occurence of a string?
I am trying to replace every occurrence of a space with two random characters (out of 103). The problem is that it is always the same 2 characters every time, which makes sense if you look at the code

I'm pretty new to  Swift and Xcode and I've already tried a bunch of things, like using a "for" loop.

```<code>newSentence = passedSentence.replacingOccurrences(of: " ", with: " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) ")
resultText.text = newSentence
</code>```

As I said before, it is always the same 2 characters when I want it to "refresh" for every occurrence of a space.

答:
Using map(_:) method instead of replacingOccurrences(of:with:) to get the desired result.

replacingOccurrences(of:with:)

A new string in which all occurrences of target in the receiver are
  replaced by replacement.

It replaces all the occurrences with the same instance that is passed in the replacementString i.e. randomArray[Int.random(in: 0...103) (randomArray[Int.random(in: 0...103)] is executed only once and used throughout the string for all occurrences of " ".

```<code>    let passedSentence = "This is a sample sentence"

    let newSentence = (passedSentence.map { (char) -> String in
        if char == " " {
            return " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) "
        }
        return String(char)
    }).joined()

    print(newSentence)
</code>```

In case the you're using the whole range of randomArray, i.e. if randomArray contains 104 elements i.e. 0...103, you can directly use randomElement() on randomArray instead of using random(in:) on Int, i.e.

Use

```<code>randomArray.randomElement()
</code>```

instead of

```<code>randomArray[Int.random(in: 0...103)]
</code>```

Body:
I am trying to replace every occurrence of a space with two random characters (out of 103). The problem is that it is always the same 2 characters every time, which makes sense if you look at the code

I'm pretty new to  Swift and Xcode and I've already tried a bunch of things, like using a "for" loop.

newSentence = passedSentence.replacingOccurrences(of: " ", with: " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) ")
resultText.text = newSentence

As I said before, it is always the same 2 characters when I want it to "refresh" for every occurrence of a space.

Body:
Using map(_:) method instead of replacingOccurrences(of:with:) to get the desired result.

replacingOccurrences(of:with:)

A new string in which all occurrences of target in the receiver are
  replaced by replacement.

It replaces all the occurrences with the same instance that is passed in the replacementString i.e. randomArray[Int.random(in: 0...103) (randomArray[Int.random(in: 0...103)] is executed only once and used throughout the string for all occurrences of " ".

    let passedSentence = "This is a sample sentence"

    let newSentence = (passedSentence.map { (char) -> String in
        if char == " " {
            return " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) "
        }
        return String(char)
    }).joined()

    print(newSentence)

In case the you're using the whole range of randomArray, i.e. if randomArray contains 104 elements i.e. 0...103, you can directly use randomElement() on randomArray instead of using random(in:) on Int, i.e.

Use

randomArray.randomElement()

instead of

randomArray[Int.random(in: 0...103)]


问:
java.io.IOException: setDataSource failed
I'm trying to play a video using FullscreenVideoView but i keep getting this error everytime that i try to play a stored video</p>

```<code>Java.io.IOException: setDataSource failed.

 File n  = new File(getApplicationContext().getFilesDir()+"/Downloads/video9.mp4");
        Log.e(TAG, "URL:" + n);

        fullscreenVideoView.videoFile(n).enableAutoStart().fastForwardSeconds(5)
                .rewindSeconds(5)
                .addSeekBackwardButton()
                .addSeekForwardButton();
</code>```

答:
There are bunch of reasons, why your dataSource doesn't work.
Try to add logging:

```<code> File n  = new File(getApplicationContext().getFilesDir()+"/Downloads/video9.mp4");
        Log.e(TAG, "URL:" + n);
        Log.e(TAG, "exists: " + n.exists());

        fullscreenVideoView.videoFile(n).enableAutoStart().fastForwardSeconds(5)
                .rewindSeconds(5)
                .addSeekBackwardButton()
                .addSeekForwardButton();
</code>```

Probably file doesn't exist. It may be because of not granted permissions or the wrong way of file.

At first I would advise you ti check permissions. If you running your code on app on 6+ android, you must request permissions in runtime. In your case they would be: READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE.

Body:
I'm trying to play a video using FullscreenVideoView but i keep getting this error everytime that i try to play a stored video

Java.io.IOException: setDataSource failed.

 File n  = new File(getApplicationContext().getFilesDir()+"/Downloads/video9.mp4");
        Log.e(TAG, "URL:" + n);

        fullscreenVideoView.videoFile(n).enableAutoStart().fastForwardSeconds(5)
                .rewindSeconds(5)
                .addSeekBackwardButton()
                .addSeekForwardButton();

Body:
There are bunch of reasons, why your dataSource doesn't work.
Try to add logging:

 File n  = new File(getApplicationContext().getFilesDir()+"/Downloads/video9.mp4");
        Log.e(TAG, "URL:" + n);
        Log.e(TAG, "exists: " + n.exists());

        fullscreenVideoView.videoFile(n).enableAutoStart().fastForwardSeconds(5)
                .rewindSeconds(5)
                .addSeekBackwardButton()
                .addSeekForwardButton();

Probably file doesn't exist. It may be because of not granted permissions or the wrong way of file.

At first I would advise you ti check permissions. If you running your code on app on 6+ android, you must request permissions in runtime. In your case they would be: READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE.


问:
Amazon S3 - How to fix 'The request signature we calculated does not match the signature' error?
I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.

I am on AWS SDK for PHP V2.8.7 running on PHP 5.3.

I am trying to connect to my Amazon S3 bucket with the following code:

// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');

// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');

$bucket = "xxx";
$keyname = "xxx";

try {
    $result = $s3Client->putObject(array(
        'Bucket' => $bucket,
        'Key' => $keyname,
        'Body' => 'Hello World!'
    ));

    $file_error = false;
} catch (Exception $e) {
    $file_error = true;

    echo $e->getMessage();

    die();
}
```
<p>My config.php file is as follows:</p>
<pre class="lang-php prettyprint-override"><code>return [
    // Bootstrap the configuration file with AWS specific features
    'includes' => ['_aws'],
    'services' => [
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => [
            'params' => [
                'credentials' => [
                    'key'    => 'key',
                    'secret' => 'secret'
                ]
            ]
        ]
    ]
];
</code>```

It is producing the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.

答: I had the same issue. I had the default method, PUT set to define the pre-signed URL but was trying to perform a GET. The error was due to method mismatch.</p>

Body:
I have searched on the web for over two days now, and probably have looked through most of the online documented scenarios and workarounds, but nothing worked for me so far.

I am on AWS SDK for PHP V2.8.7 running on PHP 5.3.

I am trying to connect to my Amazon S3 bucket with the following code:

// Create a `Aws` object using a configuration file
$aws = Aws::factory('config.php');

// Get the client from the service locator by namespace
$s3Client = $aws->get('s3');

$bucket = "xxx";
$keyname = "xxx";

try {
    $result = $s3Client->putObject(array(
        'Bucket' => $bucket,
        'Key' => $keyname,
        'Body' => 'Hello World!'
    ));

    $file_error = false;
} catch (Exception $e) {
    $file_error = true;

    echo $e->getMessage();

    die();
}

My config.php file is as follows:

return [
    // Bootstrap the configuration file with AWS specific features
    'includes' => ['_aws'],
    'services' => [
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => [
            'params' => [
                'credentials' => [
                    'key'    => 'key',
                    'secret' => 'secret'
                ]
            ]
        ]
    ]
];

It is producing the following error:

The request signature we calculated does not match the signature you provided. Check your key and signing method.

I've already checked my access key and secret at least 20 times, generated new ones, used different methods to pass in the information (i.e. profile and including credentials in code) but nothing is working at the moment.


问:
How to pass text value to action parameter?
i need to pass input value to action method in controller

i have text and button , so I need to click on the button and take the value of input to parameter and re back to the same view but in post status

i tried many things but not works

i tried to create post form and the type of button is submit but does not work

this is my view code

```<code><form method="post">
    <input  type="text" id="Comments" , name="ID" value="" />
    <button type="submit">Go</button>

</form>
</code>```

this is my controller code

```<code> public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
</code>```

答:
In your view model use @Html.BeginForm redirect to action method in controller.

In View

```<code>@using (Html.BeginForm("youractionname", "yourcontrollername",FormMethod.Post, new { @class = "form-horizontal"}))
{
<input type="text" id="Comments" name="ID" />
    <button type="submit">Go</button>
}
</code>```

In Controller

```<code>public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
    [HttpPost]
    public ActionResult Index(int ID)
    {
        Entities db = new Entities();
        var Query = from Acc in db.tbl_Accounts
                    where Acc.id== ID
                    select Acc ;

        var accList= Query.ToList<tbl_Accounts>();
        return View(accList);

    }
</code>```

You have taken an integer datatype in the action method so that you enter the digit value in the textbox

Note: Please verify your action and controller name In view Model

Body:
i need to pass input value to action method in controller

i have text and button , so I need to click on the button and take the value of input to parameter and re back to the same view but in post status

i tried many things but not works

i tried to create post form and the type of button is submit but does not work

this is my view code

<form method="post">
    <input  type="text" id="Comments" , name="ID" value="" />
    <button type="submit">Go</button>

</form>

this is my controller code

 public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
        [HttpPost]
        public ActionResult Index(int ID)
        {
            Entities db = new Entities();
            var Query = from Acc in db.tbl_Accounts
                        where Acc.id== ID
                        select Acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }

Body:
In your view model use @Html.BeginForm redirect to action method in controller.

In View

@using (Html.BeginForm("youractionname", "yourcontrollername",FormMethod.Post, new { @class = "form-horizontal"}))
{
<input type="text" id="Comments" name="ID" />
    <button type="submit">Go</button>
}

In Controller

public ActionResult Index()
        {
            Entities db = new Entities();
            var Query = from acc in db.tbl_Accounts
                        select acc ;

            var accList= Query.ToList<tbl_Accounts>();
            return View(accList);

        }
    [HttpPost]
    public ActionResult Index(int ID)
    {
        Entities db = new Entities();
        var Query = from Acc in db.tbl_Accounts
                    where Acc.id== ID
                    select Acc ;

        var accList= Query.ToList<tbl_Accounts>();
        return View(accList);

    }

You have taken an integer datatype in the action method so that you enter the digit value in the textbox

Note: Please verify your action and controller name In view Model


问:
How to make AOS not working with Slick slider?
I am using AOS to show html elements on scroll. It works well alone, but when I use it on the pages that contains Slick slider, the elements on which is AOS applied are not showing. Elements are hidden and if there is a lot scroll, it looks like the browser gives wrong information to AOS about current scrolling position and some elements are shown latter.

There is no specific code that makes this problems, any usage of slick on the same page with AOS makes AOS not working.

Did anyone solved this problem, I saw some pending questions on other websites and didn't find any solution?

答:
```<code>$(document).ready(function () {

        $('#hero-slider').on('init', function (e, slick) {

            var$firstAnimatingElements = $('div.hero-slide:first-child').find('[data-animation]');

            doAnimations($firstAnimatingElements);

        });

        $('#hero-slider').on('beforeChange', function (e, slick, currentSlide, nextSlide) {

            var$animatingElements = $('div.hero-slide[data-slick-index="' + nextSlide + '"]').find('[data-animation]');

            doAnimations($animatingElements);

        });

        $('#hero-slider').slick({

            // autoplay: true,

            // autoplaySpeed: 10000,

            dots: true,

            fade: true

        });

        functiondoAnimations(elements) {

            varanimationEndEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';

            elements.each(function () {

                var$this = $(this);

                var$animationDelay = $this.data('delay');

                var$animationType = 'animated ' + $this.data('animation');

                $this.css({

                    'animation-delay': $animationDelay,

                    '-webkit-animation-delay': $animationDelay

                });

                $this.addClass($animationType).one(animationEndEvents, function () {

                    $this.removeClass($animationType);
                });
            });
        }
    });
</code>```


问:
Problem with starting OpenOffice service (soffice) from Java (command working in commandline, but not from Java)
I want to exceute a simple command which works from the shell but doesn't work from Java.
This is the command I want to execute, which works fine:

```<code>soffice -headless "-accept=socket,host=localhost,port=8100;urp;"
</code>```

This is the code I am excecuting from Java trying to run this command:

```<code>String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""};
Process process = Runtime.getRuntime().exec(commands)
int code = process.waitFor();
if(code == 0)
    System.out.println("Commands executed successfully");
</code>```

When I run this program I get "Commands executed successfully".
However the process is not running when the program finishes.
Is it possible that the JVM kills the program after it has run?

Why doesn't this work?

答:
"/Applications/OpenOffice.org\ 2.4.app/Contents/MacOS/soffice.bin -headless -nofirststartwizard -accept='socket,host=localhost,port=8100;urp;StartOffice.Service'"

or simply escaping the quotes will work as well.  We feed a command like this to an ant script that ultimately ends up in an exec call like you have above.  I would also recommend restarting the process every 500 or so conversions because OOO does not properly free memory (depending on what version you are running).

OwnerDisplayName: Shervin

ContentLicense: CC BY-SA 2.5

Body:
I want to exceute a simple command which works from the shell but doesn't work from Java.
This is the command I want to execute, which works fine:

soffice -headless "-accept=socket,host=localhost,port=8100;urp;"

This is the code I am excecuting from Java trying to run this command:

String[] commands = new String[] {"soffice","-headless","\"-accept=socket,host=localhost,port=8100;urp;\""};
Process process = Runtime.getRuntime().exec(commands)
int code = process.waitFor();
if(code == 0)
    System.out.println("Commands executed successfully");

When I run this program I get "Commands executed successfully".
However the process is not running when the program finishes.
Is it possible that the JVM kills the program after it has run?

Why doesn't this work?

LastEditorDisplayName: Shervin

OwnerDisplayName: colin


问:
how can I convert a char to variable?
In detail:
I need this formula to work.
string = str(z)+":1.0 "+str(z+1)+":0.0"      where z is a variable with a value.

will I be able to input this formula into a dictionary value with a specific key. Like

```<code>dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'}
</code>```

so that when i see a key value 'A' I should be able to use that formula in the dictionary

Title: how can I convert a char to variable?

Body:
In detail:
I need this formula to work.
string = str(z)+":1.0 "+str(z+1)+":0.0"      where z is a variable with a value.

will I be able to input this formula into a dictionary value with a specific key. Like

dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'}

so that when i see a key value 'A' I should be able to use that formula in the dictionary

Body:
Use lambda function:

d = { 'A': lambda z: str(z)+":1.0 "+str(z+1)+":0.0" }

d['A'](5)

# returns: '5:1.0 6:0.0'


问:
Extracting particular text associated value from an image
I have an image, and from the image I want to extract key and value pair details.

As an example, I want to extract the value of "MASTER-AIRWAYBILL NO:"

I have written to extract the entire text from the image using python opencv and OCR, but I don't have any clue how to extract only the value for "MASTER-AIRWAYBILL NO:" from the entire result text of the image.

Please find the code:

```<code>import cv2
import numpy as np
import pytesseract
from PIL import Image
print ("Hello")
src_path = "C:\\Users\Venkatraman.R\Desktop\\alpha_bill.jpg"
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"

print (src_path)

# Read image with opencv
img = cv2.imread(src_path)

# Convert to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)

# Write image after removed noise
cv2.imwrite(src_path + "removed_noise.png", img)

#  Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

# Write the image after apply opencv to do some ...
cv2.imwrite(src_path + "thres.png", img)

# Recognize text with tesseract for python
result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

# Remove template file
#os.remove(temp)

print ('--- Start recognize text from image ---')
print (result)
</code>```

So output should be like:

MASTER-AIRWAYBILL NO: 157-46637194

答:
I m using python 2.7 and i m also want to finde vendor name from the image
how should i find?

m = re.findall(r"MASTER-AIRWAYBILL NO: [\d—-]+", t)
for the above line its showing error

and if i use m=re.findall(r'Vendor Name:[\d--]+', t) then also its showing error

Body:
I have an image, and from the image I want to extract key and value pair details.

As an example, I want to extract the value of "MASTER-AIRWAYBILL NO:"

I have written to extract the entire text from the image using python opencv and OCR, but I don't have any clue how to extract only the value for "MASTER-AIRWAYBILL NO:" from the entire result text of the image.

Please find the code:

import cv2
import numpy as np
import pytesseract
from PIL import Image
print ("Hello")
src_path = "C:\\Users\Venkatraman.R\Desktop\\alpha_bill.jpg"
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"

print (src_path)

# Read image with opencv
img = cv2.imread(src_path)

# Convert to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)

# Write image after removed noise
cv2.imwrite(src_path + "removed_noise.png", img)

#  Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)

# Write the image after apply opencv to do some ...
cv2.imwrite(src_path + "thres.png", img)

# Recognize text with tesseract for python
result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

# Remove template file
#os.remove(temp)

print ('--- Start recognize text from image ---')
print (result)

So output should be like:

MASTER-AIRWAYBILL NO: 157-46637194