问:
Best match REGEXP pattern
I need to look for 3 kinds of formats that might occur in a string (A = Letter; # = digit):

```<code>A###A
A####
A#####
</code>```

Example:

```<code>This booking has the ID of A#####.
</code>```

The string can contain only one of the three example patterns. I wrote this REGEXP with OR operators, so I can check and extract the IDs I need:

```<code>([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])|([a-zA-Z]\d{5})
</code>```

The problem is, that it does not return the best match from the REGEXP, but the first match. For example, if the string contains A#####, it will return A####, ignoring the last digit – becaused it already matched a pattern before.

What am I missing?
Thanks in advance!

答:
```<code>\b[a-zA-Z]\d{3}(?:[a-zA-Z]|\d{1,2})\b
</code>```

[a-zA-Z]\d{3} - constant part

([a-zA-Z]|\d{1,2}) -  letter, one or tow digits

demo

Title: Best match REGEXP pattern

Body:
I need to look for 3 kinds of formats that might occur in a string (A = Letter; # = digit):

A###A
A####
A#####

Example:

This booking has the ID of A#####.

The string can contain only one of the three example patterns. I wrote this REGEXP with OR operators, so I can check and extract the IDs I need:

([a-zA-Z]\d{4})|([a-zA-Z]\d{3}[a-zA-Z])|([a-zA-Z]\d{5})

The problem is, that it does not return the best match from the REGEXP, but the first match. For example, if the string contains A#####, it will return A####, ignoring the last digit – becaused it already matched a pattern before.

What am I missing?
Thanks in advance!

Body:
\b[a-zA-Z]\d{3}(?:[a-zA-Z]|\d{1,2})\b

[a-zA-Z]\d{3} - constant part

([a-zA-Z]|\d{1,2}) -  letter, one or tow digits

demo


来源: stackexchange

问:
JqGrid: only last row can be selected after loading data with addRowData
I used the addRowData function to load some data from an array. but when ever I want to select a row, just the last one is, no other one can be selected.
I'm using the same code from my other page which works fine except I'm loading my data routed from my controller.
Below is the code: `

    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style type="text/css">
        .ui-jqgrid-btable .ui-state-highlight {
            background: #003366;
        }

        .ui-jqgrid table.ui-jqgrid-htable th.ui-th-column input,
        .ui-jqgrid table.ui-jqgrid-htable th.ui-th-column select {
            background-color: lightcyan;
        }

        .ui-jqgrid-bdiv {
            max-height: 500px;
        }
    </style>
  </code>```

@model IEnumerable<FEC.Models.VentilationDemandeurs>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">

    <link href="../Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />

```

答: Short answer; Make sure you only have a single column with 'key' attribute equals to true.</p>

ContentLicense: CC BY-SA 3.0

Body:
I used the addRowData function to load some data from an array. but when ever I want to select a row, just the last one is, no other one can be selected.
I'm using the same code from my other page which works fine except I'm loading my data routed from my controller.
Below is the code: `

@model IEnumerable<FEC.Models.VentilationDemandeurs>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">

    <link href="../Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />


问:
Symfony Doctrine query returning not working, returning 1 and 11
```<code>$PDO = Doctrine_Manager::getInstance()->connection()->getDbh();
$PDO->prepare("
      //SQL Query Here
")->execute();
</code>```

<p>I was told that this will work for creating a custom Doctrine query in Symfony. Regardless of what I put inside the prepare statement I get a value of 1 returned. Print_r of the returned variable gives 11. How odd... what is going on? </p>

答:
That's because execute() returns TRUE on success and FALSE on FAILURE: http://pl.php.net/manual/en/pdostatement.execute.php

You should use one of the fetch* methods to actually retrieve data: http://pl.php.net/manual/en/pdostatement.fetchall.php

ContentLicense: CC BY-SA 2.5

Body:
$PDO = Doctrine_Manager::getInstance()->connection()->getDbh();
$PDO->prepare("
      //SQL Query Here
")->execute();

I was told that this will work for creating a custom Doctrine query in Symfony. Regardless of what I put inside the prepare statement I get a value of 1 returned. Print_r of the returned variable gives 11. How odd... what is going on?


问:
Jmeter - Ramp Up Time vs Constant Timer
I am trying to create a scenario where I need to hit an API with 200 unique hits(in my case 200 loan numbers).

I need 10 hits at a time for every 5 seconds

I used below values to generate above scenario

Threads: 200
Ramp UP: 300
Loop: 1

Synchronizing timer::
Number of simulated Users to Group by: 10

Constant Timer ::
Thread Delay (in milliseconds): 5000

even after giving 5000 milliseconds in constant timer, I am getting 10 hits for every 15 seconds. can someone help me how to get 10 hits at a time for every 5 seconds

答:
Given you have 200 threads and 300 seconds ramp-up time it means that JMeter will start 200 threads in 300 seconds. So you will get 10 threads up and running only by 19th second. You need to decrease your ramp-up time to 100 in order to be able to hit first request with 10 users.

Given you have Loop Count set to 1 JMeter will shut down threads which have already finished their work, I would recommend setting it to -1 so threads will loop forever. You can limit your test duration to desired via "Scheduler" section of the Thread Group or Runtime Controller. See JMeter Test Results: Why the Actual Users Number is Lower than Expected for more detailed explanation.

I would also suggest replacing your Constant Timer with the Test Action sampler so all your threads would be at the same page.

Title: Jmeter - Ramp Up Time vs Constant Timer


问:
Theano: where to input " theano-cache clear"
To remove theano compile cache, Theano 0.9 document says using 'theano-cache clear'.

I don't know where to type the command. I am using anaconda with spyder. Does the command should be input in anaconda prompt, spyder console or cmd?

Typing the command in anaconda prompt yields the error message:

```<code>'theano-cache' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Is there other way in addition to the command to remove the cache?

答:
I also met this error, I delete it in the folder: C:\Users\user\AppData\Local\Theano (maybe I am wrong). But in this way I didn't solve other problems later. I used pip install theano==0.8.2 to install an other version, and installed CUDA7.5, then it worked. My system is Windows 8.1, and my GPU is 830M.

Anyways, I found it is easy to install theano in linux, I have installed it in Ubuntu 16.04.

I hope it can help you.

Body:
To remove theano compile cache, Theano 0.9 document says using 'theano-cache clear'.

I don't know where to type the command. I am using anaconda with spyder. Does the command should be input in anaconda prompt, spyder console or cmd?

Typing the command in anaconda prompt yields the error message:

'theano-cache' is not recognized as an internal or external command,
operable program or batch file.

Is there other way in addition to the command to remove the cache?


问:
Issue while casting amount to Double
my program is receiving amount value as string and then converting it to Double using Double.parseDouble(transAmt).

Now we are getting issue when amount passed is "100.00" .

Please advise if while casting to double zero precision digits will be lost

答:
double holds no precision, and is an approximation, a sum of (negative) powers of 2. Hence 3.10 might on output be 3.0999999785, an error which enlarges when summing or multiplying.

For holding a precision and being precise - as with financial software - BigDecimal is used.

```<code>BigDecimal amount = new BigDecimal("12.99"); // A precision of 2 digits.
BigDecimal base = new BigDecimal("4.33");
assert base.multiply(BigDecimal.valueOf(3)).compareTo(amount) == 0;
</code>```

Unfortunately with BigDecimal normal math operators are not available, but in general it is not as unsafe as with double.

Title: Issue while casting amount to Double

Body:
double holds no precision, and is an approximation, a sum of (negative) powers of 2. Hence 3.10 might on output be 3.0999999785, an error which enlarges when summing or multiplying.

For holding a precision and being precise - as with financial software - BigDecimal is used.

BigDecimal amount = new BigDecimal("12.99"); // A precision of 2 digits.
BigDecimal base = new BigDecimal("4.33");
assert base.multiply(BigDecimal.valueOf(3)).compareTo(amount) == 0;

Unfortunately with BigDecimal normal math operators are not available, but in general it is not as unsafe as with double.


问:
Optimize file and number line count in Python
I got a python project with many folders, files (.css, .py, .yml, etc.) and lines of code. For this project, I made a tool called "statistics" that gives me informations about the entire project such as :

Global statistics:

Entire project ::                              32329 lines

  Project main files (.py, .yml) ::              8420 lines

  Project without vendor part ::                  1070 lines

  Core (src directory) ::                          394 lines

  Core compared to project main files ::           5 %         Kraken
  Framework (vendor/*.py) ::               7350 lines

  Main files Python code ::                       93 %

  Vendor Python code ::                           87 %

  Entire project size ::                          37M

To get all these numbers, I mainly use two functions:

```<code>def count_folder_lines(self, path):
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        num_lines = sum(1 for line in open(file))
        number += num_lines
    return number
</code>```

and

```<code>def count_number_of_files(self, path):
    files = glob.glob(path, recursive=True)
    return len(files)
</code>```

The first one is used to count the number of lines in a folder and the second one is used to count the number of specific files (ex: src/*.py).
But to get the project's statistics, it takes between 4.9 and 5.3 seconds, which is a lot.

Is there any way to make it faster ? Does parallel programming or using Cython would change something ?

Have a nice day,
Thank you.

答:
Finally found the most efficient solution for me :
I'm using multiprocessing module to count the number of lines of each file in parallel.

```<code>def count_folder_lines(self, path):
    """
        Use a buffer to count the number of line of each file among path.
        :param path: string pattern of a file type
        :return: number of lines in matching files
    """
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        f = open(file, 'rb')
        bufgen = takewhile(lambda x: x,
                           (f.raw.read(1024 * 1024) for _ in repeat(None)))
        number += sum(buf.count(b'\n') for buf in bufgen if buf)
    return number

def count_number_of_files(self, path):
    """
        Count number of files for a string pattern
        :param path: files string pattern
        :return: number of files matching the pattern
    """
    files = glob.glob(path, recursive=True)
    return len(files)

def multiproc(self):
    """
        Multiprocessing to launch several processes to count number of
        lines of each string pattern in self.files
        :return: List of number of files per string pattern
                    (list of int).
    """
    pool = mp.Pool()
    asyncResult = pool.map_async(self.count_folder_lines, self.files)
    return asyncResult.get()
</code>```

With this solution, it takes ~1.2s to count versus ~5s before.

Have a good day!

Body:
I got a python project with many folders, files (.css, .py, .yml, etc.) and lines of code. For this project, I made a tool called "statistics" that gives me informations about the entire project such as :

Global statistics:

Entire project ::                              32329 lines

  Project main files (.py, .yml) ::              8420 lines

  Project without vendor part ::                  1070 lines

  Core (src directory) ::                          394 lines

  Core compared to project main files ::           5 %         Kraken
  Framework (vendor/*.py) ::               7350 lines

  Main files Python code ::                       93 %

  Vendor Python code ::                           87 %

  Entire project size ::                          37M

To get all these numbers, I mainly use two functions:

def count_folder_lines(self, path):
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        num_lines = sum(1 for line in open(file))
        number += num_lines
    return number

and

def count_number_of_files(self, path):
    files = glob.glob(path, recursive=True)
    return len(files)

The first one is used to count the number of lines in a folder and the second one is used to count the number of specific files (ex: src/*.py).
But to get the project's statistics, it takes between 4.9 and 5.3 seconds, which is a lot.

Is there any way to make it faster ? Does parallel programming or using Cython would change something ?

Have a nice day,
Thank you.

Body:
Finally found the most efficient solution for me :
I'm using multiprocessing module to count the number of lines of each file in parallel.

def count_folder_lines(self, path):
    """
        Use a buffer to count the number of line of each file among path.
        :param path: string pattern of a file type
        :return: number of lines in matching files
    """
    files = glob.glob(path, recursive=True)
    number = 0
    for file in files:
        f = open(file, 'rb')
        bufgen = takewhile(lambda x: x,
                           (f.raw.read(1024 * 1024) for _ in repeat(None)))
        number += sum(buf.count(b'\n') for buf in bufgen if buf)
    return number

def count_number_of_files(self, path):
    """
        Count number of files for a string pattern
        :param path: files string pattern
        :return: number of files matching the pattern
    """
    files = glob.glob(path, recursive=True)
    return len(files)

def multiproc(self):
    """
        Multiprocessing to launch several processes to count number of
        lines of each string pattern in self.files
        :return: List of number of files per string pattern
                    (list of int).
    """
    pool = mp.Pool()
    asyncResult = pool.map_async(self.count_folder_lines, self.files)
    return asyncResult.get()

With this solution, it takes ~1.2s to count versus ~5s before.

Have a good day!


问:
Saving values from a http post from a nested resource?
I am trying to use a nested resource in rails to create a new record. I am attempting to use of /events/id/entries/new where there is a

```<code><%= form_for([@event, @entry]) do |f| %>
</code>```

on the new page.

My models are:

```<code>class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
  has_many :entries, dependent: :destroy

class Event < ApplicationRecord
  has_many :entries, dependent: :destroy
</code>```

The controller is:

```<code>def new
  @event = Event.find(params[:event_id])
  @entry = @event.entries.build
end

def create
  @user = current_user
  @entry = Entry.new(user_id: @user.id, event_id: :event_id , course: :entry.course , siCard: :entry.siCard)
  if @entry.save
    redirect_to @user
    flash.now[:info] = "Event Created"
  else
    render '/create'
    flash.now[:danger] = "Somthing went wrong"
  end
end
</code>```

But the record does not save NoMethodError in EntriesController#createdespite it saying that the parameters passed are.

```<code>"utf8"=>"✓",
"entry"=>{"course"=>"Orange", "siCard"=>"23232323"},
"commit"=>"Enter",
"event_id"=>"2"}
</code>```

How do I modify the create controller to save the record?

答:
Give this a go:

```<code>@entry = Entry.new(
  user_id:  current_user.id,
  event_id: params[:event_id],
  course:   params[:entry][:course],
  siCard:   params[:entry][:siCard]
)
</code>```

You don't need to @user = current_user, just use current_user.id.

event_id: :event_id is just going to set event_id to a symbol. You want to access the params value, I am guessing. So:

```<code>event_id: params[:event_id]
</code>```

Here:

```<code>course: :entry.course
</code>```

you're trying to call the course method on the :entry symbol. What?!?

Instead:

```<code>course: params[:entry][:course]
</code>```

Same thing with siCard.

BTW, siCard is not very Ruby-ish. Rather, you should do si_card.

Body:
I am trying to use a nested resource in rails to create a new record. I am attempting to use of /events/id/entries/new where there is a

<%= form_for([@event, @entry]) do |f| %>

on the new page.

My models are:

class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
  has_many :entries, dependent: :destroy

class Event < ApplicationRecord
  has_many :entries, dependent: :destroy

The controller is:

def new
  @event = Event.find(params[:event_id])
  @entry = @event.entries.build
end

def create
  @user = current_user
  @entry = Entry.new(user_id: @user.id, event_id: :event_id , course: :entry.course , siCard: :entry.siCard)
  if @entry.save
    redirect_to @user
    flash.now[:info] = "Event Created"
  else
    render '/create'
    flash.now[:danger] = "Somthing went wrong"
  end
end

But the record does not save NoMethodError in EntriesController#createdespite it saying that the parameters passed are.

"utf8"=>"✓",
"entry"=>{"course"=>"Orange", "siCard"=>"23232323"},
"commit"=>"Enter",
"event_id"=>"2"}

How do I modify the create controller to save the record?

Body:
Give this a go:

@entry = Entry.new(
  user_id:  current_user.id,
  event_id: params[:event_id],
  course:   params[:entry][:course],
  siCard:   params[:entry][:siCard]
)

You don't need to @user = current_user, just use current_user.id.

event_id: :event_id is just going to set event_id to a symbol. You want to access the params value, I am guessing. So:

event_id: params[:event_id]

Here:

course: :entry.course

you're trying to call the course method on the :entry symbol. What?!?

Instead:

course: params[:entry][:course]

Same thing with siCard.

BTW, siCard is not very Ruby-ish. Rather, you should do si_card.


问:
Sort files then directories os.listdir PYTHON
I'm trying to sort files and directories in specific way (for me it is usuall way but ok). So I have JPG files, then some txt files or wav and I have some directories I want it sorted like first sort by name all files then sort directories but when I'm trying to do something like :

```<code>path = "/my_path"
arr = os.listdir(path)
arr.sort(key=lambda x: (os.path.isdir(x), x))
print(arr)
</code>```

Code gives me output :

```<code>['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'HRYS', 'WAVS', 'k.txt', 's.wav']
</code>```

but it should be :

```<code>['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'k.txt', 's.wav', 'HRYS', 'WAVS']
</code>```

How to do it in proper way ?

答:
Well, the most straightforward way is to provide an appropriate key, so, you can use:

```<code>arr.sort(key=lambda x: (os.path.isdir(x), x))
</code>```

The key is a tuple, the first item is os.path.isdir(x), which returns a bool.

EDIT: So, to make sure this works, do:

```<code>def isdir(path, x):
    path = os.path.join(path, x)
    return os.path.isdir(path)

arr.sort(key=lambda x: (isdir(path, x), x))
</code>```

Although, it might be easier to use os.scandir, which returns more useful DirEntry objects.

```<code>arr = sorted(os.scandir(), key=lambda x: (x.is_dir(), x.name))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to sort files and directories in specific way (for me it is usuall way but ok). So I have JPG files, then some txt files or wav and I have some directories I want it sorted like first sort by name all files then sort directories but when I'm trying to do something like :

path = "/my_path"
arr = os.listdir(path)
arr.sort(key=lambda x: (os.path.isdir(x), x))
print(arr)

Code gives me output :

['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'HRYS', 'WAVS', 'k.txt', 's.wav']

but it should be :

['10000100.JPG', '10000101.JPG', '10000102.JPG', '10000103.JPG', '10000104.BMP', 'BACKUP.BIN', 'DEPOSIT.BIN', 'k.txt', 's.wav', 'HRYS', 'WAVS']

How to do it in proper way ?

Body:
Well, the most straightforward way is to provide an appropriate key, so, you can use:

arr.sort(key=lambda x: (os.path.isdir(x), x))

The key is a tuple, the first item is os.path.isdir(x), which returns a bool.

EDIT: So, to make sure this works, do:

def isdir(path, x):
    path = os.path.join(path, x)
    return os.path.isdir(path)

arr.sort(key=lambda x: (isdir(path, x), x))

Although, it might be easier to use os.scandir, which returns more useful DirEntry objects.

arr = sorted(os.scandir(), key=lambda x: (x.is_dir(), x.name))


问:
How to transfer the text output into dataframe
I have done some web scraping with beautiful soup and here is the output text I got:

```<code>TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
....
</code>```

How do I save this result into a dataframe?

How to save this information into csv files.

I will need csv files to do further analysis?

答:
Try this code:

```<code>import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA=StringIO("""
TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
    """)

df = pd.read_csv(TESTDATA, sep=" ",header=None)
df.to_csv('output.csv', sep=',')
print df
</code>```

This code will print dataframe and generate output.csv file.

Update 1:

```<code>list_raw=[]
for i in TESTDATA:

    list_raw.append(i.split(' '))

df=pd.DataFrame(list_raw)
print df
</code>```

If it is in for loop reading. Use like shown above code for dataframe conversion. then do df to csv conversion as initially shown code.

Body:
I have done some web scraping with beautiful soup and here is the output text I got:

TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
....

How do I save this result into a dataframe?

How to save this information into csv files.

I will need csv files to do further analysis?

Body:
Try this code:

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA=StringIO("""
TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
TCGA-G9-6373-01A Male  Stage not reported  Alive FPKM 4.7 Living days 811 (2.2 years)
    """)

df = pd.read_csv(TESTDATA, sep=" ",header=None)
df.to_csv('output.csv', sep=',')
print df

This code will print dataframe and generate output.csv file.

Update 1:

list_raw=[]
for i in TESTDATA:

    list_raw.append(i.split(' '))

df=pd.DataFrame(list_raw)
print df

If it is in for loop reading. Use like shown above code for dataframe conversion. then do df to csv conversion as initially shown code.


问:
How to parse jsonarray to listview in fragment

Here my array

```<code>{
 sales_schedule_name: "Visit Client",
 sales_schedule_date: "2018-01-18",
 sales_schedule_time: "10:30:00",
 sales_schedule_address: "Sydney",
 sales_schedule_description: "Sales Visit"
}
</code>```

That array came from schedule.php

```<code> $query = "select sales_schedule_name,sales_schedule_date,sales_schedule_time,sales_schedule_address,sales_schedule_description from sales_schedule";

if ($stmt = $conn->prepare($query)) {
 $stmt->execute();
 $stmt->bind_result($sales_schedule_name, $sales_schedule_date, $sales_schedule_time, $sales_schedule_address, $sales_schedule_description);

 $schedule = array();

 while ($stmt->fetch()) {
     //printf("%s, %s, %s, %s, %s\n", $sales_schedule_name, $sales_schedule_date, $sales_schedule_time, $sales_schedule_address, $sales_schedule_description);
     $temp = array();
     $temp['sales_schedule_name'] = $sales_schedule_name;
     $temp['sales_schedule_date'] = $sales_schedule_date;
     $temp['sales_schedule_time'] = $sales_schedule_time;
     $temp['sales_schedule_address'] = $sales_schedule_address;
     $temp['sales_schedule_description'] = $sales_schedule_description;
     array_push($schedule, $temp);

 }
 $stmt->close();
 }

 //displaying the result in json format
 echo json_encode($schedule);
</code>```

Anyone can help me to call that array on my public list getTestData() using json?

```
public class ScheduleFragment extends Fragment {

    public ScheduleFragment() {
    }
    RecyclerView scheduleRecyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_schedule, container, false);

        getActivity().setTitle("Schedule Task");
        scheduleRecyclerView= view.findViewById(R.id.schedule_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        scheduleRecyclerView.setLayoutManager(linearLayoutManager);
        scheduleRecyclerView.setHasFixedSize(true);
        ScheduleAdapter mAdapter = new ScheduleAdapter(getActivity(), getTestData());
        scheduleRecyclerView.setAdapter(mAdapter);
        return view;
    }

    public List getTestData() {
        final List recentSchedule = new ArrayList();
        recentSchedule.add(new ScheduleObject("Visit Client", "2018-01-18", "10:30","Sydney","Sales Visit"));

        return recentSchedule;
    }

}
```

i was try change with

```<code>public List<ScheduleObject> getTestData() {

    //recentSchedule.add(new ScheduleObject("Visit Client", "11/10/18", "10:30","Sydney","Sales Visit"));

    RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());

    String url= AppConfig.URL_SCHEDULELIST;

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Do something with the response

                    try{

                        JSONObject o = new JSONObject(response);
                        JSONArray values=o.getJSONArray("salesScheduleName");

                        for ( int i=0; i< values.length(); i++) {

                            JSONObject schedules = values.getJSONObject(i);

                            String salesScheduleName = schedules.getString("salesScheduleName");
                            String salesScheduleDate = schedules.getString("salesScheduleDate");
                            String salesScheduleTime = schedules.getString("salesScheduleTime");
                            String salesScheduleAddress = schedules.getString("salesScheduleAddress");
                            String salesScheduleDescription = schedules.getString("salesScheduleDescription");

                            //Use the title and id as per your requirement
                            recentSchedule.add(new ScheduleObject(salesScheduleName, salesScheduleDate, salesScheduleTime, salesScheduleAddress, salesScheduleDescription));
                        }

                    }  catch (JSONException ex){}

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle error
                }
            });
    return recentSchedule;
}
</code>```

But nothing happen

答:
After try to figure out which cause the problem on my listview, finaly this problem solved. Now i can call all data on my listview fragment.</p>

```<code>public List<ScheduleObject> getTestData()   {

   try {

        JSONArray jsonArray=new JSONArray(getURL(AppConfig.URL_SCHEDULELIST));
        //iterate loop
        for(int i=0;i<jsonArray.length();i++){

            //get the JSON Object
            JSONObject schedules=jsonArray.getJSONObject(i);

            //prepare data to schedule list
            String salesschedulename = schedules.getString("salesschedulename");
            String salesscheduledate = schedules.getString("salesscheduledate");
            String salesscheduletime = schedules.getString("salesscheduletime");
            String salesscheduleaddress = schedules.getString("salesscheduleaddress");
            String salesscheduledescription = schedules.getString("salesscheduledescription");

            //adding the schedule to schedule list
            recentSchedule.add(new ScheduleObject(salesschedulename, salesscheduledate, salesscheduletime, salesscheduleaddress, salesscheduledescription));

        }

    } catch (Exception e) {

        System.out.println(e.getMessage());

        Toast toast = Toast.makeText(
                //getActivity(),"Custom Toast From Fragment",Toast.LENGTH_LONG
                getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG
        );
        // Set the Toast display position layout center
        toast.setGravity(Gravity.CENTER,0,0);
        // Finally, show the toast
        toast.show();

    }

    return recentSchedule;
}

public static String getURL(String url) throws Exception {
    URL website = new URL(url);
    URLConnection connection = website.openConnection();
    BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(),"UTF8"));

    StringBuilder response = new StringBuilder();
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine);

    in.close();

    return response.toString();
}
</code>```

Body:
Here my array

{
 sales_schedule_name: "Visit Client",
 sales_schedule_date: "2018-01-18",
 sales_schedule_time: "10:30:00",
 sales_schedule_address: "Sydney",
 sales_schedule_description: "Sales Visit"
}

That array came from schedule.php

 $query = "select sales_schedule_name,sales_schedule_date,sales_schedule_time,sales_schedule_address,sales_schedule_description from sales_schedule";

if ($stmt = $conn->prepare($query)) {
 $stmt->execute();
 $stmt->bind_result($sales_schedule_name, $sales_schedule_date, $sales_schedule_time, $sales_schedule_address, $sales_schedule_description);

 $schedule = array();

 while ($stmt->fetch()) {
     //printf("%s, %s, %s, %s, %s\n", $sales_schedule_name, $sales_schedule_date, $sales_schedule_time, $sales_schedule_address, $sales_schedule_description);
     $temp = array();
     $temp['sales_schedule_name'] = $sales_schedule_name;
     $temp['sales_schedule_date'] = $sales_schedule_date;
     $temp['sales_schedule_time'] = $sales_schedule_time;
     $temp['sales_schedule_address'] = $sales_schedule_address;
     $temp['sales_schedule_description'] = $sales_schedule_description;
     array_push($schedule, $temp);

 }
 $stmt->close();
 }

 //displaying the result in json format
 echo json_encode($schedule);

Anyone can help me to call that array on my public list getTestData() using json?

public class ScheduleFragment extends Fragment {

    public ScheduleFragment() {
    }
    RecyclerView scheduleRecyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_schedule, container, false);

        getActivity().setTitle("Schedule Task");
        scheduleRecyclerView= view.findViewById(R.id.schedule_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        scheduleRecyclerView.setLayoutManager(linearLayoutManager);
        scheduleRecyclerView.setHasFixedSize(true);
        ScheduleAdapter mAdapter = new ScheduleAdapter(getActivity(), getTestData());
        scheduleRecyclerView.setAdapter(mAdapter);
        return view;
    }

    public List getTestData() {
        final List recentSchedule = new ArrayList();
        recentSchedule.add(new ScheduleObject("Visit Client", "2018-01-18", "10:30","Sydney","Sales Visit"));

        return recentSchedule;
    }

}

i was try change with

public List<ScheduleObject> getTestData() {

    //recentSchedule.add(new ScheduleObject("Visit Client", "11/10/18", "10:30","Sydney","Sales Visit"));

    RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());

    String url= AppConfig.URL_SCHEDULELIST;

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Do something with the response

                    try{

                        JSONObject o = new JSONObject(response);
                        JSONArray values=o.getJSONArray("salesScheduleName");

                        for ( int i=0; i< values.length(); i++) {

                            JSONObject schedules = values.getJSONObject(i);

                            String salesScheduleName = schedules.getString("salesScheduleName");
                            String salesScheduleDate = schedules.getString("salesScheduleDate");
                            String salesScheduleTime = schedules.getString("salesScheduleTime");
                            String salesScheduleAddress = schedules.getString("salesScheduleAddress");
                            String salesScheduleDescription = schedules.getString("salesScheduleDescription");

                            //Use the title and id as per your requirement
                            recentSchedule.add(new ScheduleObject(salesScheduleName, salesScheduleDate, salesScheduleTime, salesScheduleAddress, salesScheduleDescription));
                        }

                    }  catch (JSONException ex){}

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // Handle error
                }
            });
    return recentSchedule;
}

But nothing happen

Body:
After try to figure out which cause the problem on my listview, finaly this problem solved. Now i can call all data on my listview fragment.

public List<ScheduleObject> getTestData()   {

   try {

        JSONArray jsonArray=new JSONArray(getURL(AppConfig.URL_SCHEDULELIST));
        //iterate loop
        for(int i=0;i<jsonArray.length();i++){

            //get the JSON Object
            JSONObject schedules=jsonArray.getJSONObject(i);

            //prepare data to schedule list
            String salesschedulename = schedules.getString("salesschedulename");
            String salesscheduledate = schedules.getString("salesscheduledate");
            String salesscheduletime = schedules.getString("salesscheduletime");
            String salesscheduleaddress = schedules.getString("salesscheduleaddress");
            String salesscheduledescription = schedules.getString("salesscheduledescription");

            //adding the schedule to schedule list
            recentSchedule.add(new ScheduleObject(salesschedulename, salesscheduledate, salesscheduletime, salesscheduleaddress, salesscheduledescription));

        }

    } catch (Exception e) {

        System.out.println(e.getMessage());

        Toast toast = Toast.makeText(
                //getActivity(),"Custom Toast From Fragment",Toast.LENGTH_LONG
                getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG
        );
        // Set the Toast display position layout center
        toast.setGravity(Gravity.CENTER,0,0);
        // Finally, show the toast
        toast.show();

    }

    return recentSchedule;
}

public static String getURL(String url) throws Exception {
    URL website = new URL(url);
    URLConnection connection = website.openConnection();
    BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(),"UTF8"));

    StringBuilder response = new StringBuilder();
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine);

    in.close();

    return response.toString();
}


问:
Swift Compiler Error: Type '[AnyHashable : Any]?' has no subscript members
I'm currently making an ecommerce app in Swift 4 and linking data with Moltin. I'm doing this for school so I'm new at this. I'm also following CodeWithChris's tutorial but that is out of date and my layout is a bit different. I followed everything on it but I'm getting this error:

Type '[AnyHashable : Any]?' has no subscript members

I don't understand why.

```<code>self.objects = responseDictionary["result"] as? [AnyObject]
</code>```

I tried changing as? to as! and it still didn't work.

Here's my complete code;

```<code>import UIKit
import Moltin

class TableViewController: UITableViewController {
var objects = [AnyObject]()

override func viewDidLoad() {
   super.viewDidLoad()
   Moltin.sharedInstance().setPublicID('***my store ID***')

    Moltin.sharedInstance().product.listing(withParameters: nil, success: { (responseDictionary) in
        self.objects = responseDictionary["result"] as? [AnyObject]

        self.tableView.reloadData()
    }) { (responseDictionary, error) in
        print ("Something went wrong")
    }
}
</code>```

答:
responseDictionary appears to be an optional which needs to be checked for existence:

```<code>Moltin.sharedInstance().product.listing(withParameters: nil, success: { (response) in
    guard let responseDictionary = response as? [AnyHashable : Any] else {
        print("Error: respnonse is empty")
        return
    }

    self.objects = responseDictionary["result"] as? [AnyObject]

   // ...
}
</code>```

Body:
I'm currently making an ecommerce app in Swift 4 and linking data with Moltin. I'm doing this for school so I'm new at this. I'm also following CodeWithChris's tutorial but that is out of date and my layout is a bit different. I followed everything on it but I'm getting this error:

Type '[AnyHashable : Any]?' has no subscript members

I don't understand why.

self.objects = responseDictionary["result"] as? [AnyObject]

I tried changing as? to as! and it still didn't work.

Here's my complete code;

import UIKit
import Moltin

class TableViewController: UITableViewController {
var objects = [AnyObject]()

override func viewDidLoad() {
   super.viewDidLoad()
   Moltin.sharedInstance().setPublicID('***my store ID***')

    Moltin.sharedInstance().product.listing(withParameters: nil, success: { (responseDictionary) in
        self.objects = responseDictionary["result"] as? [AnyObject]

        self.tableView.reloadData()
    }) { (responseDictionary, error) in
        print ("Something went wrong")
    }
}

Body:
responseDictionary appears to be an optional which needs to be checked for existence:

Moltin.sharedInstance().product.listing(withParameters: nil, success: { (response) in
    guard let responseDictionary = response as? [AnyHashable : Any] else {
        print("Error: respnonse is empty")
        return
    }

    self.objects = responseDictionary["result"] as? [AnyObject]

   // ...
}


问:
Helm: generate comma separated list
Using Helm templates, I'm trying to generate a list of server names based on a number in values.yaml.  The dot for this template is set to the number (its a float64).

```<code>{{- define "zkservers" -}}
{{- $zkservers := list -}}
{{- range int . | until -}}
{{- $zkservers := print "zk-" . ".zookeeper" | append $zkservers -}}
{{- end -}}
{{- join "," $zkservers -}}
{{- end -}}
</code>```

For an input of, say, 3 I'm expecting this to produce:

```<code>zk-0.zookeeper,zk-1.zookeeper,zk-2.zookeeper
</code>```

It produces nothing.

I understand that the line within the range block is a no-op since the variable $zkservers is a new variable each time the loop iterates. It is not the same variable as the $zkservers in the outer scope.

I hope the intention is clear of what I want to do. I am at a loss how to do it.

Anyone know how to do this with Helm templates?

答:
I got it working using:

```<code>{{- define "zkservers" -}}
{{- $dot := dict "nodes" (int .) "servers" (list) -}}
{{- template "genservers" $dot -}}
{{- join "," $dot.servers -}}
{{- end -}}

{{- define "genservers" -}}
{{- range until .nodes -}}
{{- $noop := print "zk-" . ".zookeeper" | append $.servers | set $ "servers" -}}
{{- end -}}
{{- end -}}
</code>```

Seems a little bit verbose for what should normally be a simple one/two liner :)

Title: Helm: generate comma separated list

Body:
Using Helm templates, I'm trying to generate a list of server names based on a number in values.yaml.  The dot for this template is set to the number (its a float64).

{{- define "zkservers" -}}
{{- $zkservers := list -}}
{{- range int . | until -}}
{{- $zkservers := print "zk-" . ".zookeeper" | append $zkservers -}}
{{- end -}}
{{- join "," $zkservers -}}
{{- end -}}

For an input of, say, 3 I'm expecting this to produce:

zk-0.zookeeper,zk-1.zookeeper,zk-2.zookeeper

It produces nothing.

I understand that the line within the range block is a no-op since the variable $zkservers is a new variable each time the loop iterates. It is not the same variable as the $zkservers in the outer scope.

I hope the intention is clear of what I want to do. I am at a loss how to do it.

Anyone know how to do this with Helm templates?

Body:
I got it working using:

{{- define "zkservers" -}}
{{- $dot := dict "nodes" (int .) "servers" (list) -}}
{{- template "genservers" $dot -}}
{{- join "," $dot.servers -}}
{{- end -}}

{{- define "genservers" -}}
{{- range until .nodes -}}
{{- $noop := print "zk-" . ".zookeeper" | append $.servers | set $ "servers" -}}
{{- end -}}
{{- end -}}

Seems a little bit verbose for what should normally be a simple one/two liner :)


问:
Bearer token based authentication in swagger 3.x
I'm currently using swagger-ui 2.x and following is the authentication I've been using with swagger-ui 2.x.

var key = $(this).val();
swaggerUi.api.clientAuthorizations.add("default", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer "+ key, "header"));

Currently, I'm upgrading the swagger-ui into latest 3.x version and I need to know how to achieve above with swagger 3.x. Can I have on bearer token based authentication?

答:
At the moment SwaggerUI 3.x doesn't seem to have an exact way of doing this. However you can add a request interceptor when initializing SwaggerUIBundle. There you can inject the authorization header to achieve you requirement.

Ex:

SwaggerUIBundle({
    spec: spec ,
    dom_id: '#someId',
    presets: [
        SwaggerUIBundle.presets.apis
    ],
    requestInterceptor: function(request) {
        request.headers.Authorization = "Bearer " + key;
        return request;
    }
});```


问:
How to stop ListView for "jumping" when model is changed
What I need to do: I need to create a chat window using a ListView in QML that stores the chat-messages. I set listView.positionViewAtEnd() in order to follow the last messages. I disable positionViewAtEnd when I scroll upwards such that I can read the past messages without jumping at the end every time I receive a new message.

The problem: After scrolling up, every time I receive a new message it jumps at the beginning of list. To solve that I manage to store the contentY of the list and reset it every time onCountChanged handler is called (see the code below):

```<code>ListView {
    id: messagesList
    model: contact? contact.messages: []
    delegate: delegate
    anchors.fill: parent
    anchors.bottomMargin: 20
    height: parent.height
    anchors.margins: 10

    property int currentContentY

    onMovementEnded: {
       currentContentY = contentY
    }

    onCountChanged: {
        contentY = currentContentY
    }
    onContentYChanged: {
        console.log(".....contentY: " + contentY)
    }
}
</code>```

The problem is that even though I set the last contentY I had, before the model was changed, the list still jumps a bit (several pixels, not at the end or beginning) and it doesn't jump always. And when I go to the top of the list and print the contentY I get negative values. Theoretically, contentY at the beginning of the list should be 0.

Can somebody tell me what is going wrong? Or maybe suggest another solution to create my message list?

Than you in advance! :)

答:
One possible solution schould be insert ListView into Flickable and disable interactive flag for ListView

```<code>    Flickable {
        id: fparent
        anchors.fill: parent
        anchors.bottomMargin: 20
        anchors.margins: 10

        interactive: true
        clip: true
        flickableDirection: Flickable.VerticalFlick
        contentHeight: messagesList.height

        ListView {
            id: messagesList
            width: parent.width
            height: childrenRect.height
            clip: true
            model: contact? contact.messages: []
            delegate: delegate
            interactive: false
            onCountChanged: {
                fparents.returnToBounds();
            }
        }
    }
</code>```

Body:
What I need to do: I need to create a chat window using a ListView in QML that stores the chat-messages. I set listView.positionViewAtEnd() in order to follow the last messages. I disable positionViewAtEnd when I scroll upwards such that I can read the past messages without jumping at the end every time I receive a new message.

The problem: After scrolling up, every time I receive a new message it jumps at the beginning of list. To solve that I manage to store the contentY of the list and reset it every time onCountChanged handler is called (see the code below):

ListView {
    id: messagesList
    model: contact? contact.messages: []
    delegate: delegate
    anchors.fill: parent
    anchors.bottomMargin: 20
    height: parent.height
    anchors.margins: 10

    property int currentContentY

    onMovementEnded: {
       currentContentY = contentY
    }

    onCountChanged: {
        contentY = currentContentY
    }
    onContentYChanged: {
        console.log(".....contentY: " + contentY)
    }
}

The problem is that even though I set the last contentY I had, before the model was changed, the list still jumps a bit (several pixels, not at the end or beginning) and it doesn't jump always. And when I go to the top of the list and print the contentY I get negative values. Theoretically, contentY at the beginning of the list should be 0.

Can somebody tell me what is going wrong? Or maybe suggest another solution to create my message list?

Than you in advance! :)

Body:
One possible solution schould be insert ListView into Flickable and disable interactive flag for ListView

    Flickable {
        id: fparent
        anchors.fill: parent
        anchors.bottomMargin: 20
        anchors.margins: 10

        interactive: true
        clip: true
        flickableDirection: Flickable.VerticalFlick
        contentHeight: messagesList.height

        ListView {
            id: messagesList
            width: parent.width
            height: childrenRect.height
            clip: true
            model: contact? contact.messages: []
            delegate: delegate
            interactive: false
            onCountChanged: {
                fparents.returnToBounds();
            }
        }
    }


问:
What is Zone.js and core-js thing in angular 2?
I have been using angular 2 from last year but I did not get answer why we are using zone.js and core js in angular 2 file?
Can anyone explain in details in your own word?</p>

答:
core.js includes polyfills to be able to use new features that are not available in all browsers yet and still make the code run on these browsers.

zone.js is the basis for all change detection in Angular.
It wraps all Angular code in a scope where async calls like addEventListener, setTimeout, ... are patched so that Angular gets notified when they are completed. Angular runs change detection automatically every time such an async call is completed.
This allows it to reduce change detection cycles to the absolute minimum.


问:
How to check divisibility of a number not in base 10 without converting?
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

```<code>class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};
</code>```

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

答:
If your number k is in base three, then you can write it as

```<code>k = a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0
</code>```

where a0, a1, ..., an are the digits in the base-three representation.

To see if the number is divisible by two, you're interested in whether the number, modulo 2, is equal to zero.  Well, k mod 2 is given by

```<code>k mod 2 = (a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0) mod 2
        = (a0 3^n) mod 2 + (a1 3^{n-1}) mod 2 + ... + an (3^0) mod 2
        = (a0 mod 2) (3^n mod 2) + ... + (an mod 2) (3^0 mod 2)
</code>```

The trick here is that 3^i = 1 (mod 2), so this expression is

```<code>k mod 2 = (a0 mod 2) + (a1 mod 2) + ... + (an mod 2)
</code>```

In other words, if you sum up the digits of the ternary representation and get that this value is divisible by two, then the number itself must be divisible by two.  To make this even cooler, since the only ternary digits are 0, 1, and 2, this is equivalent to asking whether the number of 1s in the ternary representation is even!

More generally, though, if you have a number in base m, then that number is divisible by m - 1 iff the sum of the digits is divisible by m.  This is why you can check if a number in base 10 is divisible by 9 by summing the digits and seeing if that value is divisible by nine.

Body:
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

Body:
If your number k is in base three, then you can write it as

k = a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0

where a0, a1, ..., an are the digits in the base-three representation.

To see if the number is divisible by two, you're interested in whether the number, modulo 2, is equal to zero.  Well, k mod 2 is given by

k mod 2 = (a0 3^n + a1 3^{n-1} + a2 3^{n-2} + ... + an 3^0) mod 2
        = (a0 3^n) mod 2 + (a1 3^{n-1}) mod 2 + ... + an (3^0) mod 2
        = (a0 mod 2) (3^n mod 2) + ... + (an mod 2) (3^0 mod 2)

The trick here is that 3^i = 1 (mod 2), so this expression is

k mod 2 = (a0 mod 2) + (a1 mod 2) + ... + (an mod 2)

In other words, if you sum up the digits of the ternary representation and get that this value is divisible by two, then the number itself must be divisible by two.  To make this even cooler, since the only ternary digits are 0, 1, and 2, this is equivalent to asking whether the number of 1s in the ternary representation is even!

More generally, though, if you have a number in base m, then that number is divisible by m - 1 iff the sum of the digits is divisible by m.  This is why you can check if a number in base 10 is divisible by 9 by summing the digits and seeing if that value is divisible by nine.


问:
Is multiple login possible with firebase authentication?
I develop some kind of website

This website requires multiple logins

So I asked this question.

Is it possible for a website user to have multiple authentications
  with one email account?

Is it possible to authenticate 100 devices with one ID?

答:
If you are asking to login with same credentials on multiple devices then it's possible.

But you can't create multiple user accounts with one email id.


答:
You can try

```<code>library(tidyverse)
d %>%
  gather(key, value, -PtsAgRdTm) %>%
  ggplot(aes(x=PtsAgRdTm, y=value, fill=key)) +
   geom_col(position = "dodge")
</code>```

You transform the data from wide to long using tidyr's gather function, then plot the bars in a "dodge" or a "stack" way.

Title: ggplot Grouped barplot with R

Body:
I am having difficulties creating a grouped barplot. This is my first time using anything other than the scatter plot in R. There is the Team, and the points they give up to the position(Below the Code). C, D, and W. Going off the r-graph-gallery for the code below.

library(ggplot2)
positions=rep(c("C","W","D"))

ggplot(data=stats, aes(fill=positions, y=0,200,x=PtsAgRdTm))+
  geom_bar(position = "dodge", stat = "indentity")

Below is the df as stats than converted to data.

PtsAgRdTm     C       D       W
ANH         57.73   65.08   56.08
ARI         33      29.24   26.99
BOS         56.64   44.97   56.15
BUF         35.36   31.04   38.35
CAR         42.6    49.79   78.03
CLS         38.23   53.16   67.92
CGY         56.19   54.87   78.54
CHI         37.04   47.93   74.95
COL         54.87   47.83   78.22
DAL         59.05   39.67   33.3
DET         26.11   34.15   71.21
EDM         57.64   53.01   43.14
FLA         71.09   44.85   44.91
LA          53.06   48.62   42.11
MIN         41.86   51.44   51.93
MON         36.6    50      89.02
NJ          26.95   34.64   49.61
NSH         43.12   60.05   83.11
NYI         51.58   46.36   46.99
NYR         75.15   104.19  177.69
OTT         51.01   64.75   75.05
PHI         65.96   54.69   40.56
PIT         42.67   38.08   52.33
SJ          70.83   56.66   44.31
STL         40.51   58.83   81.85
TB          68      50.93   58.22
TOR         71.28   42.17   21.5
VAN         29.81   28.79   41.4
VGK         40.09   43.63   63.49
WPG         49.66   48.09   77.08
WAS         47.68   52.02   70.12

Body:
You can try

library(tidyverse)
d %>%
  gather(key, value, -PtsAgRdTm) %>%
  ggplot(aes(x=PtsAgRdTm, y=value, fill=key)) +
   geom_col(position = "dodge")

You transform the data from wide to long using tidyr's gather function, then plot the bars in a "dodge" or a "stack" way.


问:
Jquery change select value not working
I'm trying to set the select option with jquery but it's not working properly. It actually set the value but the text is not updated.

I have tried with .prop('selected',true), .attr('selected',true), .prop('selected','selected'), .val() and .val().change() but nothig seems to work

Here is the select

```<code><select class="input-field" id="equip_type" name="equip_type">
    <option value="" disabled selected>Tipo de Equipo </option>
    <option value="0">equip_type_other</option>
    <option value="1">equip_type_desktop</option>
    <option value="2">equip_type_laptop</option>
    <option value="3">equip_type_tablet</option>
    <option value="4">equip_type_printer</option>
</select>
</code>```

I'm going to set the option within an ajax function, so the value came from the function. This is what I'm currently trying

```<code>$('#equip_type').val(data.equipType).change();
</code>```

I have use the same method with other forms, but just this one is causing this truble. Is there something I'm missing?

答:
```<code>$('option:selected', '#my_select').val();
</code>```

First parameter selector for selected child element, second - for parent. Then call val() method to get value for selected child of select with my_select as id.

Title: Jquery change select value not working

Body:
I'm trying to set the select option with jquery but it's not working properly. It actually set the value but the text is not updated.

I have tried with .prop('selected',true), .attr('selected',true), .prop('selected','selected'), .val() and .val().change() but nothig seems to work

Here is the select

<select class="input-field" id="equip_type" name="equip_type">
    <option value="" disabled selected>Tipo de Equipo </option>
    <option value="0">equip_type_other</option>
    <option value="1">equip_type_desktop</option>
    <option value="2">equip_type_laptop</option>
    <option value="3">equip_type_tablet</option>
    <option value="4">equip_type_printer</option>
</select>

I'm going to set the option within an ajax function, so the value came from the function. This is what I'm currently trying

$('#equip_type').val(data.equipType).change();

I have use the same method with other forms, but just this one is causing this truble. Is there something I'm missing?

Body:
$('option:selected', '#my_select').val();

First parameter selector for selected child element, second - for parent. Then call val() method to get value for selected child of select with my_select as id.


问:
Join multiple rows of data to query
I am trying to join multiple rows of data onto a sql query.

My database consists of a few tables: clients, client_site_ip, and ip_accounting.

client_site_ip table has the following rows: siteid, userid, site_name and site_ip.

ip_accounting table has the following rows: id, src_address, dst_address, bytes and timeanddate.

clients table has the following rows: userid, username ...... and ipaddress

I am wanting clients to have multiple IP addresses so I have created the table client_site_ip

I need to query the database and get more than one row of data per ip address:
userid | username | datapackage | sitename | ipaddress | packagename | speedlimit ........ the list goes a bit further.

I currently have this query that separates the IP addresses and everything by a comma but need it separated by rows of new data not commas:

```<code>SELECT
    clients.userid,
    clients.username,
    clients.datapackage,
    client_site_ip.userid,
    GROUP_CONCAT(client_site_ip.site_name) AS sitenames,
    GROUP_CONCAT(client_site_ip.site_ip) AS ipaddresses,
    data_packages.packagename,
    data_packages.speedlimit,
    data_packages.threshold,
    data_packages.accountingdays,
    data_packages.throttlelimit,
    data_packages.datalimitamount
FROM
    clients
    JOIN client_site_ip ON clients.userid = client_site_ip.userid
    JOIN data_packages ON clients.datapackage = data_packages.package_id
GROUP BY
    clients.userid
</code>```

I also need my synchronization query updated, the current script looks like:

```<code>SELECT ip_address
              ,SUM(upload_bytes) as upload_bytes
              ,SUM(download_bytes) as download_bytes
              ,sum(upload_bytes + download_bytes) as totalbytes
              ,package_id
              ,username
              ,userid
              ,networkaccess
              ,packagename
              ,speedlimit
              ,threshold
              ,throttlelimit
              ,extendeddata
              ,datalimitamount
              ,accountingdays
        FROM (
              (SELECT ip_accounting.src_address as ip_address
                     ,SUM(ip_accounting.bytes) AS upload_bytes
                     ,0 as download_bytes
                     ,clients.username
                     ,clients.userid
                     ,clients.networkaccess
                     ,clients.extendeddata
                     ,data_packages.package_id
                     ,data_packages.packagename
                     ,data_packages.speedlimit
                     ,data_packages.threshold
                     ,data_packages.throttlelimit
                     ,data_packages.datalimitamount
                     ,data_packages.accountingdays
              FROM ip_accounting
              join clients on clients.ipaddress = ip_accounting.src_address
              join data_packages on data_packages.package_id =
clients.datapackage
              WHERE dst_address NOT BETWEEN INET_NTOA('192.168.0.1') AND
INET_NTOA('192.168.255.254')
              and timeanddate BETWEEN SUBDATE(CURRENT_TIMESTAMP(), INTERVAL
data_packages.accountingdays DAY) AND CURRENT_TIMESTAMP()
              GROUP BY src_address)

              UNION ALL

              (SELECT ip_accounting.dst_address as ip_address
                     ,0 AS upload_bytes
                     ,SUM(ip_accounting.bytes) as download_bytes
                     ,clients.username
                     ,clients.userid
                     ,clients.networkaccess
                     ,clients.extendeddata
                     ,data_packages.package_id
                     ,data_packages.packagename
                     ,data_packages.speedlimit
                     ,data_packages.threshold
                     ,data_packages.throttlelimit
                     ,data_packages.datalimitamount
                     ,data_packages.accountingdays
               FROM ip_accounting
               join clients on clients.ipaddress = ip_accounting.dst_address
               join data_packages on data_packages.package_id = clients.datapackage
               WHERE src_address NOT BETWEEN INET_NTOA('192.168.0.1') AND INET_NTOA('192.168.255.254')
               and timeanddate BETWEEN SUBDATE(CURRENT_TIMESTAMP(), INTERVAL data_packages.accountingdays DAY) AND CURRENT_TIMESTAMP()
               GROUP BY dst_address)
                ) a
        GROUP BY ip_address
        ORDER BY INET_ATON(ip_address)
</code>```

答:
If you want separate rows for each site_ip and site_name, you can group on these columns as well

```<code>SELECT
    clients.userid,
    clients.username,
    clients.datapackage,
    client_site_ip.userid,
    client_site_ip.site_name AS sitenames,
    client_site_ip.site_ip AS ipaddresses,
    data_packages.packagename,
    data_packages.speedlimit,
    data_packages.threshold,
    data_packages.accountingdays,
    data_packages.throttlelimit,
    data_packages.datalimitamount
FROM
    clients
    JOIN client_site_ip ON clients.userid = client_site_ip.userid
    JOIN data_packages ON clients.datapackage = data_packages.package_id
GROUP BY
    clients.userid, client_site_ip.site_name, client_site_ip.site_ip
</code>```

As far your synchronization query goes, I don't believe you'll need any update since all joins are already on ipaddress etc. and not on group_concat

Title: Join multiple rows of data to query

Body:
I am trying to join multiple rows of data onto a sql query.

My database consists of a few tables: clients, client_site_ip, and ip_accounting.

client_site_ip table has the following rows: siteid, userid, site_name and site_ip.

ip_accounting table has the following rows: id, src_address, dst_address, bytes and timeanddate.

clients table has the following rows: userid, username ...... and ipaddress

I am wanting clients to have multiple IP addresses so I have created the table client_site_ip

I need to query the database and get more than one row of data per ip address:
userid | username | datapackage | sitename | ipaddress | packagename | speedlimit ........ the list goes a bit further.

I currently have this query that separates the IP addresses and everything by a comma but need it separated by rows of new data not commas:

SELECT
    clients.userid,
    clients.username,
    clients.datapackage,
    client_site_ip.userid,
    GROUP_CONCAT(client_site_ip.site_name) AS sitenames,
    GROUP_CONCAT(client_site_ip.site_ip) AS ipaddresses,
    data_packages.packagename,
    data_packages.speedlimit,
    data_packages.threshold,
    data_packages.accountingdays,
    data_packages.throttlelimit,
    data_packages.datalimitamount
FROM
    clients
    JOIN client_site_ip ON clients.userid = client_site_ip.userid
    JOIN data_packages ON clients.datapackage = data_packages.package_id
GROUP BY
    clients.userid

I also need my synchronization query updated, the current script looks like:

SELECT ip_address
              ,SUM(upload_bytes) as upload_bytes
              ,SUM(download_bytes) as download_bytes
              ,sum(upload_bytes + download_bytes) as totalbytes
              ,package_id
              ,username
              ,userid
              ,networkaccess
              ,packagename
              ,speedlimit
              ,threshold
              ,throttlelimit
              ,extendeddata
              ,datalimitamount
              ,accountingdays
        FROM (
              (SELECT ip_accounting.src_address as ip_address
                     ,SUM(ip_accounting.bytes) AS upload_bytes
                     ,0 as download_bytes
                     ,clients.username
                     ,clients.userid
                     ,clients.networkaccess
                     ,clients.extendeddata
                     ,data_packages.package_id
                     ,data_packages.packagename
                     ,data_packages.speedlimit
                     ,data_packages.threshold
                     ,data_packages.throttlelimit
                     ,data_packages.datalimitamount
                     ,data_packages.accountingdays
              FROM ip_accounting
              join clients on clients.ipaddress = ip_accounting.src_address
              join data_packages on data_packages.package_id =
clients.datapackage
              WHERE dst_address NOT BETWEEN INET_NTOA('192.168.0.1') AND
INET_NTOA('192.168.255.254')
              and timeanddate BETWEEN SUBDATE(CURRENT_TIMESTAMP(), INTERVAL
data_packages.accountingdays DAY) AND CURRENT_TIMESTAMP()
              GROUP BY src_address)

              UNION ALL

              (SELECT ip_accounting.dst_address as ip_address
                     ,0 AS upload_bytes
                     ,SUM(ip_accounting.bytes) as download_bytes
                     ,clients.username
                     ,clients.userid
                     ,clients.networkaccess
                     ,clients.extendeddata
                     ,data_packages.package_id
                     ,data_packages.packagename
                     ,data_packages.speedlimit
                     ,data_packages.threshold
                     ,data_packages.throttlelimit
                     ,data_packages.datalimitamount
                     ,data_packages.accountingdays
               FROM ip_accounting
               join clients on clients.ipaddress = ip_accounting.dst_address
               join data_packages on data_packages.package_id = clients.datapackage
               WHERE src_address NOT BETWEEN INET_NTOA('192.168.0.1') AND INET_NTOA('192.168.255.254')
               and timeanddate BETWEEN SUBDATE(CURRENT_TIMESTAMP(), INTERVAL data_packages.accountingdays DAY) AND CURRENT_TIMESTAMP()
               GROUP BY dst_address)
                ) a
        GROUP BY ip_address
        ORDER BY INET_ATON(ip_address)

Body:
If you want separate rows for each site_ip and site_name, you can group on these columns as well

SELECT
    clients.userid,
    clients.username,
    clients.datapackage,
    client_site_ip.userid,
    client_site_ip.site_name AS sitenames,
    client_site_ip.site_ip AS ipaddresses,
    data_packages.packagename,
    data_packages.speedlimit,
    data_packages.threshold,
    data_packages.accountingdays,
    data_packages.throttlelimit,
    data_packages.datalimitamount
FROM
    clients
    JOIN client_site_ip ON clients.userid = client_site_ip.userid
    JOIN data_packages ON clients.datapackage = data_packages.package_id
GROUP BY
    clients.userid, client_site_ip.site_name, client_site_ip.site_ip

As far your synchronization query goes, I don't believe you'll need any update since all joins are already on ipaddress etc. and not on group_concat


问:
Get full path from FileSystem
I want to get the full path for a FileSystem which I created like this.

```<code>FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);
</code>```

Whatever I tried until now only got me an output like / and thats it, but what i really need to get is:

```<code>C:/Users/username/AppData/Local/Temp/junit9210120109362016454/Parent/test.zip/
</code>```

Is there any way to get this information from the FileSystem object? I know I could just take the parameter I used to create it in the first place, but I want to be sure I don't mix anything up and I think it's better like that for a unit-test

Based on the accepted answer I came up with this to solve my problem:
Paths.get(fs.toString(), "file.txt").toString()

答:
Use
Path from java.nio.file.Path;

```<code>Path path = Paths.get(directory.toString());
String fullpath=path.toUri().toString()
</code>```

which will give full path like file:///F:/somedir1/somdir2/17f5b00a-bd6e-4109-8ce5-85df79b51a00.jpg

Title: Get full path from FileSystem

Body:
I want to get the full path for a FileSystem which I created like this.

FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

Whatever I tried until now only got me an output like / and thats it, but what i really need to get is:

C:/Users/username/AppData/Local/Temp/junit9210120109362016454/Parent/test.zip/

Is there any way to get this information from the FileSystem object? I know I could just take the parameter I used to create it in the first place, but I want to be sure I don't mix anything up and I think it's better like that for a unit-test

Based on the accepted answer I came up with this to solve my problem:
Paths.get(fs.toString(), "file.txt").toString()

Body:
Use
Path from java.nio.file.Path;

Path path = Paths.get(directory.toString());
String fullpath=path.toUri().toString()

which will give full path like file:///F:/somedir1/somdir2/17f5b00a-bd6e-4109-8ce5-85df79b51a00.jpg


问:
how set splitpane divider width in javafx 2
I have SplitPane in my application. This is SplitPane have divider with default width.
How can i set the width of SplitPane Divider</p>

```<code>@FXML
private SplitPane splitPane;
// splitPane here get Divider and set New Width
</code>```

答:
For JavaFX8: If you create your view from .fxml file, you can set divider's position using the attribute dividerPosition of the node SplitPane:

```<code><SplitPane dividerPositions="0.3">

</SplitPane>
</code>```

Body:
I have SplitPane in my application. This is SplitPane have divider with default width.
How can i set the width of SplitPane Divider

@FXML
private SplitPane splitPane;
// splitPane here get Divider and set New Width

Body:
For JavaFX8: If you create your view from .fxml file, you can set divider's position using the attribute dividerPosition of the node SplitPane:

<SplitPane dividerPositions="0.3">

</SplitPane>


问:
Remove extra spaces in sp_send_dbmail
I have the following table:

```<code>CREATE TABLE [dbo].[MyTable](
    [Day_ID] [nvarchar](50) NULL,
    [SAS] [nvarchar](50) NULL,
    [STAMP] [datetime] NULL DEFAULT (getdate())
)
</code>```

which contains this data:

'2017_12_06_01','Red'

'2017_12_06_02','Yellow'

'2017_12_06_03','Green'

'2017_12_06_04','Blue'

I also have a SP which read all the data from MyTable and send it in the body of an e-mail message.

```<code>SET NOCOUNT ON;

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'MyMailProfile'
        ,@recipients = 'me@account.com'
        ,@subject = 'This is the object'
        ,@body = 'This is the body:'
        ,@body_format = 'TEXT'
        ,@query = 'SET NOCOUNT ON select [Day_ID],[SAS] from MyTable SET NOCOUNT OFF'
        ,@attach_query_result_as_file = 0
        ,@query_result_separator = '|'
        ,@exclude_query_output = 1
        ,@query_result_no_padding = 0
        ,@query_result_header = 0
        ,@append_query_error=1
</code>```

Everything works but my problem is that in the body the results appear like these:

```<code>2017_12_06_01                                   |Red
2017_12_06_02                                   |Yellow
2017_12_06_03                                   |Green
2017_12_06_04                                   |Blue
</code>```

In other words SQL Server know that the columns could be 50 characters long so they fill the space that doesn't contain characters with spaces. This is very boring if you consider that happen also if you write numeric values into a column, for example, NUMERIC.
I've tried with LTRIM and RTRIM but nothing changed.

I am using SQL Server 2005.

答:
The parameter @query_result_no_padding should allow you to do this.

Change it from:

```<code>@query_result_no_padding = 0
</code>```

to

```<code>@query_result_no_padding = 1
</code>```

[ @query_result_no_padding ] @query_result_no_padding The type is bit.
  The default is 0. When you set to 1, the query results are not padded,
  possibly reducing the file size.If you set @query_result_no_padding to
  1 and you set the @query_result_width parameter, the
  @query_result_no_padding parameter overwrites the @query_result_width
  parameter. + In this case no error occurs. If you set the
  @query_result_no_padding to 1 and you set the @query_no_truncate
  parameter, an error is raised.

Source: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql

Title: Remove extra spaces in sp_send_dbmail

Body:
I have the following table:

CREATE TABLE [dbo].[MyTable](
    [Day_ID] [nvarchar](50) NULL,
    [SAS] [nvarchar](50) NULL,
    [STAMP] [datetime] NULL DEFAULT (getdate())
)

which contains this data:

'2017_12_06_01','Red'

'2017_12_06_02','Yellow'

'2017_12_06_03','Green'

'2017_12_06_04','Blue'

I also have a SP which read all the data from MyTable and send it in the body of an e-mail message.

SET NOCOUNT ON;

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'MyMailProfile'
        ,@recipients = 'me@account.com'
        ,@subject = 'This is the object'
        ,@body = 'This is the body:'
        ,@body_format = 'TEXT'
        ,@query = 'SET NOCOUNT ON select [Day_ID],[SAS] from MyTable SET NOCOUNT OFF'
        ,@attach_query_result_as_file = 0
        ,@query_result_separator = '|'
        ,@exclude_query_output = 1
        ,@query_result_no_padding = 0
        ,@query_result_header = 0
        ,@append_query_error=1

Everything works but my problem is that in the body the results appear like these:

2017_12_06_01                                   |Red
2017_12_06_02                                   |Yellow
2017_12_06_03                                   |Green
2017_12_06_04                                   |Blue

In other words SQL Server know that the columns could be 50 characters long so they fill the space that doesn't contain characters with spaces. This is very boring if you consider that happen also if you write numeric values into a column, for example, NUMERIC.
I've tried with LTRIM and RTRIM but nothing changed.

I am using SQL Server 2005.

Body:
The parameter @query_result_no_padding should allow you to do this.

Change it from:

@query_result_no_padding = 0

to

@query_result_no_padding = 1

[ @query_result_no_padding ] @query_result_no_padding The type is bit.
  The default is 0. When you set to 1, the query results are not padded,
  possibly reducing the file size.If you set @query_result_no_padding to
  1 and you set the @query_result_width parameter, the
  @query_result_no_padding parameter overwrites the @query_result_width
  parameter. + In this case no error occurs. If you set the
  @query_result_no_padding to 1 and you set the @query_no_truncate
  parameter, an error is raised.

Source: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql


问:
Why does some files not show up in Eclipse?
I started Eclipse and opened a project that is in a Git repo. However, a folder with some files does not show. Why is that?

The files are committed, and I am on the right branch so it is not that.

```<code>$ git status
On branch feat57
nothing to commit, working tree clean
</code>```

The files exists:

```<code>$ ls -d html/catalogue/*/
html/catalogue/article/  html/catalogue/backup/  html/catalogue/projects/  html/catalogue/reports/
$ ls html/catalogue/projects/
projects_edit.php  projects_list.php  projects_new.php  projects.php  projects_view.php
</code>```

Apache finds the files when I access it through a browser.

Two icons seems to show that something is wrong. However, I don't know what they mean.

As you can see, there's something fishy with folders html and catalogue. The folder that is not showing is in catalogue. You can also see that projects does not show.

答:
I guess you are locking at your project from the "Package Explorer" view. This is a special view that doesn't represent the file system. It focuses on source and ressource folders, which you can identify by the little brownish symbol inside the "folder" icon. I suspect your catalogue folder is excluded from the build path somehow.

If it's not, try refreshing the project (mark the project and hit F5).

Finally, if you want a view showing the file system, go to Window->Show View->Navigator.

Body:
I started Eclipse and opened a project that is in a Git repo. However, a folder with some files does not show. Why is that?

The files are committed, and I am on the right branch so it is not that.

$ git status
On branch feat57
nothing to commit, working tree clean

The files exists:

$ ls -d html/catalogue/*/
html/catalogue/article/  html/catalogue/backup/  html/catalogue/projects/  html/catalogue/reports/
$ ls html/catalogue/projects/
projects_edit.php  projects_list.php  projects_new.php  projects.php  projects_view.php

Apache finds the files when I access it through a browser.

Two icons seems to show that something is wrong. However, I don't know what they mean.

As you can see, there's something fishy with folders html and catalogue. The folder that is not showing is in catalogue. You can also see that projects does not show.


问:
Adding a new array element to a JSON object
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:

```<code> {"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
</code>```

I want to add a new item to the array, such as

```<code>{"teamId":"4","status":"pending"}
</code>```

to end up with

```<code>{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
</code>```

before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.

答:
First we need to parse the JSON object and then we can add an item.

```<code>var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
</code>```

Finally we JSON.stringify the obj back to JSON

Body:
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:

 {"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}

I want to add a new item to the array, such as

{"teamId":"4","status":"pending"}

to end up with

{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}

before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.

Body:
First we need to parse the JSON object and then we can add an item.

var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);

Finally we JSON.stringify the obj back to JSON


问:
NavigationItem Left and Top not showing
I have a view who is called from a Tab Bar controller where i want to have a leftBarButtonItem, a topItem with the logo and a rightBarButtonItem.

On this first view i succeeded to have the topItem with the logo and the rightBarButtonItem, but impossible to have the leftBarButtonItem, programmatically or dragging it in the storyboard.
And i don't understand why. Here is the code.

```<code>private func setNavBarItems() {

    self.navigationItem.leftBarButtonItem?.image = UIImage(named: "empty-photo-red")

    if let navigationBar = self.navigationController?.navigationBar as? SeetyNavigationBar {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        imageView.contentMode = .ScaleAspectFit
        let image = UIImage(named: "logo-trans")
        imageView.image = image
        navigationBar.topItem?.titleView = imageView
    }

    self.navigationItem.rightBarButtonItem!.image = UIImage(named: "FAQ")
}
</code>```

If i unwrap leftBarButton with "!" the app crash, so i guess there is no leftBarButton, but why ?

And after when i perform the segue from this view to the next one, i got the leftBarButtonItem and the rightBarButtonItem and the topItem with the logo disappear. I use the same function that i call in my viewDidLoad()

EDIT: For my topItem who was disappearing: self.navigationItem.titleView = imageView
 and not navigationBar.topItem?.titleView = imageView solved the problem.

答:
Swift 4.0

```<code>let btnBack = UIButton(type: .custom)
btnBack.bounds = CGRect(x: 0, y: 0, width: 44, height: 44)
btnBack.addTarget(self, action: #selector(self.backButtonAction(sender:)), for: .touchUpInside)
btnBack.setImage(#imageLiteral(resourceName: "back_image"), for: .normal)

let leftBarButton = UIBarButtonItem(customView: btnBack)
self.navigationItem.setLeftBarButton(leftBarButton, animated: true)
</code>```

// Back Button Action

```<code>@objc func backButtonAction(sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
</code>```

Title: NavigationItem Left and Top not showing

Body:
I have a view who is called from a Tab Bar controller where i want to have a leftBarButtonItem, a topItem with the logo and a rightBarButtonItem.

On this first view i succeeded to have the topItem with the logo and the rightBarButtonItem, but impossible to have the leftBarButtonItem, programmatically or dragging it in the storyboard.
And i don't understand why. Here is the code.

private func setNavBarItems() {

    self.navigationItem.leftBarButtonItem?.image = UIImage(named: "empty-photo-red")

    if let navigationBar = self.navigationController?.navigationBar as? SeetyNavigationBar {
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        imageView.contentMode = .ScaleAspectFit
        let image = UIImage(named: "logo-trans")
        imageView.image = image
        navigationBar.topItem?.titleView = imageView
    }

    self.navigationItem.rightBarButtonItem!.image = UIImage(named: "FAQ")
}

If i unwrap leftBarButton with "!" the app crash, so i guess there is no leftBarButton, but why ?

And after when i perform the segue from this view to the next one, i got the leftBarButtonItem and the rightBarButtonItem and the topItem with the logo disappear. I use the same function that i call in my viewDidLoad()

EDIT: For my topItem who was disappearing: self.navigationItem.titleView = imageView
 and not navigationBar.topItem?.titleView = imageView solved the problem.

Body:
Swift 4.0

let btnBack = UIButton(type: .custom)
btnBack.bounds = CGRect(x: 0, y: 0, width: 44, height: 44)
btnBack.addTarget(self, action: #selector(self.backButtonAction(sender:)), for: .touchUpInside)
btnBack.setImage(#imageLiteral(resourceName: "back_image"), for: .normal)

let leftBarButton = UIBarButtonItem(customView: btnBack)
self.navigationItem.setLeftBarButton(leftBarButton, animated: true)

// Back Button Action

@objc func backButtonAction(sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}


问:
Swapping information between ActionScript and Lingo
I have a lingo script which runs some data processing for a Flash movie. I can call my Lingo functions from Flash by putting the following inside one of my methods:

```<code>getURL("Lingo: myMethod");
</code>```

and I can pass parameters from flash to lingo as follows:

```<code>getURL("Lingo: myMethod param");
</code>```

However, if myMethod returns a value, I can't seem to send it back to ActionScript. How do I code the following:

```<code>var myVar = getURL("Lingo: myMethod");
</code>```

where myMethod is defined as:

```<code>on myMethod
    --do something
    return 5
end myMethod
</code>```

We are using Flash 9 with CS 3.

答:
@wulong:
the package is flash.external., not flash.system.

OwnerDisplayName: Elie

Body:
I have a lingo script which runs some data processing for a Flash movie. I can call my Lingo functions from Flash by putting the following inside one of my methods:

getURL("Lingo: myMethod");

and I can pass parameters from flash to lingo as follows:

getURL("Lingo: myMethod param");

However, if myMethod returns a value, I can't seem to send it back to ActionScript. How do I code the following:

var myVar = getURL("Lingo: myMethod");

where myMethod is defined as:

on myMethod
    --do something
    return 5
end myMethod

We are using Flash 9 with CS 3.

LastEditorDisplayName: Elie

OwnerDisplayName: vyger

LastEditorDisplayName: vyger


问:
Custom view with button like behavior on click/touch
I have created a custom View which I usually attach an onClickListener to. I'd like to have some button like behavior: if it is pressed, it should alter its appearance which is defined in the onDraw() method. However, this code does not work:

```<code>//In my custom View:

@Override
protected void onDraw(Canvas canvas)
{

    boolean pressed = isPressed();
    //draw depending on the value of pressed
}

//when creating the view:
MyView.setClickable(true);
</code>```

pressed always has the value false. What's wrong?

Thanks a lot!

答: have you considered just using a button to do what you want?  you could use ToggleButton and write a short selector in xml that will allow you to specify an image to use when pressed or not. this question may be of some help to you.</p>

Body:
I have created a custom View which I usually attach an onClickListener to. I'd like to have some button like behavior: if it is pressed, it should alter its appearance which is defined in the onDraw() method. However, this code does not work:

//In my custom View:

@Override
protected void onDraw(Canvas canvas)
{

    boolean pressed = isPressed();
    //draw depending on the value of pressed
}

//when creating the view:
MyView.setClickable(true);

pressed always has the value false. What's wrong?

Thanks a lot!


问:
wdPasteText pasting as image on Word
I am very close to finally completing this code I have been working on but I have hit a bit of a snag. I  need the selected to be pasted as plain text onto a word document, however, with my current code, it pastes the selected as an image.

```<code>Sub CopyRangeToWord()
 Dim objWord
 Dim objDoc

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add

Sheets("Executive Outline").Range("B5:B220").Select
Selection.Copy

With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteText, _
    Placement:=wdInLine, DisplayAsIcon:=False
End With
objWord.Visible = True
End Sub
</code>```

Can someone please let me know where I am going wrong? I would greatly appreciate it.

答:
The solution here is to use this code:

```<code>.Selection.PasteSpecial Link:=False, DataType:=2, _
    Placement:=wdInLine, DisplayAsIcon:=False
</code>```

Short explanation...:

You are working with Late Bindings and without Option Explicit statement. Therefore all MS Word constants like wdPasteText, wdInLine are considered as variables with not declared values. Therefore you have 0 for both constants. Solutions:

use early binding to keep text constants

always use Option Explicit to avoid such problems

for late binding always use numeric values instead of text constants.

Title: wdPasteText pasting as image on Word

Body:
I am very close to finally completing this code I have been working on but I have hit a bit of a snag. I  need the selected to be pasted as plain text onto a word document, however, with my current code, it pastes the selected as an image.

Sub CopyRangeToWord()
 Dim objWord
 Dim objDoc

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add

Sheets("Executive Outline").Range("B5:B220").Select
Selection.Copy

With objWord
    .Selection.PasteSpecial Link:=False, DataType:=wdPasteText, _
    Placement:=wdInLine, DisplayAsIcon:=False
End With
objWord.Visible = True
End Sub

Can someone please let me know where I am going wrong? I would greatly appreciate it.

Body:
The solution here is to use this code:

.Selection.PasteSpecial Link:=False, DataType:=2, _
    Placement:=wdInLine, DisplayAsIcon:=False

Short explanation...:

You are working with Late Bindings and without Option Explicit statement. Therefore all MS Word constants like wdPasteText, wdInLine are considered as variables with not declared values. Therefore you have 0 for both constants. Solutions:

use early binding to keep text constants

always use Option Explicit to avoid such problems

for late binding always use numeric values instead of text constants.


问:
first character in the input should be letter
I have an input type element that should have 5 characters starting with a letter </p>

```<code>  <input mdInput #acronyme placeholder="Company" type="text" maxlength="5" minlength="5" required [value]="acronyme.value.toUpperCase()">
</code>```

<p>My problem is with with the starting character that should be a letter because i want to prevent the input from writing any number in the starting character </p>

答:
It is an angular form, you can use model driven form and put a pattern property for the same, for an example

```<code>pattern="[a-zA-Z ][0-9]+"
</code>```

this will ensure that you will have a varchar for that field, which will start with a letter.

Body:
I have an input type element that should have 5 characters starting with a letter

  <input mdInput #acronyme placeholder="Company" type="text" maxlength="5" minlength="5" required [value]="acronyme.value.toUpperCase()">

My problem is with with the starting character that should be a letter because i want to prevent the input from writing any number in the starting character

Body:
It is an angular form, you can use model driven form and put a pattern property for the same, for an example

pattern="[a-zA-Z ][0-9]+"

this will ensure that you will have a varchar for that field, which will start with a letter.


问:
Selective role based module loading
I wanted to know if there is any way to selectively load module based on roles.

e.g:-
There are three groups of users namely- admin, biller and end-user. Based on their role, they will be authorized to use certain feature. The app is split into three modules based on same user groups with one common module shared by all of them.
Based on login, is it possible to selectively load only the module required for that particular user?

Note:- routing path is same for all, like /home, /dashboard, /sales etc

Adding a point:
In the above scenario, assume, I have generated four files- admin.chunk.js, biller.chunk.js, end-user.chunk.js and common module will be eagerly loaded with app js.
Based on the user logging in, from the backend, I am selectively sending the js suitable for that logged in user. Now paths for all the components are same, except the part that admin will have access to couple of modules more than end-user. How to manage routing in this case...?

答:
Guards?

Basically, implement CanActivate guard and use it.

```<code>import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { AuthService }    from './somewhere';

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private authService: AuthService) {}
  canActivate() {
    if (this.authService.isAuthenticated() && this.authService.isAdmin()) {
      console.log('You are admin, go through!');
      return true;
    }
    return false;
  }
}
</code>```

Then in your router:

```<code>const routes: Routes = [
  { path: 'peasants', component: PeasantComponent },
  { path: 'kings', component: PeasantComponent, canActivate: [AdminGuard] },
]
</code>```

Edit: You wanted to load a module based on this. Well, the same:

```<code>const routes: Routes = [
  { path: 'peasants', component: PeasantComponent },
  { path: 'kings', loadChildren: 'some/path/to/admin.module', canActivate: [AdminGuard] },
]
</code>```

Title: Selective role based module loading

Body:
Guards?

Basically, implement CanActivate guard and use it.

import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';
import { AuthService }    from './somewhere';

@Injectable()
export class AdminGuard implements CanActivate {
  constructor(private authService: AuthService) {}
  canActivate() {
    if (this.authService.isAuthenticated() && this.authService.isAdmin()) {
      console.log('You are admin, go through!');
      return true;
    }
    return false;
  }
}

Then in your router:

const routes: Routes = [
  { path: 'peasants', component: PeasantComponent },
  { path: 'kings', component: PeasantComponent, canActivate: [AdminGuard] },
]

Edit: You wanted to load a module based on this. Well, the same:

const routes: Routes = [
  { path: 'peasants', component: PeasantComponent },
  { path: 'kings', loadChildren: 'some/path/to/admin.module', canActivate: [AdminGuard] },
]