问:
How can I check if a string contains a specifig character with any digit in front of it in Python 2.7
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

```<code>lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))
</code>```

Result of code:

答:
How about using regexp?

```<code>import re

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100"]

pattern = re.compile(r"\d+\s*g")

for line in lines:
    search = pattern.search(line)
    if search:
        print search.group()
</code>```

returns:

```<code>100g
100 g
100 g
15 g
85 g
</code>```

Body:
I've got a question about my code(below). I'm trying to make a function to check if a string contains a gram unit. The code loops checks each string for a g with a digit in front of it. If it find this, it will loop backwards through the indices of the string until the index is not a digit. The code is working for me but I'm wondering how I can improve this code and if there is a better way to do this.

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]

for lineIndex, line in enumerate(lines): # loop through lines
    line = line.lower() # make line lowercase
    line = "".join(line.split()) # delete whitespaces

    check = False

    for charIndex, char in enumerate(line): # loop through every index from string
        if char == "g" and line[charIndex-1].isdigit() == True: #check for a g with in front a digit
            index = charIndex - 1
            myList = []

            #loop until the index in front is not a digit
            while True:
                if line[index].isdigit() == True:
                    myList.append(line[index])
                    index -= 1
                else:
                    break

            # make a string from the list and print it
            myList.reverse()
            result = ""
            for letter in myList:
                result += letter
            result += "g"
            print("Line: %s\nBecomes: %s" % (line, result))

            # make check False
            check = True

    if check is False:
        print("Line: %s\nDoes not contain grams" % (line))

Result of code:

Body:
How about using regexp?

import re

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100"]

pattern = re.compile(r"\d+\s*g")

for line in lines:
    search = pattern.search(line)
    if search:
        print search.group()

returns:

100g
100 g
100 g
15 g
85 g


来源: stackexchange

问:
Laravel 5.4: Change DB according to sub domain in laravel
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

```<code>Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});
</code>```

in app/Providers\RouteServiceProvieder.php

```<code> public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }
</code>```

Then i have created a ServiceProvider ConfigServiceProvider

```<code><?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}
</code>```

But the code is not working?

The Error i am getting is

```<code>FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected
</code>```

I am using Laravel 5.4. Can any one guide me how to do it correctly?

答:
What I would suggest is to create 2 .env files, one for each subdomain e.g. .env.domain1 and .env.domain2

Then in your app service provider:

```<code>public function boot() {      //Use boot for this
    $fn = ".env.".$this->app->request->route('domain');
    $dotenv = new \Dotenv\Dotenv(self::basePath(), $fn);
    try {
        $dotenv->overload();
    } catch (\Dotenv\Exception\InvalidPathException $e) {
       //Nothing to overload with
    }
}
</code>```

This makes your sub-domains behave like different environments which does look like what you're trying to do.

ContentLicense: CC BY-SA 3.0

Body:
I am creating a SAAS application with a single laravel installation and multi tenant database.
So i have a main DB that is connected to laravel by default. the client can access the application through their sub-domain like: client1.example.com and client2.example.com

I am saving all info fo the client like domain and db name in the main db.

How can change the DB according to the subdomain

I tried with the following Code

in routes/web.php

Route::group(['domain' => '{account}'], function() {
    Route::get('/', function($account) {
        // This will return {account}, which you can pass along to what you'd like
        return $account;
    });

});

in app/Providers\RouteServiceProvieder.php

 public function boot(Router $router)
    {
        parent::boot($router);

        $router->bind('domain', function ($value) {
            //$hst=$request->getHost();
            $domain= Customer::where('sub_domain',$value)->first();
            if ($domain) {
                return $domain;
            }
            throw new Exception('error message');
        });

    }

Then i have created a ServiceProvider ConfigServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class ConfigServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register(Request $request)
    {
        $customer=$request->route('domain');
        //$customer = Request::route('domain');  // there are multiple ways of doing this
        //$customer = $request->route()->domain;
        config([
            'database.mysql.database' => $customer->customer_database,  //this is because I have same username and password for all the databases. If you have different username and passwords set them too.
        ]);
        DB::reconnect(); // this will help in reconnecting the database if the connection is already established. and import the DB facade.
    }
}

But the code is not working?

The Error i am getting is

FatalThrowableError in ConfigServiceProvider.php line 25:
Type error: Too few arguments to function App\Providers\ConfigServiceProvider::register(), 0 passed in C:\xampp\htdocs\main\vendor\laravel\framework\src\Illuminate\Foundation\Application.php on line 568 and exactly 1 expected

I am using Laravel 5.4. Can any one guide me how to do it correctly?

Body:
What I would suggest is to create 2 .env files, one for each subdomain e.g. .env.domain1 and .env.domain2

Then in your app service provider:

public function boot() {      //Use boot for this
    $fn = ".env.".$this->app->request->route('domain');
    $dotenv = new \Dotenv\Dotenv(self::basePath(), $fn);
    try {
        $dotenv->overload();
    } catch (\Dotenv\Exception\InvalidPathException $e) {
       //Nothing to overload with
    }
}

This makes your sub-domains behave like different environments which does look like what you're trying to do.


问:
Unbind previous events jquery
I'ts possible to unbind  the previos events of a button ,something like that</p>

```<code>$("#my-button").on('click',function(){
        $( "#my-button" ).unbind();
        alert('whatever');
      });
</code>```

答:
Try this:

```<code>$("#my-button").off('click').on('click',function() {
  alert('whatever');
});
</code>```

Documentation for jQuery off

The .off() method removes event handlers that were attached with .on()

Title: Unbind previous events jquery

Body:
I'ts possible to unbind  the previos events of a button ,something like that

$("#my-button").on('click',function(){
        $( "#my-button" ).unbind();
        alert('whatever');
      });

Body:
Try this:

$("#my-button").off('click').on('click',function() {
  alert('whatever');
});

Documentation for jQuery off

The .off() method removes event handlers that were attached with .on()


问:
Use Azure Data Factory (without MapReduce) to import and unzip archives to a Blob Storage
I have to import various zip files from an ftp server to some Azure SQL tables. Every zip file contains up to 10 text (csv) files with different structure, i.e the rows in the first text file are of the form

"1|Monday|2017-03-20|345671"

while the rows in the second text file are of the form, say,

"abc|345894|xyz||2|yyy|true|3".

I didn't want to use MapReduce (or custom activities), as it is expensive and slow (Microsoft Azure Support suggested to use HDInsight (on demand) MapReduce activity to unzip the files first).

答:
Define the necessary Linked service, for me an FTP Linked Service, and then use a Dataset of type FileShare to get the files from the source (FTP Server). In this Dataset, assert that the files are compressed:

```<code>{
    "name": "myFTPFileInput",
    "properties": {
    "published": false,
    "type": "FileShare",
    "linkedServiceName": "myFTPLinkedService",
    "typeProperties": {
        "fileName": "xyz20170316.zip",
        "useBinaryTransfer": "true",
        "folderPath": "/Products/xyzProducts",
        "compression": {
            "type": "ZipDeflate",
            "level": "Optimal"
        }
    },
    "availability": {
        "frequency": "Day",
        "interval": 15
    },
    "external": true,
    "policy": {}
    }
}
</code>```

Use a Blobsink to write the files in to blob storage:

```<code>{
    "name": "myAzureBlobOutput",
    "properties": {
    "published": false,
    "type": "AzureBlob",
    "linkedServiceName": "myAzureStorageLinkedService",
    "typeProperties": {
        "folderPath": "mytest/ftp/xyz/{Year}/{Month}",
        "format": {
            "type": "TextFormat",
            "rowDelimiter": "\n",
            "columnDelimiter": "|"
        },
        "partitionedBy": [
            {
                "name": "Year",
                "value": {
                    "type": "DateTime",
                    "date": "SliceStart",
                    "format": "yyyy"
                }
            },
            {
                "name": "Month",
                "value": {
                    "type": "DateTime",
                    "date": "SliceStart",
                    "format": "MM"
                }
            }
        ]
    },
    "availability": {
        "frequency": "Day",
        "interval": 15
    }
  }
}
</code>```

The Data will be decompressed and written to the specified folder as text. From there I can use a standard ADF Copy Activity to import each file to the corresponding Azure SQL table.

Hope this helps

Body:
Define the necessary Linked service, for me an FTP Linked Service, and then use a Dataset of type FileShare to get the files from the source (FTP Server). In this Dataset, assert that the files are compressed:

{
    "name": "myFTPFileInput",
    "properties": {
    "published": false,
    "type": "FileShare",
    "linkedServiceName": "myFTPLinkedService",
    "typeProperties": {
        "fileName": "xyz20170316.zip",
        "useBinaryTransfer": "true",
        "folderPath": "/Products/xyzProducts",
        "compression": {
            "type": "ZipDeflate",
            "level": "Optimal"
        }
    },
    "availability": {
        "frequency": "Day",
        "interval": 15
    },
    "external": true,
    "policy": {}
    }
}

Use a Blobsink to write the files in to blob storage:

{
    "name": "myAzureBlobOutput",
    "properties": {
    "published": false,
    "type": "AzureBlob",
    "linkedServiceName": "myAzureStorageLinkedService",
    "typeProperties": {
        "folderPath": "mytest/ftp/xyz/{Year}/{Month}",
        "format": {
            "type": "TextFormat",
            "rowDelimiter": "\n",
            "columnDelimiter": "|"
        },
        "partitionedBy": [
            {
                "name": "Year",
                "value": {
                    "type": "DateTime",
                    "date": "SliceStart",
                    "format": "yyyy"
                }
            },
            {
                "name": "Month",
                "value": {
                    "type": "DateTime",
                    "date": "SliceStart",
                    "format": "MM"
                }
            }
        ]
    },
    "availability": {
        "frequency": "Day",
        "interval": 15
    }
  }
}

The Data will be decompressed and written to the specified folder as text. From there I can use a standard ADF Copy Activity to import each file to the corresponding Azure SQL table.

Hope this helps


问:
GCM not working for release apk
Before any one marks this as a duplicate, I have been through every related documents and questions in Stack Overflow but I could not get my exact solution for my problem.

GCM for release apk works with other devices but does not work in Sony Xperia Z5 with Android version 7. Every other devices works fine.

I have tried with OnePlus 3 with Android version 7 and it works. The problem exists only with Sony Xperia Z5 (Nougat).

In my caseIi have checked all GCM key and tried with SHA1 fingerprint as recommended by few answers in Stack Overflow.

I have tried adding few lines in ProGaurd file as recommended in GCM registration works for debug APK but not release APK.

But nothing is working for me.

答: Since it's device specific, maybe the app manager in your Sony Xperia blocks the notification of your app. There was no issue with GCM because as you've said, the problem exists only with Sony Xperia and works fine with other devices. Here's a thread which might help. If Setting > Personalization > Notification center doesn't work, try to repair the firmware using PCC.

Title: GCM not working for release apk


问:
mysql explain taking time
I am doing an explain plan on following select query and the explain plan never returns. The explain plan was returning in 2-3 minutes before but now it's taking for ever and never returns. Following is the explain query i am running </p>

```<code>explain SELECT * FROM
((
SELECT DISTINCT hi.target_profile_id, hi.handset_id
FROM handset_inclusions hi,
campaigns c,
campaigns_target_profiles ctp
WHERE hi.target_profile_id = ctp.target_profile_id
AND c.id=ctp.campaign_id
AND c.active=1
AND c.house_ad = true
ORDER BY target_profile_id, handset_id)
UNION DISTINCT
(
SELECT DISTINCT hi.target_profile_id, hi.handset_id
FROM handset_inclusions hi,
campaigns c,
campaign_flights f,
campaigns_target_profiles ctp
WHERE hi.target_profile_id = ctp.target_profile_id
AND c.id=ctp.campaign_id
AND c.active=1
AND c.house_ad = false
AND c.id = f.campaign_id
AND (f.active_flight = true or c.id in (199,857,947)
       OR (NOW() >= DATE_SUB(f.start_time, INTERVAL 6 HOUR)
           AND NOW() <= DATE_ADD(f.end_time, INTERVAL 6 HOUR)))
ORDER BY target_profile_id, handset_id)
UNION DISTINCT
(SELECT prof.target_profile_id, h.id as handset_id
FROM  (SELECT distinct (pc.target_profile_id) as target_profile_id
       FROM placements p, sites s, publishers pubs, placement_3PNchannel pc
       LEFT OUTER JOIN 3PNchannel c
       ON c.id = pc.3PNchannel_id
       WHERE p.id = pc.placement_id
         AND p.siteid = s.id
         AND pubs.id = s.publisherid
         AND pc.active = TRUE
         AND pubs.allows_3pn)prof, handsets h, handset_inclusions i
WHERE prof.target_profile_id = i.target_profile_id
  AND i.handset_id = h.id)) t
  order by t.target_profile_id;
</code>```

答:
It was a bug. MySQL seems to have executed subqueries when running EXPLAIN.

It seems like it should be fixed in MySQL >= 5.6

Title: mysql explain taking time

Body:
I am doing an explain plan on following select query and the explain plan never returns. The explain plan was returning in 2-3 minutes before but now it's taking for ever and never returns. Following is the explain query i am running

explain SELECT * FROM
((
SELECT DISTINCT hi.target_profile_id, hi.handset_id
FROM handset_inclusions hi,
campaigns c,
campaigns_target_profiles ctp
WHERE hi.target_profile_id = ctp.target_profile_id
AND c.id=ctp.campaign_id
AND c.active=1
AND c.house_ad = true
ORDER BY target_profile_id, handset_id)
UNION DISTINCT
(
SELECT DISTINCT hi.target_profile_id, hi.handset_id
FROM handset_inclusions hi,
campaigns c,
campaign_flights f,
campaigns_target_profiles ctp
WHERE hi.target_profile_id = ctp.target_profile_id
AND c.id=ctp.campaign_id
AND c.active=1
AND c.house_ad = false
AND c.id = f.campaign_id
AND (f.active_flight = true or c.id in (199,857,947)
       OR (NOW() >= DATE_SUB(f.start_time, INTERVAL 6 HOUR)
           AND NOW() <= DATE_ADD(f.end_time, INTERVAL 6 HOUR)))
ORDER BY target_profile_id, handset_id)
UNION DISTINCT
(SELECT prof.target_profile_id, h.id as handset_id
FROM  (SELECT distinct (pc.target_profile_id) as target_profile_id
       FROM placements p, sites s, publishers pubs, placement_3PNchannel pc
       LEFT OUTER JOIN 3PNchannel c
       ON c.id = pc.3PNchannel_id
       WHERE p.id = pc.placement_id
         AND p.siteid = s.id
         AND pubs.id = s.publisherid
         AND pc.active = TRUE
         AND pubs.allows_3pn)prof, handsets h, handset_inclusions i
WHERE prof.target_profile_id = i.target_profile_id
  AND i.handset_id = h.id)) t
  order by t.target_profile_id;


问:
Sql tuning advisor(accepting profile)
I have created sql tuning task for some query and executed it.After generating report,It recommends me to run the following command:

```<code>execute dbms_sqltune.accept_sql_profile(task_name => 'tuning_task_name',
                                        replace => TRUE);
</code>```

But! Of course I want to know what does this profile do?! and after searching this question on the internet I found the following query:

```<code>select
    rat.attr1
from
  sys.WRI$_ADV_TASKS    tsk,
  sys.WRI$_ADV_RATIONALE  rat
where
  tsk.name = 'tuning_task_name'
and  rat.task_id   = tsk.id
</code>```

And the result of this query is the following:

I don't understand what does it do :( And also I want to convert this profile hints into the more readable (/+ hint/) sql hints?

答: Based on page 24 of this PDF it looks like these hints are mostly telling the optimizer to adjust the cardinality estimates for different objects.  WHY the profiler is doing this I'm not sure; maybe the statistics are bad or maybe it's making fake statistics to force a better plan?  But perhaps a better way to understand the profile is to compare the explain plan before and after.</p>

ContentLicense: CC BY-SA 2.5

Title: Sql tuning advisor(accepting profile)

Body:
I have created sql tuning task for some query and executed it.After generating report,It recommends me to run the following command:

execute dbms_sqltune.accept_sql_profile(task_name => 'tuning_task_name',
                                        replace => TRUE);

But! Of course I want to know what does this profile do?! and after searching this question on the internet I found the following query:

select
    rat.attr1
from
  sys.WRI$_ADV_TASKS    tsk,
  sys.WRI$_ADV_RATIONALE  rat
where
  tsk.name = 'tuning_task_name'
and  rat.task_id   = tsk.id

And the result of this query is the following:

I don't understand what does it do :( And also I want to convert this profile hints into the more readable (/+ hint/) sql hints?


问:
Writing a request for the number of hired/fired each year
I'm trying to write an SQL request to count the number of Employees hired/fired each year.

I can have each Employee's dates with this select:

```<code>SELECT HiredDate, FiredDate FROM Employees;
</code>```

I can list each year with this select:

```<code>SELECT to_char(e1.HiredDate, 'YYYY') Year FROM Employees e1
UNION
SELECT to_char(e2.FiredDate, 'YYYY') Year FROM Employees e2;
</code>```

But I don't manage to count the number of hired/fired each year.

EDIT

Employees sample data:

```<code>Name   | HiredDate  | FiredDate
--------------------------------
John   | 01/02/2003 | 03/04/2013
Jack   | 05/06/2006 | 07/08/2013
Jean   | 03/04/2006 | null
James  | 01/02/2013 | null
</code>```

Expected results:

```<code>Year | HiredNumber | FiredNumber
---------------------------------
2003 |           1 |           0
2006 |           2 |           0
2013 |           1 |           2
</code>```

答:
There may be years with no hiring and years with no firings. So the easiest way to solve this problem is with two sub-queries, one for each count and join them with a full outer join.

```<code>with e1 as (
    select extract(year from hireddate) as emp_year
           , count(hireddate) as hired_count
    from employees
    where hireddate is not null
    group by extract(year from hireddate)
   )
, e2 as (
    select extract(year from fireddate) as emp_year
           , count(fireddate) as fired_count
    from employees
    where fireddate is not null
    group by extract(year from fireddate)
    )
select coalesce (e1.emp_year, e2.emp_year) as emp_year
       , nvl(e1.hired_count, 0) as hired_count
       , nvl(e2.fired_count, 0) as fired_count
from e1
     full outer join e2
     on e1.emp_year = e2.emp_year
order by 1
</code>```

Notes

This will exclude any years with neither hirings nor firings. It's easy enough to generate such things.

Presumably hireddate is mandatory but the not null check is retained for symmetry :)

". It works well in SQL Developer but can't be set as a Visual datasource"

Here is a variant without the FULL OUTER JOIN:

```<code>select emp_year
       , sum(hired_count) as hired_count
       , sum(fired_count) as fired_count
from (
    select extract(year from hireddate) as emp_year
           , count(hireddate) as hired_count
           , 0 as fired_count
    from employees
    where hireddate is not null
    group by extract(year from hireddate)
    union all
    select extract(year from fireddate) as emp_year
           , 0 as hired_count
           , count(fireddate) as fired_count
    from employees
    where fireddate is not null
    group by extract(year from fireddate)
    )
group by emp_year
order by 1
</code>```

Body:
I'm trying to write an SQL request to count the number of Employees hired/fired each year.

I can have each Employee's dates with this select:

SELECT HiredDate, FiredDate FROM Employees;

I can list each year with this select:

SELECT to_char(e1.HiredDate, 'YYYY') Year FROM Employees e1
UNION
SELECT to_char(e2.FiredDate, 'YYYY') Year FROM Employees e2;

But I don't manage to count the number of hired/fired each year.

EDIT

Employees sample data:

Name   | HiredDate  | FiredDate
--------------------------------
John   | 01/02/2003 | 03/04/2013
Jack   | 05/06/2006 | 07/08/2013
Jean   | 03/04/2006 | null
James  | 01/02/2013 | null

Expected results:

Year | HiredNumber | FiredNumber
---------------------------------
2003 |           1 |           0
2006 |           2 |           0
2013 |           1 |           2

Body:
There may be years with no hiring and years with no firings. So the easiest way to solve this problem is with two sub-queries, one for each count and join them with a full outer join.

with e1 as (
    select extract(year from hireddate) as emp_year
           , count(hireddate) as hired_count
    from employees
    where hireddate is not null
    group by extract(year from hireddate)
   )
, e2 as (
    select extract(year from fireddate) as emp_year
           , count(fireddate) as fired_count
    from employees
    where fireddate is not null
    group by extract(year from fireddate)
    )
select coalesce (e1.emp_year, e2.emp_year) as emp_year
       , nvl(e1.hired_count, 0) as hired_count
       , nvl(e2.fired_count, 0) as fired_count
from e1
     full outer join e2
     on e1.emp_year = e2.emp_year
order by 1

Notes

This will exclude any years with neither hirings nor firings. It's easy enough to generate such things.

Presumably hireddate is mandatory but the not null check is retained for symmetry :)

". It works well in SQL Developer but can't be set as a Visual datasource"

Here is a variant without the FULL OUTER JOIN:

select emp_year
       , sum(hired_count) as hired_count
       , sum(fired_count) as fired_count
from (
    select extract(year from hireddate) as emp_year
           , count(hireddate) as hired_count
           , 0 as fired_count
    from employees
    where hireddate is not null
    group by extract(year from hireddate)
    union all
    select extract(year from fireddate) as emp_year
           , 0 as hired_count
           , count(fireddate) as fired_count
    from employees
    where fireddate is not null
    group by extract(year from fireddate)
    )
group by emp_year
order by 1


答:
You can unbind click using .unbind() or .off()</p>

```<code>$( "#my-button" ).unbind( "click" );
</code>```

Title: Unbind previous events jquery

Body:
You can unbind click using .unbind() or .off()

$( "#my-button" ).unbind( "click" );


问:
How to perform some action when device is connected to WiFi and app is terminated?
How should I communicate with server or do some action when my device is connected to the WiFi and my app is terminated (not runnning on background/foreground)?</p>

答: If your app goes in Terminated state, you can't perform any operation. The thing you could've done is in the Background state. You should go through this Apple Documentation for better understanding on iOS App Lifecycle.


问:
WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"
I'm having a problem using a WCF call from a Windows service to my WCF service running on my web server.  This call has been working for a number of weeks, but then stopped working all of a sudden, and has not worked since.

The exception I'm getting is:

General Error Occurred System.ServiceModel.CommunicationException: An error occurred while making the HTTP request

and then it says

This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

The security I'm using on both ends is wsHttpBinding, without any kind of encryption.  It also is just using HTTP - not HTTPS, so I'm not sure why it's complaining about HTTPS.

The rest of the inner exception stack is:

SystemNet.WebException: The underlying connection was closed: An unexpected error occurred on a send.
  ---> System.IO.IOException: Unable to write data to the transport connection: An invalid argument was supplied.
  ---> System.Net.Sockets.SocketException: An invalid argument was supplied at System.Net.Sockets.Socket.MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.MultipleWrite(BufferOffsetSize[] buffers)

I should also note that the point in my program where this occurs is on the "Execute" line of the call to the web service - that is, right as soon as I call the web service and pass it the wrapped up DataContract object, it blows up.

All this service is doing is getting passed a large amount of XML (passed as a .NET object to the call on the client side), which it then does some work with.  Probably about 100-200k of XML is being transmitted.  I've raised the limits for the data sizes on both ends to over 6 megs, but that didn't seem to help.

Any ideas?

Some more information on this issue:

When we duplicate the client environment locally, we find that we cannot upload large amounts of XML unless we make the following changes:
1. On the server, set the "maxRequestLength" to 100 MB (way higher than we are sending)
2. On the client, we set the value of maxItemsInObjectGraph under the dataContractSerializer tag to "2147483646".

With these changes, our local installation uploads successfully.  However, the client's install on their server still fails.  What interesting to note is that once we made the maxRequestLength value change on the server, our test installation started throwing an error specifically relating to the maxItemsInObjectGraph setting.  Whereas on our client's server, still the original "HTTP.sys" error is happening.

As I noted before, we are not using SSL at all, and there are 2 other web services calls that execute and upload XML in the same way.  However, since the non-working service call transmits more data, this appears to be a size issue.

However, if the issue the client is having were the same one our test install had, I don't get why the client error message wouldn't be related to the ObjectGraph error.

Is it possible that we're just getting the generic "invalid parameter" "HTTP.sys" error for every possible error on the client (ie. it's really getting the objectGraph error too, but just isn't showing it?)

答:
Just recently experienced this:

System.ServiceModel.CommunicationException:

An error occurred while making the HTTP request to http://example.com/WebServices/SomeService.svc. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.

---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.

Our license of the bluecoat proxy was expired! so it was not possible to to reach the external party (internet).


问:
Create structures in loop without naming them
Let's say I want to create structures in a loop. I don't want to change the values of the structure variables in each loop, I want to create new ones. However, from what I've learnt until know I have to name every new structure I make. Is there a way to do it without naming the structures?

And more specifically, can I have a pointer in each structure that will point to the next one?

What I wanna make is a BST and my struct is for every new node I add to the tree.That's how I've seen people do it, with struct. How can I add nodes if I don't name them? I definitely have some blanks there.

答: If I understood your question, answer is no, you can't declare a structure without a name. And regarding pointer to the next structure member, you should read more about lists and double linked lists in C here http://www.learn-c.org/en/Linked_lists</p>


答:
You could greatly reduce that with a regular expression, searching for at least one digit, followed by possible whitespace, followed by the letter "g":

```<code>import re

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]
for line in lines:
    result = re.findall(r'\d+\s*g', line)
    if result:
        print(*result)
    else:
        print('Not found.')
</code>```

The result:

```<code>100g
100 g
100 g
15 g
Not found.
85 g
Not found.
</code>```

Title: How can I check if a string contains a specifig character with any digit in front of it in Python 2.7

Body:
You could greatly reduce that with a regular expression, searching for at least one digit, followed by possible whitespace, followed by the letter "g":

import re

lines = ["100gr", "pack of 100 gram", "100 g", "great pack of 15 gram", "1 pack of 8", "3 oz = 85 g", "100",]
for line in lines:
    result = re.findall(r'\d+\s*g', line)
    if result:
        print(*result)
    else:
        print('Not found.')

The result:

100g
100 g
100 g
15 g
Not found.
85 g
Not found.


问:
Taskscheduler not working properly on windows server
I was trying to setup a cron to run a php script on my windows server. The script is working fine when accessed manually but it doesn't work via the task schedule.

Here is the problem:

```<code>// Code to fetch stuff from db
mysqlqueries...
for loop{
// Mail according to fetch content
mail function
}
// Mail a status report at the end to me.
</code>```

I am getting the status report but nothing else, my server is on godaddy and when i chatted with support they said there is "a special syntax for running crons" in php? This is the first time i have heard about such a thing. Can anyone help?

答: I was able to fix the issue, nothing needed to be changed in the code. I just had to change from php.exe to php-cgi.exe in the cron call.</p>

Body:
I was trying to setup a cron to run a php script on my windows server. The script is working fine when accessed manually but it doesn't work via the task schedule.

Here is the problem:

// Code to fetch stuff from db
mysqlqueries...
for loop{
// Mail according to fetch content
mail function
}
// Mail a status report at the end to me.

I am getting the status report but nothing else, my server is on godaddy and when i chatted with support they said there is "a special syntax for running crons" in php? This is the first time i have heard about such a thing. Can anyone help?


问:
how to add a server provider name on visual studio 2013 Mvc4 c#
what should i do !!?
i didn't download SQl server , i just setup the default one on visual studio 2013
as you see in the web config i tried everything
the problem is it the default provider name is working but when i try my new provider name it never works and get me error

```<code>  providerName="System.Data.SqlClient" />
       </connectionStrings>
</code>```

that's the default connection string !!
any idea's??

my web.config
the error

答:
The problem is that you've defined the connectionStrings section twice (as you can see in the Detailed Error Information:

Config section 'connectionStrings' already defined.

Delete the first one.

UPDATE:

Check the following: Entity Framework Code First Migrations failing on Wrong Provider (3.5 instead of 4.0)

And don't forget to add the required references: System.Data.Linq and System.Data.SqlServerCe.dll version 4.0.0.0.

Body:
what should i do !!?
i didn't download SQl server , i just setup the default one on visual studio 2013
as you see in the web config i tried everything
the problem is it the default provider name is working but when i try my new provider name it never works and get me error

  providerName="System.Data.SqlClient" />
       </connectionStrings>

that's the default connection string !!
any idea's??

my web.config
the error


问:
Coredump GDB "Backtrace stopped: frame did not save the PC"
While trying to analyse the backtrace of a coredump (process dumped by a SIGABRT from assert) in GDB I get the following output:

```<code>(gdb) bt
#0  0x76d6bc54 in raise () from ./lib/libc.so.1
#1  0x76d63bb8 in abort () from ./lib/libc.so.1
Backtrace stopped: frame did not save the PC
(gdb) thread apply all bt
</code>```

The binary is compiled with "-g" so are all linked libraries except the ones from the toolchain (e.g. libc which doesn't even have symbols) of which I can't determine how it was built.

Is this stack corruption or is it consequence of libc being compiled with something like "fomit-frame-pointer".

As a general question if an uncaught exception happens from a runtime linked library and that library wasn't built for debug what happens i.e. can the coredump still contain useful information?

Thanks

答:
One way to improve a backtrace which includes functions from shared objects without debug symbols is to install debug symbols where gdb can see them. The details of how to do that depend on your environment. One example is that if libc.so.6 is provided by the libc6 package on a Debian system, installing the libc6-dbg package places a number of symbol tables underneath /usr/lib/debug/.build-id (the libc6 package, in addition to libc.so.6, provides a number of other stripped shared objects). If you're using a debugger environment for a non-native core (as suggested by the leading . in ./lib/libc.so.1) you might extract such a package rather than installing it (on a Debian system dpkg -x is one way to do that).

Aside from the issue of debug symbols, in some cases you can improve a backtrace by insuring that the shared objects (stripped or otherwise) seen by gdb correctly correspond to the shared objects which were in use by the process which dumped the core. One way to check that is to compare build IDs, which are (on a typical Linux system) reported by the file command. This only helps if you can reliably determine which shared objects were in use at the time of the core dump, and it presumes your shared objects were built in such a way that they include build IDs.

In some situations the build IDs of the executable and all of the relevant shared objects can be reliably extracted from the core file itself. On a Linux system, this requires the presence of a file note in the core, and the presence of the first page of the executable and each shared object. Recent Linux kernels configured with typical defaults include all of those.

https://github.com/wackrat/structer provides python code which extracts build IDs from a core file which satisfies its assumptions. Depending on how big the core file is it might be preferable to use a 64 bit system, even if the core itself came from a 32 bit system.

If it turns out that gdb is using the correct shared objects for this core (or if there is no viable way to confirm or refute that), another possibility is to disassemble code in the two stack frames reported by gdb. If the shared objects gdb sees are not the right ones for this core, that disassembly is likely to be mysterious, because gdb relies on the contents of the shared objects it uses to line up with the contents of that location at the time the core file was dumped (readonly segments are typically excluded from the core file, with the exception of that first page which provides each build ID). In my experience gdb can typically provide a coherent backtrace without debug symbols even without a frame pointer, but if the wrong shared object is used, gdb might be basing its backtrace on instructions which do not correspond to the correct contents of that location.

Body:
While trying to analyse the backtrace of a coredump (process dumped by a SIGABRT from assert) in GDB I get the following output:

(gdb) bt
#0  0x76d6bc54 in raise () from ./lib/libc.so.1
#1  0x76d63bb8 in abort () from ./lib/libc.so.1
Backtrace stopped: frame did not save the PC
(gdb) thread apply all bt

The binary is compiled with "-g" so are all linked libraries except the ones from the toolchain (e.g. libc which doesn't even have symbols) of which I can't determine how it was built.

Is this stack corruption or is it consequence of libc being compiled with something like "fomit-frame-pointer".

As a general question if an uncaught exception happens from a runtime linked library and that library wasn't built for debug what happens i.e. can the coredump still contain useful information?

Thanks


问:
How to separate letters and digits from a string in php
I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits:  ex:If my string is "12jan" i hav to get "12" "jan" separately..</p>

答:
```<code>$numbers = preg_replace('/[^0-9]/', '', $str);
$letters = preg_replace('/[^a-zA-Z]/', '', $str);
</code>```


答:
```<code>$( "#my-button" ).unbind("click");
</code>```

click can be any event we want to unbind.

unbind need to know which event it has to unbind.

Title: Unbind previous events jquery

Body:
$( "#my-button" ).unbind("click");

click can be any event we want to unbind.

unbind need to know which event it has to unbind.


问:
ElasticSearch Stored Procedure
Suppose I have documents with structure:

```<code>{
    name:"some_name",
    salary:INT_VAL,
    date:YYYY.dd.MMTHH:mm:sssZ,
    num_of_months:INT_VAL
 }
</code>```

And now I want to make a query to elastic, that would select top 10 documents that sorted by criteria salary*num_of_months.
How can I do this?
And what if I want to sort by criteria with some logic inside, sth. like

```<code>if (num_of_months < 5)
 then criteria = salary*100 ;
elseif  criteria = salary*200;
endif
sort_by_criteria()
</code>```

答:
Doing a Sort with a script will enable you to perform calculations on the data and return it in the right order:

```<code>GET /myindex/mytype/_search?pretty
{
 "sort" :{
    "_script" : {
       "type" : "number",
        "lang": "expression",
        "script" :  "doc['num_of_months'].value <  5 ? doc['salary']*100 : doc['salary']*200",
        "order":"desc"
            }
        },
  "size": 10
}
</code>```

Note the use of the ternary operator to do the If statement.

Title: ElasticSearch Stored Procedure

Body:
Suppose I have documents with structure:

{
    name:"some_name",
    salary:INT_VAL,
    date:YYYY.dd.MMTHH:mm:sssZ,
    num_of_months:INT_VAL
 }

And now I want to make a query to elastic, that would select top 10 documents that sorted by criteria salary*num_of_months.
How can I do this?
And what if I want to sort by criteria with some logic inside, sth. like

if (num_of_months < 5)
 then criteria = salary*100 ;
elseif  criteria = salary*200;
endif
sort_by_criteria()

Body:
Doing a Sort with a script will enable you to perform calculations on the data and return it in the right order:

GET /myindex/mytype/_search?pretty
{
 "sort" :{
    "_script" : {
       "type" : "number",
        "lang": "expression",
        "script" :  "doc['num_of_months'].value <  5 ? doc['salary']*100 : doc['salary']*200",
        "order":"desc"
            }
        },
  "size": 10
}

Note the use of the ternary operator to do the If statement.


问:
PHP - limit the file size but somehow got Warning: POST Content-Length exceeds the limit
I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.

Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

instead of the error message of "Sorry, your file is too large. Only 3MB allowed"  from the php code.

```<code><html><head></head>
<body>

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

    Upload File:
    <input type="file" name="upload" /><br>
    <input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

<?php
include("config.php");
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(in_array($ext, $allowed)){

            if($filesize > 3000000) {
                $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;

                if ($con->query($query) == TRUE) {
                echo "<br><br> New record created successfully";
                } else {
                echo "Error:<br>" . $con->error;
                }

                }
            else{
                echo "Sorry, your file is too large. Only 3MB allowed";
            }
        }
        else{
            echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
        }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;

if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}

}
$con->close();
}

?>
</code>```

I don't get it. What did I do wrong in this code?

I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.

答:
Its not a problem with your code. The http request isnt going through php because of the post max size setting.

Find this line in your php.ini of the server and change it:

```<code>; http://php.net/post-max-size
post_max_size = [max uploadsize like '32M' or '1G']
</code>```

Body:
I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.

Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

instead of the error message of "Sorry, your file is too large. Only 3MB allowed"  from the php code.

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

    Upload File:
    <input type="file" name="upload" />

    <input type="submit" name="submit" value="Submit"/>
</form>

<?php
include("config.php");
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(in_array($ext, $allowed)){

            if($filesize > 3000000) {
                $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;

                if ($con->query($query) == TRUE) {
                echo "

 New record created successfully";
                } else {
                echo "Error:
" . $con->error;
                }

                }
            else{
                echo "Sorry, your file is too large. Only 3MB allowed";
            }
        }
        else{
            echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
        }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;

if ($con->query($query) == TRUE) {
echo "

 New record created successfully";
} else {
echo "Error:
" . $con->error;
}

}
$con->close();
}

?>

I don't get it. What did I do wrong in this code?

I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.

Body:
Its not a problem with your code. The http request isnt going through php because of the post max size setting.

Find this line in your php.ini of the server and change it:

; http://php.net/post-max-size
post_max_size = [max uploadsize like '32M' or '1G']


问:
How to generate documentation for a Class-based View?
In Django documentation there's a short info on how to document models, views and other files to make it easily available in the Django Admin. But it lacks info on how to do this for class-based views. Say I have simple DetailView:

```<code>class MyDetailView(DetailView):
    model = MyModel
</code>```

I write something like:

```<code>class MyDetailView(DetailView):
   """
       Displays single :model:`myApp.MyModel` with all details.

       :template: `myApp/mymodel_detail.html`
    """
    model = MyModel
</code>```

But this won't show as a doc text with references to models/templates. How should I do that?

答: Turns out it didn't display :template: due to the extra unecessary space after the colon.

Body:
In Django documentation there's a short info on how to document models, views and other files to make it easily available in the Django Admin. But it lacks info on how to do this for class-based views. Say I have simple DetailView:

class MyDetailView(DetailView):
    model = MyModel

I write something like:

class MyDetailView(DetailView):
   """
       Displays single :model:`myApp.MyModel` with all details.

       :template: `myApp/mymodel_detail.html`
    """
    model = MyModel

But this won't show as a doc text with references to models/templates. How should I do that?


问:
MJML - Template Interpolation, Dynamic Data, Context
After a lot of searches,
I am having difficulties in finding how:

MJML handles dynamic data and template interpolations

I was expecting something like:

import { mjml2html } from 'mjml';

const context = {
  message: 'Hello World'
};

const view = mjml2html(template, context);
```

<pre class="lang-html prettyprint-override"><code><mjml>
  <mj-body>
    <mj-container>
      <mj-section>
        <mj-column>
          <mj-text>{message}</mj-text>
        </mj-column>
      </mj-section>
    </mj-container>
  </mj-body>
</mjml>
</code>```

答:
MJML doesn't handle any templating. If you want templates, use a template engine such as handlebars to render to MJML.</p>

```<code>import { compile } from 'handlebars';
import { mjml2html } from 'mjml';

const template = compile(`
<mjml>
  <mj-body>
    <mj-container>
      <mj-section>
        <mj-column>
          <mj-text>{{message}}</mj-text>
        </mj-column>
      </mj-section>
    </mj-container>
  </mj-body>
</mjml>
`);
const context = {
    message: 'Hello World'
};
const mjml = template(context);
const html = mjml2html(mjml);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After a lot of searches,
I am having difficulties in finding how:

MJML handles dynamic data and template interpolations

I was expecting something like:

import { mjml2html } from 'mjml';

const context = {
  message: 'Hello World'
};

const view = mjml2html(template, context);

<mjml>
  <mj-body>
    <mj-container>
      <mj-section>
        <mj-column>
          <mj-text>{message}</mj-text>
        </mj-column>
      </mj-section>
    </mj-container>
  </mj-body>
</mjml>

Body:
MJML doesn't handle any templating. If you want templates, use a template engine such as handlebars to render to MJML.

import { compile } from 'handlebars';
import { mjml2html } from 'mjml';

const template = compile(`
<mjml>
  <mj-body>
    <mj-container>
      <mj-section>
        <mj-column>
          <mj-text>{{message}}</mj-text>
        </mj-column>
      </mj-section>
    </mj-container>
  </mj-body>
</mjml>
`);
const context = {
    message: 'Hello World'
};
const mjml = template(context);
const html = mjml2html(mjml);


问:
Must EOT be at the bebinning in the line?
```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}
</code>```

or

```<code>if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}
</code>```

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...

答:
You can move it to an external file like:

```<code>return <<<"EOF"
  Hello $var
EOF;
</code>```

then get it via include

```<code>if(...) {
  if(...) {
    $var = 'World';
    print include 'file.php';
  }
}
</code>```

result is

Hello World

Body:
if(...) {
    if(...) {
        echo <<<EOT
        xxxxxx
EOT;
    }
}

or

if(...) {
    if(...) {
        echo <<<EOT
        xxxxx
        EOT;
    }
}

I prefer the latter, because it won't break the structure of code.

But it seems that the latter will cause highlight error in most editors.

Are there any standard stipulate that we must write as the former one? If so, why they make such a unsatisfying standard?

And are there any alternatives for writing block strings in php that won't break the code structure as the former one does? It is really unsatisfying...

Body:
You can move it to an external file like:

return <<<"EOF"
  Hello $var
EOF;

then get it via include

if(...) {
  if(...) {
    $var = 'World';
    print include 'file.php';
  }
}

result is

Hello World


问:
Setting query string using Fetch GET request
I'm trying to use the new Fetch API:

I am making a GET request like this:

```<code>var request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET'
});
fetch(request);
</code>```

However, I'm unsure how to add a query string to the GET request. Ideally, I want to be able to make a GET request to a URL like:

```<code>'http://myapi.com/orders?order_id=1'
</code>```

In jQuery I could do this by passing {order_id: 1} as the data parameter of $.ajax(). Is there an equivalent way to do that with the new Fetch API?

答:
Maybe this is better:</p>

```<code>const withQuery = require('with-query');

fetch(withQuery('https://api.github.com/search/repositories', {
  q: 'query',
  sort: 'stars',
  order: 'asc',
}))
.then(res => res.json())
.then((json) => {
  console.info(json);
})
.catch((err) => {
  console.error(err);
});
</code>```

Body:
I'm trying to use the new Fetch API:

I am making a GET request like this:

var request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET'
});
fetch(request);

However, I'm unsure how to add a query string to the GET request. Ideally, I want to be able to make a GET request to a URL like:

'http://myapi.com/orders?order_id=1'

In jQuery I could do this by passing {order_id: 1} as the data parameter of $.ajax(). Is there an equivalent way to do that with the new Fetch API?

Body:
Maybe this is better:

const withQuery = require('with-query');

fetch(withQuery('https://api.github.com/search/repositories', {
  q: 'query',
  sort: 'stars',
  order: 'asc',
}))
.then(res => res.json())
.then((json) => {
  console.info(json);
})
.catch((err) => {
  console.error(err);
});


问:
TIFFPackBitsCompressor - NPE?
I'm using com.sun.media.imageioimpl.plugins.tiff.TIFFPackBitsCompressor to try and encode an array of tiff bytes I have using PackBits. I'm unfamiliar with this class and haven't been finding many examples on how to use it. But, when following the javadoc, I've been getting an NPE every time I try to encode my data. So far as I can see, none of my values are null. I've tried these tests with multiple values at this point, but below is my most recent iteration:

```<code>                TIFFPackBitsCompressor pack = new TIFFPackBitsCompressor();
                //bImageFromConvert is a 16-bit BufferedImage with all desired data.
                short[] bufferHolder = ((DataBufferUShort) bImageFromConvert.getRaster().getDataBuffer()).getData();
                //Since bImageFromConvert is 16-bits, the short array isn't the right length.
                //The below conversion handles tihs issue
                byte[] byteBuffer = convertShortToByte(bufferHolder);
                //I'm not entirely sure what this int[] in the parameters should be.
                //For now, it is a test int[] array containing all 1s
                int[] testint = new int[byteBuffer.length];
                Arrays.fill(testint, 1);
                //0 offset. dimWidth = 1760, dimHeight = 2140. Not sure what that last param is supposed to be in layman's terms.
                //npe thrown at this line.
                int testOut = pack.encode(byteBuffer, 0, dimWidth, dimHeight, testint, 1);
</code>```

Does anyone have any insight as to what's happening? Also, if available, does anyone know a better way to encode my TIFF files using PackBits in a java program?

Let me know if there's anything to make my question clearer.

Thank you!

答:
As said in the comment, you are not supposed to use the TIFFPackBitsCompressor directly, instead it's used internally by the JAI ImageIO TIFF plugin (the TIFFImageWriter) when you specify "PackBits" as compression type in the ImageWriteParam. You may also pass a compressor instance in the param, if you cast it to TIFFImageWriteParam first, but this is more useful for custom compressions not known by the plugin.

Also note that the compressor will only write PackBits compressed pixel data, it will not create a full TIFF file.

The normal way of writing a PackBits compressed TIFF file is:

```<code>BufferedImage image = ...; // Your input image

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next(); // Assuming a TIFF plugin is installed

try (ImageOutputStream out = ImageIO.createImageOutputStream(...)) { // Your output file or stream
    writer.setOutput(out);

    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType("PackBits");

    writer.write(null, new IIOImage(image, null, null), param);
}

writer.dispose();
</code>```

The above code should work fine using both JAI ImageIO and the TwelveMonkeys ImageIO TIFF plugins.

PS: PackBits is a very simple compression algorithm based on run-length encoding of byte data. As 16 bit data may vary wildly between the high and low byte of a single sample, PackBits is generally not a good choice for compression of such data.

As stated in my comments, using completely random values I got the following results:

```<code>Compression      | File size
-----------------|-----------------
None             |  7 533 680 bytes
PackBits         |  7 593 551 bytes
LZW w/predictor  | 10 318 091 bytes
ZLib w/predictor | 10 318 444 bytes
</code>```

This is not very surprising, as completely random data isn't generally compressible (without data loss). For a linear gradient, which may be more similar to "photographic" image data I got completely different results:

```<code>Compression      | File size
-----------------|-----------------
None             |  7 533 680 bytes
PackBits         |  7 588 779 bytes
LZW w/predictor  |    200 716 bytes
ZLib w/predictor |    144 136 bytes
</code>```

As you see, here the LZW and Deflate/Zlib algorithms (with predictor step) performs MUCH better. For "real" data, there's likely more noise, so your results is likely somewhere in between these extremes.

Title: TIFFPackBitsCompressor - NPE?

Body:
I'm using com.sun.media.imageioimpl.plugins.tiff.TIFFPackBitsCompressor to try and encode an array of tiff bytes I have using PackBits. I'm unfamiliar with this class and haven't been finding many examples on how to use it. But, when following the javadoc, I've been getting an NPE every time I try to encode my data. So far as I can see, none of my values are null. I've tried these tests with multiple values at this point, but below is my most recent iteration:

                TIFFPackBitsCompressor pack = new TIFFPackBitsCompressor();
                //bImageFromConvert is a 16-bit BufferedImage with all desired data.
                short[] bufferHolder = ((DataBufferUShort) bImageFromConvert.getRaster().getDataBuffer()).getData();
                //Since bImageFromConvert is 16-bits, the short array isn't the right length.
                //The below conversion handles tihs issue
                byte[] byteBuffer = convertShortToByte(bufferHolder);
                //I'm not entirely sure what this int[] in the parameters should be.
                //For now, it is a test int[] array containing all 1s
                int[] testint = new int[byteBuffer.length];
                Arrays.fill(testint, 1);
                //0 offset. dimWidth = 1760, dimHeight = 2140. Not sure what that last param is supposed to be in layman's terms.
                //npe thrown at this line.
                int testOut = pack.encode(byteBuffer, 0, dimWidth, dimHeight, testint, 1);

Does anyone have any insight as to what's happening? Also, if available, does anyone know a better way to encode my TIFF files using PackBits in a java program?

Let me know if there's anything to make my question clearer.

Thank you!

Body:
As said in the comment, you are not supposed to use the TIFFPackBitsCompressor directly, instead it's used internally by the JAI ImageIO TIFF plugin (the TIFFImageWriter) when you specify "PackBits" as compression type in the ImageWriteParam. You may also pass a compressor instance in the param, if you cast it to TIFFImageWriteParam first, but this is more useful for custom compressions not known by the plugin.

Also note that the compressor will only write PackBits compressed pixel data, it will not create a full TIFF file.

The normal way of writing a PackBits compressed TIFF file is:

BufferedImage image = ...; // Your input image

ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next(); // Assuming a TIFF plugin is installed

try (ImageOutputStream out = ImageIO.createImageOutputStream(...)) { // Your output file or stream
    writer.setOutput(out);

    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType("PackBits");

    writer.write(null, new IIOImage(image, null, null), param);
}

writer.dispose();

The above code should work fine using both JAI ImageIO and the TwelveMonkeys ImageIO TIFF plugins.

PS: PackBits is a very simple compression algorithm based on run-length encoding of byte data. As 16 bit data may vary wildly between the high and low byte of a single sample, PackBits is generally not a good choice for compression of such data.

As stated in my comments, using completely random values I got the following results:

Compression      | File size
-----------------|-----------------
None             |  7 533 680 bytes
PackBits         |  7 593 551 bytes
LZW w/predictor  | 10 318 091 bytes
ZLib w/predictor | 10 318 444 bytes

This is not very surprising, as completely random data isn't generally compressible (without data loss). For a linear gradient, which may be more similar to "photographic" image data I got completely different results:

Compression      | File size
-----------------|-----------------
None             |  7 533 680 bytes
PackBits         |  7 588 779 bytes
LZW w/predictor  |    200 716 bytes
ZLib w/predictor |    144 136 bytes

As you see, here the LZW and Deflate/Zlib algorithms (with predictor step) performs MUCH better. For "real" data, there's likely more noise, so your results is likely somewhere in between these extremes.


问:
C# get cmd output just as shown in real cmd window
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

```<code>private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}
</code>```

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit
</code>```

And here is how output looks like when I open a cmd window and type in the commands:

```<code>Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>
</code>```

How do I get this output in my my C# code???

答:
Can you try this simple solution. I don't know how much it can be successful in your case.</p>

```<code>        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c ping 192.168.x.x"; //or your thing
        p.Start();

        string result = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
</code>```

Body:
I have a BackgroundWorker thread that runs a cmd process and writes multiple commands to it. Some of the commands may take a while to complete so I want to show the user the cmd output of the progress.
My code for running the cmd commands looks like this:

private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    var startInfo = new ProcessStartInfo("cmd.exe")
    {
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    cmd = new Process { StartInfo = startInfo };

    cmd.OutputDataReceived += Cmd_OutputDataReceived;
    cmd.Start();
    cmd.BeginOutputReadLine();

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\uboot");

    string[] commands = CmdCommands.GetUbootFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine($"cd {baseFolder}\\External Resources\\img files\\android");
    commands = CmdCommands.GetKernelFlashCommands();
    foreach (var command in commands)
        cmd.StandardInput.WriteLine(command);

    cmd.StandardInput.WriteLine("exit");
    cmd.WaitForExit();
}

private void Cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        txtCmd.Text += e.Data + Environment.NewLine;
    }));
}

But the cmd output loos nothing the real output as shown in a regular cmd window.
Here is how my output looks like:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\>cd C:\img files\uboot

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>fastboot flash XXX.bin

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel

C:\img files\android>fastboot flash system XXX.img

C:\img files\android>fastboot flash userdata XXX.img

C:\img files\android>fastboot flash cache XXX.img

C:\img files\android>exit

And here is how output looks like when I open a cmd window and type in the commands:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\WINDOWS\system32>cd C:\img files\uboot

C:\img files\uboot>fastboot flash bl2 bl2.bin
target didn't report max-download-size
sending 'bl2' (14 KB)...
OKAY [  0.006s]
writing 'bl2'...
OKAY [  0.042s]
finished. total time: 0.052s

C:\img files\uboot>fastboot flash bootloader u-boot.bin
target didn't report max-download-size
sending 'bootloader' (275 KB)...
OKAY [  0.049s]
writing 'bootloader'...
OKAY [  0.046s]
finished. total time: 0.098s

C:\img files\uboot>cd C:\img files\android

C:\img files\android>fastboot flash kernel zImage-dtb
target didn't report max-download-size
sending 'kernel' (5099 KB)...
OKAY [  0.839s]
writing 'kernel'...
OKAY [  0.145s]
finished. total time: 0.988s

C:\img files\android>fastboot flash system system.img
target didn't report max-download-size
sending 'system' (426874 KB)...
OKAY [ 70.327s]
writing 'system'...
OKAY [ 30.963s]
finished. total time: 101.295s

C:\img files\android>fastboot flash userdata userdata.img
target didn't report max-download-size
sending 'userdata' (35680 KB)...
OKAY [  5.895s]
writing 'userdata'...
OKAY [  2.301s]
finished. total time: 8.200s

C:\img files\android>fastboot flash cache cache.img
target didn't report max-download-size
sending 'cache' (6248 KB)...
OKAY [  1.036s]
writing 'cache'...
OKAY [  0.380s]
finished. total time: 1.422s

C:\img files\android>

How do I get this output in my my C# code???

Body:
Can you try this simple solution. I don't know how much it can be successful in your case.

        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c ping 192.168.x.x"; //or your thing
        p.Start();

        string result = p.StandardOutput.ReadToEnd();
        p.WaitForExit();


问:
Abide Foundation on Valid Form
I have a really strange issue in that I'm using the abide foundation validation plugin and all seems to be ok, I can get a pop a message to appear but the form doesn't actually submit... it just seems to refresh the page.

Can anyone see what I'm doing wrong:

```<code>$(document)
// to prevent form from submitting upon successful validation
.on("submit", function(ev,frm) {
    ev.preventDefault();
    $.blockUI({
        message: $('#message'),
        css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' }
    });
    setTimeout(function () {
        $.unblockUI();
        return true;
    }, 17000); // in milliseconds
});
</code>```

Any help would be great on this, it's stressing me out.

UPDATE

I've got a little further

```<code>$(".form")
  .on('invalid', function () {
    var invalid_fields = $(this).find('[data-invalid]');
    console.log(invalid_fields);
  })
  .on('valid', function () {
      $.blockUI({
          message: $('#message'),
          css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' }
      });
      setTimeout(function () {
          $.unblockUI();
      }, 17000); // in milliseconds
    return false;
    $(".form").submit();
  })
  .on('submit', function(){
    return true;
  });
</code>```

For some reason, though the pop shows for a second and then the form submits... it doesn't seem to wait for my timeout.

ANOTHER UPDATE

I've now managed to get this working, anyone else who's having the same issue you need to submit the raw dom form using the options within BlockUi.

```<code>$(".form")
      .on('invalid', function () {
        var invalid_fields = $(this).find('[data-invalid]');
        console.log(invalid_fields);
      })
      .on('valid', function () {
          var theForm = this;
          $.blockUI({
              message: $('#message'),
              css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' },
              timeout: 17000,
              onUnblock: function() { theForm.submit(); }
          });
        return false;
      })
      .on('submit', function(){
        return false;
      });
</code>```

Title: Abide Foundation on Valid Form

Body:
I have a really strange issue in that I'm using the abide foundation validation plugin and all seems to be ok, I can get a pop a message to appear but the form doesn't actually submit... it just seems to refresh the page.

Can anyone see what I'm doing wrong:

$(document)
// to prevent form from submitting upon successful validation
.on("submit", function(ev,frm) {
    ev.preventDefault();
    $.blockUI({
        message: $('#message'),
        css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' }
    });
    setTimeout(function () {
        $.unblockUI();
        return true;
    }, 17000); // in milliseconds
});

Any help would be great on this, it's stressing me out.

UPDATE

I've got a little further

$(".form")
  .on('invalid', function () {
    var invalid_fields = $(this).find('[data-invalid]');
    console.log(invalid_fields);
  })
  .on('valid', function () {
      $.blockUI({
          message: $('#message'),
          css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' }
      });
      setTimeout(function () {
          $.unblockUI();
      }, 17000); // in milliseconds
    return false;
    $(".form").submit();
  })
  .on('submit', function(){
    return true;
  });

For some reason, though the pop shows for a second and then the form submits... it doesn't seem to wait for my timeout.

ANOTHER UPDATE

I've now managed to get this working, anyone else who's having the same issue you need to submit the raw dom form using the options within BlockUi.

$(".form")
      .on('invalid', function () {
        var invalid_fields = $(this).find('[data-invalid]');
        console.log(invalid_fields);
      })
      .on('valid', function () {
          var theForm = this;
          $.blockUI({
              message: $('#message'),
              css: { top: '20%', width: '80%', height: '50%', left: '10%', border: 'none', background: 'none' },
              timeout: 17000,
              onUnblock: function() { theForm.submit(); }
          });
        return false;
      })
      .on('submit', function(){
        return false;
      });


问:
Sharing variable globally
In my main controller I have a user service that returns the current user.

```<code>// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});
</code>```

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

```<code>// My other awesome controller
console.log(currUser.fullName);
</code>```

答:
You could go for a LocalStorage or $rootScope. , if you are sure about not using Providers/Services

Sample:

```<code>myApp.controller('DemoController1', ['$scope', '$rootScope', function DemoController($scope,$rootScope) {
     $rootScope.currUser.fullName ="test";
}]);
</code>```

Then access it as,

```<code>myApp.controller('DemoController2', ['$scope', '$rootScope', function DemoController($scope,$rootScope) {
   var fullName =  $rootScope.currUser.fullName;
}])
</code>```

Title: Sharing variable globally

Body:
In my main controller I have a user service that returns the current user.

// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

// My other awesome controller
console.log(currUser.fullName);

Body:
You could go for a LocalStorage or $rootScope. , if you are sure about not using Providers/Services

Sample:

myApp.controller('DemoController1', ['$scope', '$rootScope', function DemoController($scope,$rootScope) {
     $rootScope.currUser.fullName ="test";
}]);

Then access it as,

myApp.controller('DemoController2', ['$scope', '$rootScope', function DemoController($scope,$rootScope) {
   var fullName =  $rootScope.currUser.fullName;
}])


问:
Can I automatically increment the file build version when using Visual Studio?
I was just wondering how I could automatically increment the build (and version?) of my files using Visual Studio (2005).

If I look up the properties of say C:\Windows\notepad.exe, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not version 1.0.0.0, which let's face it is a bit dull.

I tried a few things, but it doesn't seem to be out-of-box functionality, or maybe I'm just looking in the wrong place (as usual).

I work with mainly web projects....

I looked at both:

http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx

http://www.codeproject.com/KB/dotnet/build_versioning.aspx

and I couldn't believe it so much effort to do something is standard practice.

EDIT:
It does not work in VS2005 as far I can tell (http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx)

答:
There is a visual studio extension Automatic Versions which supports Visual Studio (2017,2019 & 2022)

Screen Shots

LastEditorDisplayName: Rob


问:
Converting a RequestBody json to an Object - Spring Boot
I am a begineer in java development but has previous experience on programming languages like PHP and Python. So little confused on how to proceed on spring boot with the development.

I am developing a rest API which has the following request

```<code>{
  "key":"value",
  "key1":"value1",
  "platform_settings":[
      {"key":"value"}
  ]
}
</code>```

What I did

I created a RestController which accepts the http request and created a function for the resource

```<code>public Share share(@RequestBody final Share share) {
        LOGGER.debug("This is the request", share);
        return share; //
}
</code>```

Question 1 : If it was any other programming language like PHP or Python, there will be helper function which will accept the json request and convert it to object which I can easily work on.

In python it is as simple as

```<code>import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)
//can work on json_data anyway I want.
</code>```

But in java, I will have to create a POJO class, or have jackson/JPA entity as dependency which will map the request to a Class (Which I should predefine with the requests).

Is there any better way I can do this? For every request I make, I will have to create a Class which the request can be mapped to and I will have to define the class

```<code>Entity

package com.payunow.socialsharemodule.models;

import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity
public class Share {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String key;
    private String key1;
    private Map<String,String> platform_settings;

    public Share(String name, String description,Map<String,String> platform_settings) {
        this.key = key;
        this.key1 = key1;
        this.platform_settings = platform_settings;
    }

    //for JPA
    public Share() {}

    public String getKey() {
        return key;
    }

    public String getKey1() {
        return key1;
    }

    public Map<String,String> getPlatform_settings() {
        return platform_settings;
    }

}
</code>```

For every request I make, I will have to create a class defining all its variables inside. Is this the only way to do this?

答:
You need to have Jackson dependecy for coversion of json to java object. But spring provides it by default, so you don't have to add it explicitly.

You don't need a JPA Entity. This is needed only when you want to store the recieved data into database.

Just to recieve the request you don't have to create a separate pojo class. Look at this code

```<code>@PostMapping("/json")
public JSONObject getGeneric(@RequestBody String stringToParse){
        JSONParser parser = new JSONParser();
        JSONObject json = null;
        try {
            json = (JSONObject) parser.parse(stringToParse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    return json;
}
</code>```

As you can see here it takes a string as a request and converts it into a generic JSONObject. So basically you can pass any json to this endpoint.

Body:
I am a begineer in java development but has previous experience on programming languages like PHP and Python. So little confused on how to proceed on spring boot with the development.

I am developing a rest API which has the following request

{
  "key":"value",
  "key1":"value1",
  "platform_settings":[
      {"key":"value"}
  ]
}

What I did

I created a RestController which accepts the http request and created a function for the resource

public Share share(@RequestBody final Share share) {
        LOGGER.debug("This is the request", share);
        return share; //
}

Question 1 : If it was any other programming language like PHP or Python, there will be helper function which will accept the json request and convert it to object which I can easily work on.

In python it is as simple as

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)
//can work on json_data anyway I want.

But in java, I will have to create a POJO class, or have jackson/JPA entity as dependency which will map the request to a Class (Which I should predefine with the requests).

Is there any better way I can do this? For every request I make, I will have to create a Class which the request can be mapped to and I will have to define the class

Entity

package com.payunow.socialsharemodule.models;

import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity
public class Share {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String key;
    private String key1;
    private Map<String,String> platform_settings;

    public Share(String name, String description,Map<String,String> platform_settings) {
        this.key = key;
        this.key1 = key1;
        this.platform_settings = platform_settings;
    }

    //for JPA
    public Share() {}

    public String getKey() {
        return key;
    }

    public String getKey1() {
        return key1;
    }

    public Map<String,String> getPlatform_settings() {
        return platform_settings;
    }

}

For every request I make, I will have to create a class defining all its variables inside. Is this the only way to do this?

Body:
You need to have Jackson dependecy for coversion of json to java object. But spring provides it by default, so you don't have to add it explicitly.

You don't need a JPA Entity. This is needed only when you want to store the recieved data into database.

Just to recieve the request you don't have to create a separate pojo class. Look at this code

@PostMapping("/json")
public JSONObject getGeneric(@RequestBody String stringToParse){
        JSONParser parser = new JSONParser();
        JSONObject json = null;
        try {
            json = (JSONObject) parser.parse(stringToParse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    return json;
}

As you can see here it takes a string as a request and converts it into a generic JSONObject. So basically you can pass any json to this endpoint.


问:
Calling Servlet in SAPUI5 application shows 404 error
I have  developed SAPUI5 application and trying to use servlets for implementing some server side functionality.
I have taken guidance from this tutorial

I use JQuery ajax call from SAPUI5 controller to Servlet which works fine on my local development environment ( i.e. Eclipse Neon , localhost ).

```<code>//Name of servlet is GetUserServlet , mapping defined in web.xml

 $.get('GetUserServlet', {
                            userName : "Hello World"
                         }, function(responseText) {
                          alert(responseText);
  });
</code>```

This Ajax call successfully calls servlet (200 status) and Hello World is alerted when I run this from Eclipse on my local machine. Basically I capture in servlet parameter userName value and send back to controller js file

```<code>string text = request.getParameter("username");
response.getWriter().write(text );
</code>```

But when this application is deployed to ABAP server , the Ajax call to servlet throws 404 (not found error) as seen in Network console of Chrome developer tools.

Has anybody deployed SAPUI5 application with servlet functionality on ABAP ?

Is it some path issue ?

Please tell cause of error or hint in direction to solve this issue.

答:
The reason why you are getting 404 is because the servlet is not deployed in SAP Server.
You can always connect to any Servlet or REST/Web Service API from a SAP UI5 Application but  you will have below things to take care of to be able to access those services:

The service should be deployed properly on a server, if it is a an
ODATA or Hana Service then it will be easy to access as it will be in
same domain and can be deployed in Gateway or HANA servers.

If the service is deployed on any other server which is in a
different domain then you need to update the response headers of your
servelt/service to allow Cross Origin access otherwise browser will
block it and give Cross Origin not allowed error.

The 3 main response headers that you will need in this case are:

Access-Control-Allow-Origin : This can be either a "*" or comma separated domain names that you want to allow access to.

Access-Control-Allow-Methods : GET,POST etc

Access-Control-Allow-Headers : You can tell which header you want the browser to allow in cross domain service such as Origin, Content-Type, Accept;

Body:
I have  developed SAPUI5 application and trying to use servlets for implementing some server side functionality.
I have taken guidance from this tutorial

I use JQuery ajax call from SAPUI5 controller to Servlet which works fine on my local development environment ( i.e. Eclipse Neon , localhost ).

//Name of servlet is GetUserServlet , mapping defined in web.xml

 $.get('GetUserServlet', {
                            userName : "Hello World"
                         }, function(responseText) {
                          alert(responseText);
  });

This Ajax call successfully calls servlet (200 status) and Hello World is alerted when I run this from Eclipse on my local machine. Basically I capture in servlet parameter userName value and send back to controller js file

string text = request.getParameter("username");
response.getWriter().write(text );

But when this application is deployed to ABAP server , the Ajax call to servlet throws 404 (not found error) as seen in Network console of Chrome developer tools.

Has anybody deployed SAPUI5 application with servlet functionality on ABAP ?

Is it some path issue ?

Please tell cause of error or hint in direction to solve this issue.


问:
React.JS pass role value from top menu page to sub page
I have the logon user's role infromation in the TopMenu.jxs

```<code>  getIsCurrentUserAdmin () {
    return _.some(this.props.currentUser.userRoles, ['roleId', 2]);
  },
  render: function () {
    let isCurrentUserAdmin = this.getIsCurrentUserAdmin();
</code>```

How can I pass the value of isCurrentUserAdmin to my sub page, say UserDetails.jxs. Here userDetails mean that logon user is administrating other users' detailed information.
Please help me. I am a newbie to React.JS

答:
If I understand the question correctly you are looking to pass down data to a component using props.

You can do this like so

```<code>render: function() {
  const isCurrentUserAdmin = this.getIsCurrentUserAdmin();

  return <MyOtherComponent isAdmin={isCurrentUserAdmin} />;
}
</code>```

You will also need to add isAdmin to the PropTypes of MyOtherComponent, however using prop types is beyond the scope of this question. See the docs for a starting place about PropTypes

Body:
I have the logon user's role infromation in the TopMenu.jxs

  getIsCurrentUserAdmin () {
    return _.some(this.props.currentUser.userRoles, ['roleId', 2]);
  },
  render: function () {
    let isCurrentUserAdmin = this.getIsCurrentUserAdmin();

How can I pass the value of isCurrentUserAdmin to my sub page, say UserDetails.jxs. Here userDetails mean that logon user is administrating other users' detailed information.
Please help me. I am a newbie to React.JS

Body:
If I understand the question correctly you are looking to pass down data to a component using props.

You can do this like so

render: function() {
  const isCurrentUserAdmin = this.getIsCurrentUserAdmin();

  return <MyOtherComponent isAdmin={isCurrentUserAdmin} />;
}

You will also need to add isAdmin to the PropTypes of MyOtherComponent, however using prop types is beyond the scope of this question. See the docs for a starting place about PropTypes


问:
parameter reference to pointer C++
I was wondering what is the difference between

```<code>void foo(std::shared_ptr<A> a_){
   //work on a_
}
</code>```

and

```<code>void bar(std::shared_ptr<A>& a_){
   //work on a_
}
</code>```

?

Is the reference here useful to something? Since i'm working with side effect on a_ I believe it wouldn't. But it is possible to write something like this so I'm really wondering.

Thanks!

答:
It works just like in case of any other data type, smart pointers are not different in this sense:

When passing by value, you can work with a copy of the original object.

When passing by reference, you can modify the original object.

See this simple example

```<code>#include <iostream>
#include <memory>

struct A {
    int a_;
    A(int a) : a_(a) {}
};

void foo_val(std::shared_ptr<A> a_){
    a_ = std::make_shared<A>(10);
}
void foo_ref(std::shared_ptr<A>& a_){
    a_ = std::make_shared<A>(10);
}

int main() {
   std::shared_ptr<A> pA = std::make_shared<A>(20);

   foo_val(pA);
   std::cout << pA->a_ << std::endl;
   foo_ref(pA);
   std::cout << pA->a_ << std::endl;

   return 0;
}
</code>```

It outputs 20, 10 showing that foo_val couldn't change original object, while foo_ref could.

demo

Title: parameter reference to pointer C++

Body:
I was wondering what is the difference between

void foo(std::shared_ptr a_){
   //work on a_
}

and

void bar(std::shared_ptr& a_){
   //work on a_
}

?

Is the reference here useful to something? Since i'm working with side effect on a_ I believe it wouldn't. But it is possible to write something like this so I'm really wondering.

Thanks!

Body:
It works just like in case of any other data type, smart pointers are not different in this sense:

When passing by value, you can work with a copy of the original object.

When passing by reference, you can modify the original object.

See this simple example

#include <iostream>
#include <memory>

struct A {
    int a_;
    A(int a) : a_(a) {}
};

void foo_val(std::shared_ptr<A> a_){
    a_ = std::make_shared<A>(10);
}
void foo_ref(std::shared_ptr<A>& a_){
    a_ = std::make_shared<A>(10);
}

int main() {
   std::shared_ptr<A> pA = std::make_shared<A>(20);

   foo_val(pA);
   std::cout << pA->a_ << std::endl;
   foo_ref(pA);
   std::cout << pA->a_ << std::endl;

   return 0;
}

It outputs 20, 10 showing that foo_val couldn't change original object, while foo_ref could.

demo