问:
How to access file metadata, for files in google cloud storage, from a python google cloud function
I'm trying to access the custom metadata on a file in Google cloud storage from within a Cloud Function, but it always returns "None".

The file definitely has custom metadata on it - the custom metadata can be seen from the GCS browser.

I can access the custom metadata successfully if I run my code in a cloud shell environment.

But if I run the same code in a cloud function, then the returned blob.metadata is always "None".

What am I doing wrong?  What do I have to do differently in a Cloud Function compared to a Cloud Shell.

```<code>from google.cloud import storage
client = storage.Client()
bucket = client.bucket(<my bucket name>)
blob = bucket.get_blob(<my filename>)
metadata = blob.metadata
</code>```

Note also that blob.download_as_string() gets me the file contents correctly - it's just the custom metadata I can't get.

答:
blob.metadata only returns Storage object's custom metadata (a dict). None means that there is no custom metadata. See the docs of metadata :

Retrieve arbitrary/application specific metadata for the object.

The documentation of Object resource (API) specify that metadata is :

User-provided metadata, in key/value pairs.

Note that custom metadata is different from fixed-key metadata, that you can also edit with Edit metadata button in Google Cloud Console. Fixed-key metadata contains :

Content-Type

Content-Encoding

Content-Disposition

Content-Language

Cache-Control

This particular kind of metadata can be accessed via blob.content_type, blob.content_encoding, ... (check a complete example).

To add custom metadata, just click Add item button on the same window (Edit metadata) or use gsutil (see Editing object metadata docs) :

```<code>gsutil setmeta -h "x-goog-meta-examplekey:examplevalue" gs://<your-bucket>
</code>```

Body:
I'm trying to access the custom metadata on a file in Google cloud storage from within a Cloud Function, but it always returns "None".

The file definitely has custom metadata on it - the custom metadata can be seen from the GCS browser.

I can access the custom metadata successfully if I run my code in a cloud shell environment.

But if I run the same code in a cloud function, then the returned blob.metadata is always "None".

What am I doing wrong?  What do I have to do differently in a Cloud Function compared to a Cloud Shell.

from google.cloud import storage
client = storage.Client()
bucket = client.bucket(<my bucket name>)
blob = bucket.get_blob(<my filename>)
metadata = blob.metadata

Note also that blob.download_as_string() gets me the file contents correctly - it's just the custom metadata I can't get.

Body:
blob.metadata only returns Storage object's custom metadata (a dict). None means that there is no custom metadata. See the docs of metadata :

Retrieve arbitrary/application specific metadata for the object.

The documentation of Object resource (API) specify that metadata is :

User-provided metadata, in key/value pairs.

Note that custom metadata is different from fixed-key metadata, that you can also edit with Edit metadata button in Google Cloud Console. Fixed-key metadata contains :

Content-Type

Content-Encoding

Content-Disposition

Content-Language

Cache-Control

This particular kind of metadata can be accessed via blob.content_type, blob.content_encoding, ... (check a complete example).

To add custom metadata, just click Add item button on the same window (Edit metadata) or use gsutil (see Editing object metadata docs) :

gsutil setmeta -h "x-goog-meta-examplekey:examplevalue" gs://<your-bucket>


来源: stackexchange

问:
My webscraper is returning an empty list when im using the correct CSS selector
I am attempting to scrape some data off of this particular url by using selenium or scrapy.

ive scraped other pages without issue, however when it comes to these particular urls the info im trying to scrape into a list is returning empty. I've used scrapy then moved on to using selenium but the result is the same. I'm also using pycharm and chromedriver.

The info im looking for in particular is all the different phone models on 'https://shop.freedommobile.ca/devices'. I print the list only to find out nothing was scraped from the site or rather scrape is successful but nothing was returned.

The same occurs when i try to scrape anything from here as well:

https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786074&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB

```<code>from selenium import webdriver

#open chrome browser and navigate to the webpage
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

#extract the names of the phones
phones = driver.find_elements_by_css_selector('.jXeFbj')

#counts phone and its model
for element in range(len(phones)):
    numPhone = int(element) + 1
    print("phone "+ str(numPhone) +" : " + phones[element].text)

#number of phones in total
sizeOfList = len(phones)
print(sizeOfList)
</code>```

Whats supposed to happen is pull all the model names of the phones into a list.

phones = ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...]

答:
Your code is ok, what might be happenning is that you get an empty list sometimes by sending the request to fast.

You can overcome this issue using WebDriverWait.

Here's code that you can uses will small improvements:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

# get the list of phones
wait = WebDriverWait(driver, 10)
phones = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.jXeFbj')))
numPhones = len(phones)

#prints the formatted output of each phone
for idx, phone in enumerate(phones):
    phone_name = phone.text
    print("phone " + str(idx) + " : " + phone_name)

print(numPhones)
</code>```

Output 1:

```<code>phone 0 : iPhone XS Max
phone 1 : iPhone XS
phone 2 : iPhone XR
phone 3 : iPhone 8 Plus
phone 4 : iPhone 8
phone 5 : Galaxy S10+
...
</code>```

Output 2:

```<code>27
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to scrape some data off of this particular url by using selenium or scrapy.

ive scraped other pages without issue, however when it comes to these particular urls the info im trying to scrape into a list is returning empty. I've used scrapy then moved on to using selenium but the result is the same. I'm also using pycharm and chromedriver.

The info im looking for in particular is all the different phone models on 'https://shop.freedommobile.ca/devices'. I print the list only to find out nothing was scraped from the site or rather scrape is successful but nothing was returned.

The same occurs when i try to scrape anything from here as well:

https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786074&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB

from selenium import webdriver

#open chrome browser and navigate to the webpage
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

#extract the names of the phones
phones = driver.find_elements_by_css_selector('.jXeFbj')

#counts phone and its model
for element in range(len(phones)):
    numPhone = int(element) + 1
    print("phone "+ str(numPhone) +" : " + phones[element].text)

#number of phones in total
sizeOfList = len(phones)
print(sizeOfList)

Whats supposed to happen is pull all the model names of the phones into a list.

phones = ['iPhone XS Max', 'iPhone XS', 'iPhone XR',...]

Body:
Your code is ok, what might be happenning is that you get an empty list sometimes by sending the request to fast.

You can overcome this issue using WebDriverWait.

Here's code that you can uses will small improvements:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://shop.freedommobile.ca/devices")

# get the list of phones
wait = WebDriverWait(driver, 10)
phones = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.jXeFbj')))
numPhones = len(phones)

#prints the formatted output of each phone
for idx, phone in enumerate(phones):
    phone_name = phone.text
    print("phone " + str(idx) + " : " + phone_name)

print(numPhones)

Output 1:

phone 0 : iPhone XS Max
phone 1 : iPhone XS
phone 2 : iPhone XR
phone 3 : iPhone 8 Plus
phone 4 : iPhone 8
phone 5 : Galaxy S10+
...

Output 2:

27


问:
Return Count Value back as 0 if emtpy or none
I am running the following query in our database and I am trying to get the count value back as 0 if none are present, but having problems doing so. Could someone help assist and explain how to accomplish this

```<code>select state, count(phone_number) from VOIP_PHONE_NUMBER_POOL
where status = 3
group by state
order by state asc;
</code>```

For example, currently my query is returning something back like this

```<code>State  Count

AZ     25
</code>```

When I want it to return the empty values and look like this

```<code>State  Count

AZ     25
CA     0
</code>```

答:
If there are no rows in the fact table (VOIP_PHONE_NUMBER_POOL) with a particular state, you will not get such a result from only querying that table.

You will need to join your fact table to a dimension table (a table with all possible states) in order to get the desired counts.

For example, assuming you have such a dimension table and it is named "state_info":

```<code>         SELECT s.state,
                COUNT(v.phone_number) AS phone_number_count
           FROM state_info s
LEFT OUTER JOIN voip_phone_number_pool v
                ON s.state = v.state
       GROUP BY s.state;
</code>```

Body:
I am running the following query in our database and I am trying to get the count value back as 0 if none are present, but having problems doing so. Could someone help assist and explain how to accomplish this

select state, count(phone_number) from VOIP_PHONE_NUMBER_POOL
where status = 3
group by state
order by state asc;

For example, currently my query is returning something back like this

State  Count

AZ     25

When I want it to return the empty values and look like this

State  Count

AZ     25
CA     0

Body:
If there are no rows in the fact table (VOIP_PHONE_NUMBER_POOL) with a particular state, you will not get such a result from only querying that table.

You will need to join your fact table to a dimension table (a table with all possible states) in order to get the desired counts.

For example, assuming you have such a dimension table and it is named "state_info":

         SELECT s.state,
                COUNT(v.phone_number) AS phone_number_count
           FROM state_info s
LEFT OUTER JOIN voip_phone_number_pool v
                ON s.state = v.state
       GROUP BY s.state;


问:
How to prevent HTML5 form validation on non-submit button?
A form with reset and submit buttons, but both are causing HTML5 validation.  When the user clicks reset, I just want the fields cleared.  Assuming this is default action for any form button, and not just submit, how do I prevent the default action, but still run the custom action?

```<code><button data-ng-click="reset()">Reset Form</button>
<input type="submit" data-ng-click="main.$valid && post('Check')" class="submitbtn" value="Submit" />
</code>```

答:
Set its type attribute this way:</p>

```<code><button type="button">Reset Form</button>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A form with reset and submit buttons, but both are causing HTML5 validation.  When the user clicks reset, I just want the fields cleared.  Assuming this is default action for any form button, and not just submit, how do I prevent the default action, but still run the custom action?

<button data-ng-click="reset()">Reset Form</button>
<input type="submit" data-ng-click="main.$valid && post('Check')" class="submitbtn" value="Submit" />

Body:
Set its type attribute this way:

<button type="button">Reset Form</button>


问:
Look for the resource to match a key word
Suppose I have two kineses, I'd like to get the one of them with the key word _consumer.

```<code>variable "kinesis" {
  default = ["kinesis_publisher", "kinesis_consumer"]
}

resource "aws_kinesis_stream" "test_stream" {
  count = "${length(var.kinesis)}"
  name             = "${var.kinesis[count.index]}"
  shard_count      = 1
  retention_period = 48

  shard_level_metrics = [
    "IncomingBytes",
    "OutgoingBytes",
  ]

  tags = {
    Environment = "test"
  }
}
</code>```

How do I get consumer arn only?

```<code>output "kinesis_consumer_arn" {
  value = "??? lookup or matchkeys with _consumer ???"
}
</code>```

It is not always the same sequence and will be many kinesis. So I can't use 0 or 1 directly.

答:
You may create modules for each kafka stream , thereby giving more control on variables passed into and derived from the resources.

```<code>module "kinesis_publisher" {

    source          = "../modules/test_stream"
    stream_name     = "kinesis_publisher"
    }

module "kinesis_consumer" {

    source          = "../modules/test_stream"
    stream_name     = "kinesis_consumer"
    }
</code>```

And then output can be filtered on basis of modules.

```<code>output "kinesis_consumer_arn" {
  value = "{module.kinesis_consumer.arn}"
}
</code>```

Body:
Suppose I have two kineses, I'd like to get the one of them with the key word _consumer.

variable "kinesis" {
  default = ["kinesis_publisher", "kinesis_consumer"]
}

resource "aws_kinesis_stream" "test_stream" {
  count = "${length(var.kinesis)}"
  name             = "${var.kinesis[count.index]}"
  shard_count      = 1
  retention_period = 48

  shard_level_metrics = [
    "IncomingBytes",
    "OutgoingBytes",
  ]

  tags = {
    Environment = "test"
  }
}

How do I get consumer arn only?

output "kinesis_consumer_arn" {
  value = "??? lookup or matchkeys with _consumer ???"
}

It is not always the same sequence and will be many kinesis. So I can't use 0 or 1 directly.

Body:
You may create modules for each kafka stream , thereby giving more control on variables passed into and derived from the resources.

module "kinesis_publisher" {

    source          = "../modules/test_stream"
    stream_name     = "kinesis_publisher"
    }

module "kinesis_consumer" {

    source          = "../modules/test_stream"
    stream_name     = "kinesis_consumer"
    }

And then output can be filtered on basis of modules.

output "kinesis_consumer_arn" {
  value = "{module.kinesis_consumer.arn}"
}


问:
Chrome Update 73 - Materialize CSS JS trigger error
After the latest Chrome Update 73, the date pickers, time pickers and dropdowns for Materialize CSS 0.100.2 isn't working anymore, it flickers when you click on it and then disappears.

Any idea how to fix this?

答:
I had the same problem. Although I am using angular2-materialize, I believe this should work for people using materialize directly.

The solution that worked for me was to wrap the materialize select input with a div that has a click listener that simply calls event.stopPropagation():

```<code><div (click)="$event.stopPropagation()">
    <select materialize="material_select" [value]="selectValue" formControlName="someControl">
    // options omitted (not relevant to answer)
    </select>
</div>
</code>```

I hope this helps some people.

Body:
I had the same problem. Although I am using angular2-materialize, I believe this should work for people using materialize directly.

The solution that worked for me was to wrap the materialize select input with a div that has a click listener that simply calls event.stopPropagation():

<div (click)="$event.stopPropagation()">
    <select materialize="material_select" [value]="selectValue" formControlName="someControl">
    // options omitted (not relevant to answer)
    </select>
</div>

I hope this helps some people.


问:
R - aggregated data.table columns differently
I am given a large data-table that needs to be aggregated according to the first column:

The problem is the following:

For several columns, one just has to form the sum for each category (given in column 1)

For other columns, one has to calculate the mean

There is a 1-1 correspondence between the entries in the first and second columns. Such that the entries of the second column should be kept.

The following is a possible example of such a data-table. Let's assume that columns 3-9 need to be summed up and columns 10-12 need to be averaged.

```<code>library(data.table)
set.seed(1)
a<-matrix(c("cat1","text1","cat2","text2","cat3","text3"),nrow=3,byrow=TRUE)
M<-do.call(rbind, replicate(1000, a, simplify=FALSE)) # where m is your matrix
M<-cbind(M,matrix(sample(c(1:100),3000*10,replace=TRUE ),ncol=10))
M <- as.data.table(M)
</code>```

The result should be a table of the form

```<code>     V1    V2 V3 V4 V5  V6 V7 V8 V9 V10 V11 V12
1: cat1 text1 27 81 78  95 27 22 12  76  18  76
2: cat2 text2 38 48 70 100 11 97  8  53  56  33
3: cat3 text3 58 18 66  24 14 73 18  27  92  70
</code>```

but with entries the corresponding sums respective averages.

Body:
I am given a large data-table that needs to be aggregated according to the first column:

The problem is the following:

For several columns, one just has to form the sum for each category (given in column 1)

For other columns, one has to calculate the mean

There is a 1-1 correspondence between the entries in the first and second columns. Such that the entries of the second column should be kept.

The following is a possible example of such a data-table. Let's assume that columns 3-9 need to be summed up and columns 10-12 need to be averaged.

library(data.table)
set.seed(1)
a<-matrix(c("cat1","text1","cat2","text2","cat3","text3"),nrow=3,byrow=TRUE)
M<-do.call(rbind, replicate(1000, a, simplify=FALSE)) # where m is your matrix
M<-cbind(M,matrix(sample(c(1:100),3000*10,replace=TRUE ),ncol=10))
M <- as.data.table(M)

The result should be a table of the form

     V1    V2 V3 V4 V5  V6 V7 V8 V9 V10 V11 V12
1: cat1 text1 27 81 78  95 27 22 12  76  18  76
2: cat2 text2 38 48 70 100 11 97  8  53  56  33
3: cat3 text3 58 18 66  24 14 73 18  27  92  70

but with entries the corresponding sums respective averages.

Body:
M[, names(M)[-c(1,2)] := lapply(.SD, as.numeric),
    .SDcols = names(M)[-c(1,2)]][,
                                  c(lapply(.SD[, ((3:9)-2), with=FALSE], sum),
                                    lapply(.SD[, ((10:12)-2), with=FALSE], mean)),
                                   by = eval(names(M)[c(1,2)])]

#>      V1    V2    V3    V4    V5    V6    V7    V8    V9    V10    V11    V12
#> 1: cat1 text1 51978 49854 48476 49451 49620 49870 50248 50.193 51.516 49.694
#> 2: cat2 text2 50607 50097 50572 50507 48960 51419 48905 49.700 49.631 48.863
#> 3: cat3 text3 51033 50060 49742 50345 51532 51299 50957 50.192 50.227 50.689


问:
Current consumption of the uC on a STM32 Nucleo-64 evaluation board
I want to measure the current consumption of the uC on my STM32 Nucleo-64 evaluation board (NUCLEO-L073RZ). The manual says, that I just have to remove the JP6/IDD jumper and then connect the pins to an ammeter:

But if I just remove the JP6 jumper (no pin connection), the uC is still running (I can still debug/communicate via I2C). I would have expected, that if the JP6 is removed, the uC is no longer powered and therefore not accessible anymore...

Can somebody please explain me, where is my error in reasoning?

Here is the link to the corresponding STM32 Nucleo-64 manual (page 23):

https://www.st.com/content/ccc/resource/technical/document/user_manual/98/2e/fa/4b/e0/82/43/b7/DM00105823.pdf/files/DM00105823.pdf/jcr:content/translations/en.DM00105823.pdf

答: Connecting the USB to the debug port IS powering the MCU through the debug pod. Try removing the 2 ST-LINK jumpers on upper left an inch from the the USB connector. That disconnects the built-in ST-LINK from the MCU. That might remove the power from the debug pod to the MCU.


问:
Relationship with the same table (Many to Many?) - Laravel
In my database I have to save people and the data of people that have a relationship with the first. For example: father, mother, son, daughter, etc

Then the design of the database, I did it in the following way Is a relation many-to-many because, a person have many people related to it.

But I'm not sure if is ok..

```<code>class Person extends Model
{
    protected $fillable = [
        'name',
        'surname',
        'profile_picture'
         .....
    ];

    public function relationships()
    {
        return $this -> belongsToMany(Person::class);
    }
}
</code>```

When I create the relation I create a thirth migration table call person_person to save the ids and a description (father, mother, son, daughter)

it's ok describe the relationship this way?

```<code>    public function relationships()
    {
        return $this -> belongsToMany(Person::class);
    }
</code>```

What should I add to complete successful this relationship?

答:
You'll need to define the table, primary and foreign key, as Laravel likely can't determine this (it'll try, but it probably won't succeed). Something like:

```<code>public function relationships(){
  return $this->belongsToMany(Person::class, "person_person", "id_person", "id_person_related")
  ->withPivot(["parentesco"]);
}
</code>```

or similar. Table name is a bit awkward, consider something else, like 'relationships' or something that conveys more meaning.

See https://laravel.com/docs/5.8/eloquent-relationships#many-to-many for details on how to define additional parameters for belongsToMany()

Body:
In my database I have to save people and the data of people that have a relationship with the first. For example: father, mother, son, daughter, etc

Then the design of the database, I did it in the following way Is a relation many-to-many because, a person have many people related to it.

But I'm not sure if is ok..

class Person extends Model
{
    protected $fillable = [
        'name',
        'surname',
        'profile_picture'
         .....
    ];

    public function relationships()
    {
        return $this -> belongsToMany(Person::class);
    }
}

When I create the relation I create a thirth migration table call person_person to save the ids and a description (father, mother, son, daughter)

it's ok describe the relationship this way?

    public function relationships()
    {
        return $this -> belongsToMany(Person::class);
    }

What should I add to complete successful this relationship?

Body:
You'll need to define the table, primary and foreign key, as Laravel likely can't determine this (it'll try, but it probably won't succeed). Something like:

public function relationships(){
  return $this->belongsToMany(Person::class, "person_person", "id_person", "id_person_related")
  ->withPivot(["parentesco"]);
}

or similar. Table name is a bit awkward, consider something else, like 'relationships' or something that conveys more meaning.

See https://laravel.com/docs/5.8/eloquent-relationships#many-to-many for details on how to define additional parameters for belongsToMany()


问:
What is the best way to handel click-events in MVVM?
What is the best way to handel click-events in MVVM? Are there a best way?

I have found two solutions:

with a relaycommand:

```<code>RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
    get
    {
        return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
                                                                                param => true));
    }
}
</code>```

pro: ?; contra: need workaround with events if i would change ui elements like focus

with attached behaviour:

```<code>public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
{
    return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
}
public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
{
    treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
}
public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
    DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
    new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));
</code>```

pro: you have RoutedEventArgs for changes on the ui; contra: access to other controls?

Right now i use both solutions. The RellayCommand in Buttons (with events for ui updates) and the attached behaviour for a treeview to deselect the treeviewitem if a user clicks.

答:
To me there is no simple answer to this question.
That's the way I see it:

if you have a defined state-change on the VM, expose a RelayCommand which then can be bound to something the triggers it. In 99,9% percent of the cases this is a button/menu-entry. Something where it can be easily used. The cases that are left -> well some workaround might be needed, like calling a method from the view.
So a RelayCommand should imho be used if you are really targeting the VM.

Focus-changes on the other hand are view-related functionality. Imho this has nothing todo with the WM. That means for me it should be implemented in the view. So to me I'd even go for a straight-forward eventhandler that does the job.

hth,
Martin

Body:
What is the best way to handel click-events in MVVM? Are there a best way?

I have found two solutions:

with a relaycommand:

RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
    get
    {
        return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
                                                                                param => true));
    }
}

pro: ?; contra: need workaround with events if i would change ui elements like focus

with attached behaviour:

public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
{
    return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
}
public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
{
    treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
}
public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
    DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
    new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));

pro: you have RoutedEventArgs for changes on the ui; contra: access to other controls?

Right now i use both solutions. The RellayCommand in Buttons (with events for ui updates) and the attached behaviour for a treeview to deselect the treeviewitem if a user clicks.


问:
How to join two tables with many-to-many relation using vlookup in Excel?
I have a data model between three entities (tables):

```<code>Field
Screen
Window
</code>```

Window-Screen has many-to-many relationship. So, I defined a join table Screen_Window with foreign keys to both tables.

Screen-Field has one-to-many relationship. So, each Screen has many Fields. But each Field belongs to one Screen record.

Now, I want to build a report that will join Fields to their corresponding Windows.

A sample data from Screen_Window:

```<code>(column A) (column B)
screen_id  window_id
s1         w1
s2         w1
s1         w2
</code>```

The expected report should be like that:

```<code>(column D) (column E) (column F)
field_id   screen_id  window_id
f1         s1         w1
f1         s1         w2
</code>```

I use the VLOOKUP function in column F in order to produce this report:

```<code>=VLOOKUP(E2;A2:B4;2)
</code>```

The result is the following:

```<code>(column D) (column E) (column F)
field_id   screen_id  window_id
f1         s1         w1
</code>```

So, VLOOKUP ignores the w2 record:

```<code>f1         s1         w2
</code>```

How can I produce the expected report automatically in Excel?

答:
The VLOOKUP() formula can't make it but you can still use excel to work with it using the following array formula:

```<code>{=+INDEX($B$2:$B$12,SMALL(IF(E2=$A$2:$A$12,ROW($A$2:$A$12)-ROW($A$2)+1),COUNTIF($E$2:E2,E2)))}
</code>```

In order to make the formula an array formula you have to use "Ctrl + Shift + Enter" keys together instead of "Enter" only.

I tried in an example and works:

Body:
I have a data model between three entities (tables):

Field
Screen
Window

Window-Screen has many-to-many relationship. So, I defined a join table Screen_Window with foreign keys to both tables.

Screen-Field has one-to-many relationship. So, each Screen has many Fields. But each Field belongs to one Screen record.

Now, I want to build a report that will join Fields to their corresponding Windows.

A sample data from Screen_Window:

(column A) (column B)
screen_id  window_id
s1         w1
s2         w1
s1         w2

The expected report should be like that:

(column D) (column E) (column F)
field_id   screen_id  window_id
f1         s1         w1
f1         s1         w2

I use the VLOOKUP function in column F in order to produce this report:

=VLOOKUP(E2;A2:B4;2)

The result is the following:

(column D) (column E) (column F)
field_id   screen_id  window_id
f1         s1         w1

So, VLOOKUP ignores the w2 record:

f1         s1         w2

How can I produce the expected report automatically in Excel?

Body:
The VLOOKUP() formula can't make it but you can still use excel to work with it using the following array formula:

{=+INDEX($B$2:$B$12,SMALL(IF(E2=$A$2:$A$12,ROW($A$2:$A$12)-ROW($A$2)+1),COUNTIF($E$2:E2,E2)))}

In order to make the formula an array formula you have to use "Ctrl + Shift + Enter" keys together instead of "Enter" only.

I tried in an example and works:


问:
Calling non static method without class instance inside a non static method
```<code>class GFG {
public static void main (String[] args) {
    GFG g=new GFG();
    g.pri();

}

void pri(){
  mod();
}
void mod()
{
    System.out.println("HHI");
}

}
</code>```

In this following code when i am calling a  mod() method inside a non static method without creating class instance for mod() method it does work and given Output "Hi";
According to the definition of non static method cannot be called without Class instance;

How it does work?

答:
```<code>class GFG {
    public static void main (String[] args) {
        GFG g=new GFG();
        g.pri();
    }
}
</code>```

It works, because you call non-static pri() method of instance of GFC.

```<code>class GFG {
    public static void main (String[] args) {
        pri();
    }
}
</code>```

will fails, because you call non-static pri() from static main()

Body:
class GFG {
public static void main (String[] args) {
    GFG g=new GFG();
    g.pri();

}

void pri(){
  mod();
}
void mod()
{
    System.out.println("HHI");
}

}

In this following code when i am calling a  mod() method inside a non static method without creating class instance for mod() method it does work and given Output "Hi";
According to the definition of non static method cannot be called without Class instance;

How it does work?

Body:
class GFG {
    public static void main (String[] args) {
        GFG g=new GFG();
        g.pri();
    }
}

It works, because you call non-static pri() method of instance of GFC.

class GFG {
    public static void main (String[] args) {
        pri();
    }
}

will fails, because you call non-static pri() from static main()


问:
How to properly pass a string with blanks as separate command line arguments?
For example, if I want to rename the file old_name new_name, I can use the following code:

args='old_name new_name'
mv $args
```

<p>However, if the original filename is <code>old name</code>, neither of the following code is able to work as intended:</p>

<pre class="lang-sh prettyprint-override"><code>args='"old name" new_name'
mv $args
# mv: target 'new_name' is not a directory
</code>```

args='old\ name new_name'
mv $args
# mv: target 'new_name' is not a directory
```

new_name is recognized as the third arguments. It seems that characters like " and \ lose their special meanings after expanded from a string.

How to properly pass a string with blanks as separate command line arguments? In this case, is there a way to specify that old and name should be grouped together?

Thanks!

答:
Arrays were added to the language precisely to address this use case (not as a general-purpose container):</p>

```<code>args=("old name" "new name")
mv "${args[@]}"
</code>```

Body:
For example, if I want to rename the file old_name new_name, I can use the following code:

args='old_name new_name'
mv $args

However, if the original filename is old name, neither of the following code is able to work as intended:

args='"old name" new_name'
mv $args
# mv: target 'new_name' is not a directory

args='old\ name new_name'
mv $args
# mv: target 'new_name' is not a directory

new_name is recognized as the third arguments. It seems that characters like " and \ lose their special meanings after expanded from a string.

How to properly pass a string with blanks as separate command line arguments? In this case, is there a way to specify that old and name should be grouped together?

Thanks!

Body:
Arrays were added to the language precisely to address this use case (not as a general-purpose container):

args=("old name" "new name")
mv "${args[@]}"


问:
Configure makefile for debug and release targets
Considering a Makefile similar to the following:

```<code>CC = gcc
CXX = g++
CXXFLAGS += -std=c++11

SRCDIR = .
OBJECTS = \
    file1.o \
    file2.o \
    file3.o
THREADS = 1

all: release

release: CXXFLAGS += -DNUM_THREADS=$(THREADS)
release: main

debug: CXXFLAGS += -g -DDEBUG -DVERBOSENESS=3 -DNUM_THREADS=$(THREADS)
debug: main

# Build main executable...
main: $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $@ $^

# Compile all object files...
file1.o: $(SRCDIR)/file1.cpp
    $(CXX) $(CXXFLAGS) -c $^
file2.o: $(SRCDIR)/file2.cpp
    $(CXX) $(CXXFLAGS) -c $^
file3.o: $(SRCDIR)/file3.cpp
    $(CXX) $(CXXFLAGS) -c $^
</code>```

This works properly only for the first make: using other words, object files are not recompiled when I launch make with a different target respect to the previous one.
That said, how could I make the object files recompile if I change between debug or release target?

答:
If you want to force recompilation strictly based on one label, say "Debug" vs. "Release", then you can do it by writing and depending on appropriate timestamp files, like so:

```<code>TYPE = Debug

#
# ... conditional settings based on $(TYPE) ...
#

OBJS = prog.o

all: test

prog: $(OBJS)
    $(CC) -o $@ $(OBJS)

$(OBJS): $(TYPE)-mode-stamp

$(TYPE)-mode-stamp: last-mode-stamp
    touch $@
    touch -r $@ last-mode-stamp

last-mode-stamp:
    touch $@

clean:
    @rm *-mode-stamp $(OBJS) prog
</code>```

That supposes you select the build type by setting variable $(TYPE), possibly via the command line.  All the object files have $(TYPE)-mode-stamp as a prerequisite, so if that file is out of date then all of them will be rebuilt, along with anything that has any of them as a prerequisite.  $(TYPE)-mode-stamp itself has last-mode-stamp as a prerequisite, so the former is updated if it is older than the latter, or if the latter itself is out of date.  The recipe for $(TYPE)-mode-stamp sets both files timestamps to the current time, so that

$(TYPE)-mode-stamp is no longer out of date with respect to last-mode-stamp, and

last-mode-stamp is newer than any OtherType-mode-stamp that may be present.

A rule without any prerequisites (but with a recipe) creates last-mode-stamp if it does not initially exist.

Note well that this is altogether different from and orthogonal to monitoring whether any build tools or flags change.

Body:
Considering a Makefile similar to the following:

CC = gcc
CXX = g++
CXXFLAGS += -std=c++11

SRCDIR = .
OBJECTS = \
    file1.o \
    file2.o \
    file3.o
THREADS = 1

all: release

release: CXXFLAGS += -DNUM_THREADS=$(THREADS)
release: main

debug: CXXFLAGS += -g -DDEBUG -DVERBOSENESS=3 -DNUM_THREADS=$(THREADS)
debug: main

# Build main executable...
main: $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $@ $^

# Compile all object files...
file1.o: $(SRCDIR)/file1.cpp
    $(CXX) $(CXXFLAGS) -c $^
file2.o: $(SRCDIR)/file2.cpp
    $(CXX) $(CXXFLAGS) -c $^
file3.o: $(SRCDIR)/file3.cpp
    $(CXX) $(CXXFLAGS) -c $^

This works properly only for the first make: using other words, object files are not recompiled when I launch make with a different target respect to the previous one.
That said, how could I make the object files recompile if I change between debug or release target?

Body:
If you want to force recompilation strictly based on one label, say "Debug" vs. "Release", then you can do it by writing and depending on appropriate timestamp files, like so:

TYPE = Debug

#
# ... conditional settings based on $(TYPE) ...
#

OBJS = prog.o

all: test

prog: $(OBJS)
    $(CC) -o $@ $(OBJS)

$(OBJS): $(TYPE)-mode-stamp

$(TYPE)-mode-stamp: last-mode-stamp
    touch $@
    touch -r $@ last-mode-stamp

last-mode-stamp:
    touch $@

clean:
    @rm *-mode-stamp $(OBJS) prog

That supposes you select the build type by setting variable $(TYPE), possibly via the command line.  All the object files have $(TYPE)-mode-stamp as a prerequisite, so if that file is out of date then all of them will be rebuilt, along with anything that has any of them as a prerequisite.  $(TYPE)-mode-stamp itself has last-mode-stamp as a prerequisite, so the former is updated if it is older than the latter, or if the latter itself is out of date.  The recipe for $(TYPE)-mode-stamp sets both files timestamps to the current time, so that

$(TYPE)-mode-stamp is no longer out of date with respect to last-mode-stamp, and

last-mode-stamp is newer than any OtherType-mode-stamp that may be present.

A rule without any prerequisites (but with a recipe) creates last-mode-stamp if it does not initially exist.

Note well that this is altogether different from and orthogonal to monitoring whether any build tools or flags change.


问:
Why doesn't my tank move when I press "a" and "d"?
Currently, I am stuck on trying to get my tank to move when the user presses "a" and "d". The lines involving pressing a key to move the tank seem correct and I believe should work. This is also my first time using one of these forums. Please provide feedback so I can improve. Thank you for your help.

I have asked my teacher and friends for help, but they are all wondering why the tank will not move. I also have searched over the internet and youtube for answers. A weird thing is that my friend and I directly copied a youtube video on user movement where the user can move a rectangle around. My friend can hold down "w","a","s",or "d" to move the rectangle, but I can not hold down "w","a","s",or "d" to move it but need to spam the button. What is weird is that when you move your mouse around, I can then hold down "w","a","s",or "d".

```<code>import pygame
from pygame.locals import *
import math
import random

width = 640
height = 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("2 Player Tanks")

def gameloop():
    pygame.init()
    time = pygame.time.get_ticks()

    screen.fill(white)

    tankx = 100
    tanky = 100
    tankwidth = 40
    tankheight = 20
    turretwidth = 5
    wheelwidth = 5
    tankmove = 5

    def tank(x,y):
        x = int(x)
        y = int(y)
        pygame.draw.circle(screen,black,(x,y),10)
        pygame.draw.rect(screen,black,(x-tankheight,y,tankwidth,tankheight))
        pygame.draw.line(screen,black,(x,y),(x-20,y-20), turretwidth)

        startx = 15
        for i in range(7):
            pygame.draw.circle(screen,black,(x-startx,y+20),wheelwidth)
            startx -= 5

   for event in pygame.event.get():
        if event.type == pygame.QUIT:
           pygame.quit()

        keys= pygame.key.get_pressed()

        if keys[pygame.K_a]:
            tankx -= tankmove
        if keys[pygame.K_d]:
            tankx += tankmove
        if keys[pygame.K_w]:
            tanky -= tankmove
        if keys[pygame.K_s]:
            tanky += tankmove

         tank(tankx,tanky)
         pygame.display.update()

gameloop()
</code>```

I want the player to be able to use "a" and "d" to move the tank horizontally.

答:
The event loop is executed only when an event occurs. This means it is executed when a key is pressed or a key is released — however, when a key is held down, no event occurs and the event loop is not executed.

You've got to evaluate the key presses in the main loop (in scope of gameloop) rather than in the event loop:

e.g.

def gameloop():

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    # <--
    keys= pygame.key.get_pressed()

    if keys[pygame.K_a]:
        tankx -= tankmove
    if keys[pygame.K_d]:
        tankx += tankmove
    if keys[pygame.K_w]:
        tanky -= tankmove
    if keys[pygame.K_s]:
        tanky += tankmove

    tank(tankx,tanky)
    pygame.display.update()
```

<p>Note: <code>pygame.key.get_pressed()</code> returns the current states of the keys and the states are evaluated and updated when <code>pygame.event.get()</code> is called.</p>

<hr>

<p>The position of the tank is reset at the begin of the frame, because the variables  <code>tankx</code> and <code>tanky</code> are set at the begin of <code>gameloop</code>:</p>

<blockquote>
``` def gameloop():
      #[...]

      tankx = 100
      tanky = 100
```
</blockquote>

<p>Define the variables in global scope, and use the <code>global</code> statement to access them.<br>
Decrease the speed of the tank, because it would move very rapidly (<code>tankmove = 1</code>).</p>

<p>The  <code>pygame.init()</code> should be called once only, at the begin of application.</p>

<p>e.g.</p>

<pre class="lang-py prettyprint-override"><code>def gameloop():
    global tankx, tanky, tankmove

    tankwidth = 40
    tankheight = 20
    turretwidth = 5
    wheelwidth = 5

    time = pygame.time.get_ticks()

    screen.fill(white)

    # [...]

pygame.init()

tankx = 100
tanky = 100
tankmove = 1
run = True
while run:
    gameloop()
</code>```

I can move the tank with a randomized background, but the program keeps on drawing a new tank. To fix this, I added a screen.fill(white). That fixes the drawing problem, but now I have no background.

Don't draw the random background to the window. Create a pygame.Surface and draw the random background to the surface.

.blit the background surface to the screen in every frame:

background_surface = pygame.Surface((widht, height))
# draw background to "background_surface" rather then "screen"
# [...]
```

<pre class="lang-py prettyprint-override"><code>def gameloop():

    # [...]

    # blit background instead of screen.fill(white)
    screen.blit(background_surface, (0, 0))

    # [...]
</code>```

Body:
Currently, I am stuck on trying to get my tank to move when the user presses "a" and "d". The lines involving pressing a key to move the tank seem correct and I believe should work. This is also my first time using one of these forums. Please provide feedback so I can improve. Thank you for your help.

I have asked my teacher and friends for help, but they are all wondering why the tank will not move. I also have searched over the internet and youtube for answers. A weird thing is that my friend and I directly copied a youtube video on user movement where the user can move a rectangle around. My friend can hold down "w","a","s",or "d" to move the rectangle, but I can not hold down "w","a","s",or "d" to move it but need to spam the button. What is weird is that when you move your mouse around, I can then hold down "w","a","s",or "d".

import pygame
from pygame.locals import *
import math
import random

width = 640
height = 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("2 Player Tanks")

def gameloop():
    pygame.init()
    time = pygame.time.get_ticks()

    screen.fill(white)

    tankx = 100
    tanky = 100
    tankwidth = 40
    tankheight = 20
    turretwidth = 5
    wheelwidth = 5
    tankmove = 5

    def tank(x,y):
        x = int(x)
        y = int(y)
        pygame.draw.circle(screen,black,(x,y),10)
        pygame.draw.rect(screen,black,(x-tankheight,y,tankwidth,tankheight))
        pygame.draw.line(screen,black,(x,y),(x-20,y-20), turretwidth)

        startx = 15
        for i in range(7):
            pygame.draw.circle(screen,black,(x-startx,y+20),wheelwidth)
            startx -= 5

   for event in pygame.event.get():
        if event.type == pygame.QUIT:
           pygame.quit()

        keys= pygame.key.get_pressed()

        if keys[pygame.K_a]:
            tankx -= tankmove
        if keys[pygame.K_d]:
            tankx += tankmove
        if keys[pygame.K_w]:
            tanky -= tankmove
        if keys[pygame.K_s]:
            tanky += tankmove

         tank(tankx,tanky)
         pygame.display.update()

gameloop()

I want the player to be able to use "a" and "d" to move the tank horizontally.

Body:
The event loop is executed only when an event occurs. This means it is executed when a key is pressed or a key is released — however, when a key is held down, no event occurs and the event loop is not executed.

You've got to evaluate the key presses in the main loop (in scope of gameloop) rather than in the event loop:

e.g.

def gameloop():

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    # <--
    keys= pygame.key.get_pressed()

    if keys[pygame.K_a]:
        tankx -= tankmove
    if keys[pygame.K_d]:
        tankx += tankmove
    if keys[pygame.K_w]:
        tanky -= tankmove
    if keys[pygame.K_s]:
        tanky += tankmove

    tank(tankx,tanky)
    pygame.display.update()

Note: pygame.key.get_pressed() returns the current states of the keys and the states are evaluated and updated when pygame.event.get() is called.

The position of the tank is reset at the begin of the frame, because the variables  tankx and tanky are set at the begin of gameloop:

 def gameloop():
      #[...]

      tankx = 100
      tanky = 100

Define the variables in global scope, and use the global statement to access them.

Decrease the speed of the tank, because it would move very rapidly (tankmove = 1).

The  pygame.init() should be called once only, at the begin of application.

e.g.

def gameloop():
    global tankx, tanky, tankmove

    tankwidth = 40
    tankheight = 20
    turretwidth = 5
    wheelwidth = 5

    time = pygame.time.get_ticks()

    screen.fill(white)

    # [...]

pygame.init()

tankx = 100
tanky = 100
tankmove = 1
run = True
while run:
    gameloop()

I can move the tank with a randomized background, but the program keeps on drawing a new tank. To fix this, I added a screen.fill(white). That fixes the drawing problem, but now I have no background.

Don't draw the random background to the window. Create a pygame.Surface and draw the random background to the surface.

.blit the background surface to the screen in every frame:

background_surface = pygame.Surface((widht, height))
# draw background to "background_surface" rather then "screen"
# [...]

def gameloop():

    # [...]

    # blit background instead of screen.fill(white)
    screen.blit(background_surface, (0, 0))

    # [...]


问:
extracting specific values in R
I am a beginner in R coding and I have the sample data here. I am trying to extract all the entries which have 2 "d7" and one "d1" for identical Idvalue number.

```<code>
Sample   name         Idvalue_number
a       d1                 1
f       d7                 1
b       d7                 1
s       d1                 5
g       d7                 5
r       d7                 5
z       d1                 7
y       d7                 7
d       d1                 7

Expected output
a   d1  1
f   d7  1
b   d7  1
s   d1  5
g   d7  5
r   d7  5

</code>```

Some code I have tried which is not giving me the desired output is here:

```<code>d1d7 <- data_ %>%
  group_by(dvalue_number) %>%
  filter(n() >= 3 & any(name == first(name)))
</code>```

Could someone help me here? Thanks in advance.

答:
An option would be to filter based on the frequency of 'd1', 'd7' in each 'Idvalue_number'

```<code>library(dplyr)
data_ %>%
   group_by(Idvalue_number) %>%
   filter(n() >= 3, sum(name == 'd1') == 1, sum(name == "d7")== 2)
# A tibble: 6 x 3
# Groups:   Idvalue_number [2]
#  Sample name  Idvalue_number
#  <chr>  <chr>          <int>
#1 a      d1                 1
#2 f      d7                 1
#3 b      d7                 1
#4 s      d1                 5
#5 g      d7                 5
#6 r      d7                 5
</code>```

data

```<code>data_ <- structure(list(Sample = c("a", "f", "b", "s", "g", "r", "z",
"y", "d"), name = c("d1", "d7", "d7", "d1", "d7", "d7", "d1",
"d7", "d1"), Idvalue_number = c(1L, 1L, 1L, 5L, 5L, 5L, 7L, 7L,
7L)), class = "data.frame", row.names = c(NA, -9L))
</code>```

Title: extracting specific values in R

Body:
I am a beginner in R coding and I have the sample data here. I am trying to extract all the entries which have 2 "d7" and one "d1" for identical Idvalue number.

Sample   name         Idvalue_number
a       d1                 1
f       d7                 1
b       d7                 1
s       d1                 5
g       d7                 5
r       d7                 5
z       d1                 7
y       d7                 7
d       d1                 7

Expected output
a   d1  1
f   d7  1
b   d7  1
s   d1  5
g   d7  5
r   d7  5

Some code I have tried which is not giving me the desired output is here:

d1d7 <- data_ %>%
  group_by(dvalue_number) %>%
  filter(n() >= 3 & any(name == first(name)))

Could someone help me here? Thanks in advance.

Body:
An option would be to filter based on the frequency of 'd1', 'd7' in each 'Idvalue_number'

library(dplyr)
data_ %>%
   group_by(Idvalue_number) %>%
   filter(n() >= 3, sum(name == 'd1') == 1, sum(name == "d7")== 2)
# A tibble: 6 x 3
# Groups:   Idvalue_number [2]
#  Sample name  Idvalue_number
#  <chr>  <chr>          <int>
#1 a      d1                 1
#2 f      d7                 1
#3 b      d7                 1
#4 s      d1                 5
#5 g      d7                 5
#6 r      d7                 5

data

data_ <- structure(list(Sample = c("a", "f", "b", "s", "g", "r", "z",
"y", "d"), name = c("d1", "d7", "d7", "d1", "d7", "d7", "d1",
"d7", "d1"), Idvalue_number = c(1L, 1L, 1L, 5L, 5L, 5L, 7L, 7L,
7L)), class = "data.frame", row.names = c(NA, -9L))


问:
How to return to app from play directive in alexa app?
I am developing an app for audio streming. if i am saying alexa to play song for this artist, alexa is playing all the song. But is not listening in between to switch to another artist. Alexa is completing all the song for the artist and then stopped then i need to launch the app again to listen to another artist's song. How do i call for another artist in between the song?

here is my coding for the first song

```<code>$speech     = "playing songs of $artistName";

$card = '"card": {
              "type": "Simple",
              "title": "Play Audio",
              "content": ""
        }';
$response = '{
        "version" : "1.0",
        "response" : {
            "outputSpeech": {
              "type": "PlainText",
              "text": "'.$speech.'"
            },
            '.$card.',
            "directives": [
              {
                "type": "AudioPlayer.Play",
                "playBehavior": "REPLACE_ALL",
                "audioItem": {
                  "stream": {
                "token": "FirstSong",
                "url": "myUrl",
                "offsetInMilliseconds": 0
                  }
                }
              }
            ],
            "shouldEndSession" : true
        }
    }';

  echo $response;
</code>```

And then adding the audio to it by replacing playBehaviour to ENQUEUE. Songs are getting added and every song is getting played properly but at any point of time if I am saying any command related to my app.. alexa is not responding and it is actually like getting out of my app because i have to launch the app again once song is playing to make alexa work with my app.

答: You can do this now by using the ASK Music Skill API that allows you to create skills that manage your own music library.</p>

Body:
I am developing an app for audio streming. if i am saying alexa to play song for this artist, alexa is playing all the song. But is not listening in between to switch to another artist. Alexa is completing all the song for the artist and then stopped then i need to launch the app again to listen to another artist's song. How do i call for another artist in between the song?

here is my coding for the first song

$speech     = "playing songs of $artistName";

$card = '"card": {
              "type": "Simple",
              "title": "Play Audio",
              "content": ""
        }';
$response = '{
        "version" : "1.0",
        "response" : {
            "outputSpeech": {
              "type": "PlainText",
              "text": "'.$speech.'"
            },
            '.$card.',
            "directives": [
              {
                "type": "AudioPlayer.Play",
                "playBehavior": "REPLACE_ALL",
                "audioItem": {
                  "stream": {
                "token": "FirstSong",
                "url": "myUrl",
                "offsetInMilliseconds": 0
                  }
                }
              }
            ],
            "shouldEndSession" : true
        }
    }';

  echo $response;

And then adding the audio to it by replacing playBehaviour to ENQUEUE. Songs are getting added and every song is getting played properly but at any point of time if I am saying any command related to my app.. alexa is not responding and it is actually like getting out of my app because i have to launch the app again once song is playing to make alexa work with my app.


问:
Using findOneAndUpdate with varying field values
I am curious to know if there is a better way to go about updating field values. The field values I use sometimes will be there and sometimes will not be, depending on the type of post the user is creating:

Here is my code to bield out the fields that are to be added to the database

```<code>switch (req.body.postType) {
      case "text":
        postFields = {
          postType: "text",
          postBody: req.body.postBody
        };
        break;
      case "video":
        postFields = {
          postType: "video",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          video: {
            ...req.files["postVideo"][0],
            thumbnail: { ...req.files["postVideoThumbnail"][0] }
          }
        };
        break;
      case "photo":
        postFields = {
          postType: "photo",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          photo: {
            ...req.files["postPhoto"][0]
          }
        };
        break;
      case "document":
        postFields = {
          postType: "document",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          document: {
            ...req.files["postDocument"][0]
          }
        };
        break;
      default:
        return res.status(400).json({
          Error:
            "Incorrect postType sent to server. Must be: text, video, photo"
        });
    }
</code>```

After I build this out I then use findOneAndUpdate as follows

```<code> Feed.findOneAndUpdate(
              { school: req.user.school },
              {
                $push: {
                  posts: postFields
                }
              },
              { new: true }
            )
</code>```

Is there a better way to create the field values?

答:
You could do something like this since you already are using ES6:

```<code>let { postType, postBody, postTitle } = req.body  // <-- de-structure
let postFields = {
    postType,
    postBody,
    postTitle,  // <-- no title for text?
    ...(type === 'video' ? { video: {...req.files["postVideo"][0], thumbnail: { ...req.files["postVideoThumbnail"][0]}}} : {}),
    ...(type === 'photo' ? { photo: { ...req.files["postPhoto"][0]}} : {}),
    ...(type === 'document' ? { document: {...req.files["postDocument"][0]}} : {}),
}
</code>```

if text has no title then just use the same approach as the video etc where you use the ternary operator and if type is text just add the title via spreading an object with the title ...

Basically the idea is to use spread with a ternary operator to conditionally decorate an object with properties.

Body:
I am curious to know if there is a better way to go about updating field values. The field values I use sometimes will be there and sometimes will not be, depending on the type of post the user is creating:

Here is my code to bield out the fields that are to be added to the database

switch (req.body.postType) {
      case "text":
        postFields = {
          postType: "text",
          postBody: req.body.postBody
        };
        break;
      case "video":
        postFields = {
          postType: "video",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          video: {
            ...req.files["postVideo"][0],
            thumbnail: { ...req.files["postVideoThumbnail"][0] }
          }
        };
        break;
      case "photo":
        postFields = {
          postType: "photo",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          photo: {
            ...req.files["postPhoto"][0]
          }
        };
        break;
      case "document":
        postFields = {
          postType: "document",
          postTitle: req.body.postTitle,
          postBody: req.body.postBody,
          document: {
            ...req.files["postDocument"][0]
          }
        };
        break;
      default:
        return res.status(400).json({
          Error:
            "Incorrect postType sent to server. Must be: text, video, photo"
        });
    }

After I build this out I then use findOneAndUpdate as follows

 Feed.findOneAndUpdate(
              { school: req.user.school },
              {
                $push: {
                  posts: postFields
                }
              },
              { new: true }
            )

Is there a better way to create the field values?

Body:
You could do something like this since you already are using ES6:

let { postType, postBody, postTitle } = req.body  // <-- de-structure
let postFields = {
    postType,
    postBody,
    postTitle,  // <-- no title for text?
    ...(type === 'video' ? { video: {...req.files["postVideo"][0], thumbnail: { ...req.files["postVideoThumbnail"][0]}}} : {}),
    ...(type === 'photo' ? { photo: { ...req.files["postPhoto"][0]}} : {}),
    ...(type === 'document' ? { document: {...req.files["postDocument"][0]}} : {}),
}

if text has no title then just use the same approach as the video etc where you use the ternary operator and if type is text just add the title via spreading an object with the title ...

Basically the idea is to use spread with a ternary operator to conditionally decorate an object with properties.


问:
No errors shown, but stored procedure will not execute on button click
I have 2 list boxes that store Likes and Dislikes for clients. When an item is selected, there is a button below each respective list box that says "Remove a Like" in one, and "Remove a Dislike" in another. When I click the button for either one, nothing happens. My screen just refreshes. It was working fine for a while, and I have since added a search box that is tied to a stored procedure as well. That is the only major change I have made, though not sure why it would have any affect.

I did remove the search box I had added, but that did not change anything. I changed the auto postback on the buttons to false, and that did not change anything either. I have removed databinds, re added them, nothing seems to get the buttons working.

Here is the "Remove a Like" button. Since the "Remove a Dislike" button is the same, I will not paste that code.

```<code>Protected Sub RemoveLikeBtn_Click(sender As Object, e As EventArgs) Handles RemoveLikeBtn.Click

    Dim connection As New SqlConnection(My.Settings.dbInterests)
    Dim insertProcedure As String = "sp_Delete_ClientInterests"

    Dim insertCommand As New SqlCommand(insertProcedure, connection)
    insertCommand.CommandType = CommandType.StoredProcedure
    insertCommand.Parameters.AddWithValue("@ClientInterestID", LikesLB.SelectedValue)

    Try
        connection.Open()
        insertCommand.ExecuteNonQuery()
    Catch ex As SqlException
        MsgBox("Please select an interest to remove")
    Finally
        connection.Close()
    End Try

    LikesLB.DataBind()
    InterestsLB.DataBind()
    DislikesLB.DataBind()
</code>```

Here is the stored procedure

```<code>CREATE PROCEDURE [dbo].[sp_Delete_ClientInterests]
    (@ClientInterestID INT)
AS
    DELETE FROM ClientInterests
    WHERE ID = @ClientInterestID;
GO
</code>```

And here is the List box it is tied to, plus the button control itself

```<code><div class="col-md-3 bgLightgreen">
    <h5>Individual Likes</h5>
    <telerik:RadListBox ID="LikesLB" runat="server" Height="500px" Width="100%" Sort="Ascending" DataSourceID="dboInterestLikeList" DataTextField="Interest" DataValueField="InterestID" Skin="MetroTouch">
        <ButtonSettings TransferButtons="All"></ButtonSettings>
    </telerik:RadListBox>
    <asp:SqlDataSource ID="dboInterestLikeList" runat="server" ConnectionString="<%$ ConnectionStrings:Interests.My.MySettings.dbInterests %>" SelectCommand="sp_Client_Interest_Likes_List" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="ClientDDL" Name="ClientID" PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>
    <br />
    <br />
    <telerik:RadButton ID="RemoveLikeBtn" runat="server" Text="Remove a Like" BackColor="#CCCCCC"></telerik:RadButton>
</div>
</code>```

答:
I suggest traditional debugging:

Put a breakpoint on RemoveLikeBtn_Click and check, whether LikesLB.SelectedValue returns the expected id.

If yes, try to run the query manually in SQLServer Management Studio and have a look if the according record is deleted.

If not, debug the stored procedure (execute it again step-by-step by pressing F11).

If it only does not work in your application, check the connection string and whether you access the database in the same way (integrated security or sql login and whether there are differences in the rights).

Execute a GRANT EXECUTE ON [dbo].[sp_Delete_ClientInterests] TO PUBLIC and see if it works then.

If yes, REVOKE EXECUTE ON [dbo].[uspLogError] TO PUBLIC again and grant execute to only the roles needed.

Body:
I have 2 list boxes that store Likes and Dislikes for clients. When an item is selected, there is a button below each respective list box that says "Remove a Like" in one, and "Remove a Dislike" in another. When I click the button for either one, nothing happens. My screen just refreshes. It was working fine for a while, and I have since added a search box that is tied to a stored procedure as well. That is the only major change I have made, though not sure why it would have any affect.

I did remove the search box I had added, but that did not change anything. I changed the auto postback on the buttons to false, and that did not change anything either. I have removed databinds, re added them, nothing seems to get the buttons working.

Here is the "Remove a Like" button. Since the "Remove a Dislike" button is the same, I will not paste that code.

Protected Sub RemoveLikeBtn_Click(sender As Object, e As EventArgs) Handles RemoveLikeBtn.Click

    Dim connection As New SqlConnection(My.Settings.dbInterests)
    Dim insertProcedure As String = "sp_Delete_ClientInterests"

    Dim insertCommand As New SqlCommand(insertProcedure, connection)
    insertCommand.CommandType = CommandType.StoredProcedure
    insertCommand.Parameters.AddWithValue("@ClientInterestID", LikesLB.SelectedValue)

    Try
        connection.Open()
        insertCommand.ExecuteNonQuery()
    Catch ex As SqlException
        MsgBox("Please select an interest to remove")
    Finally
        connection.Close()
    End Try

    LikesLB.DataBind()
    InterestsLB.DataBind()
    DislikesLB.DataBind()

Here is the stored procedure

CREATE PROCEDURE [dbo].[sp_Delete_ClientInterests]
    (@ClientInterestID INT)
AS
    DELETE FROM ClientInterests
    WHERE ID = @ClientInterestID;
GO

And here is the List box it is tied to, plus the button control itself

Individual Likes

    <telerik:RadListBox ID="LikesLB" runat="server" Height="500px" Width="100%" Sort="Ascending" DataSourceID="dboInterestLikeList" DataTextField="Interest" DataValueField="InterestID" Skin="MetroTouch">
        <ButtonSettings TransferButtons="All"></ButtonSettings>
    </telerik:RadListBox>
    <asp:SqlDataSource ID="dboInterestLikeList" runat="server" ConnectionString="<%$ ConnectionStrings:Interests.My.MySettings.dbInterests %>" SelectCommand="sp_Client_Interest_Likes_List" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="ClientDDL" Name="ClientID" PropertyName="SelectedValue" Type="Int32" />
        </SelectParameters>
    </asp:SqlDataSource>

    <telerik:RadButton ID="RemoveLikeBtn" runat="server" Text="Remove a Like" BackColor="#CCCCCC"></telerik:RadButton>


问:
how to check if there data range between 2 given dates?
I have start time and end time in my application. I now need to check if there is any time falling between those time in SQL Query.

How do I write the query.

Thanks

答:
This will also work :- </p>

```<code> select * from tablename where time between '7/7/2009 12:35:35' and '7/7/2010 23:35:35'
</code>```

Body:
This will also work :-

 select * from tablename where time between '7/7/2009 12:35:35' and '7/7/2010 23:35:35'


问:
Get a list of key's in HashMap having key like 'some value'
In Mysql we can query a table having clause " WHERE name LIKE '%someName%' ", can we have the same functionality with HashMap in java,if so how can we achieve this more efficiently in a less time by not iterating over each element?

答:
Remove all values which doesn't contain key part:

```<code>yourMap.keySet().removeIf(key -> !key.contains(keyPart));
</code>```

Or regex:

```<code>yourMap.keySet().removeIf(key -> !key.matches(".*keyPart.*"));
</code>```

Body:
Remove all values which doesn't contain key part:

yourMap.keySet().removeIf(key -> !key.contains(keyPart));

Or regex:

yourMap.keySet().removeIf(key -> !key.matches(".*keyPart.*"));


问:
React use route from Express instead of index.html
I have a React application running on port 3000,  I have an express backend running on port 5000.  I would like React to instead of using index.html as the base HTML for the application to instead call port 5000 and use that html (I have a route there, index.html that when I do localhost:5000/index.html responds correctly).  How can I tell React to not look in the public/index.html and instead pull it from the backend?</p>

答:
You can do this with a proxy and CORS.

In your React app in your package.json you can specify

```<code>"proxy": "http://localhost:5000"
</code>```

You should also install the CORS library on your express server

Body:
You can do this with a proxy and CORS.

In your React app in your package.json you can specify

"proxy": "http://localhost:5000"

You should also install the CORS library on your express server


问:
Translating from SQL to R (concat and inner joins)
```<code>SELECT CONCAT(a.name,' ', a.surname) as "Deluxe drivers", m.producer, m.model
from employer a
INNER JOIN Driver s on s.iddriver=a.idemployer
INNER JOIN Taxi t ON t.idtaxi=s.idtaxi
INNER JOIN Model m ON m.idmodelcar=t.idmodelcar
WHERE m.producer IN ('Audi','Skoda','Honda','Hyundai') AND m.year>2010
GROUP BY a.name, a.surname, m.producer, m.model
ORDER BY 2,3
</code>```

So this is pretty much a basic SQL query but I need to translate it to R and I have some difficulties. Also, I am not sure if there is a function like CONCAT that can basically unite 2 different columns into one so the name and surname don't appear separately.

Can anyone assist me, please?

答:
When asking a question you should provide your data in a reproducible format, this makes it easier for us to help. I will give you a guideline of the functions I think can help you:

```<code>employer$deluxedrivers <- paste(name, surname, sep = ")
%in%
dplyr::group_by()
dplyr::order_by()
dplyr::filter()
merge()
</code>```

Hope this helps you!

Also, if you want to use SQL in R there is a package called sqldf that let you do it!

Body:
SELECT CONCAT(a.name,' ', a.surname) as "Deluxe drivers", m.producer, m.model
from employer a
INNER JOIN Driver s on s.iddriver=a.idemployer
INNER JOIN Taxi t ON t.idtaxi=s.idtaxi
INNER JOIN Model m ON m.idmodelcar=t.idmodelcar
WHERE m.producer IN ('Audi','Skoda','Honda','Hyundai') AND m.year>2010
GROUP BY a.name, a.surname, m.producer, m.model
ORDER BY 2,3

So this is pretty much a basic SQL query but I need to translate it to R and I have some difficulties. Also, I am not sure if there is a function like CONCAT that can basically unite 2 different columns into one so the name and surname don't appear separately.

Can anyone assist me, please?

Body:
When asking a question you should provide your data in a reproducible format, this makes it easier for us to help. I will give you a guideline of the functions I think can help you:

employer$deluxedrivers <- paste(name, surname, sep = ")
%in%
dplyr::group_by()
dplyr::order_by()
dplyr::filter()
merge()

Hope this helps you!

Also, if you want to use SQL in R there is a package called sqldf that let you do it!


问:
How to avoid break columns when to print page
I'm using css to creat columns with result query inside divs, but when I'm trying print the lasts divs every break, how to avoid this?

css:

```<code>     .div-em-colunas {
     -webkit-column-count:4; /* Chrome, Safari, Opera */
     -moz-column-count:4;    /* Firefox */
      column-count:4;         /* padrão */
</code>```

html

```<code>     <div class="div-em-colunas" >
     <div align="center" style="border-style: ridge;height:90px;"><b><?=$linha['user']?></b></br><?=$linha['name']?>
     </div>
</div>
</code>```

image:

答:
You need to use the page break inside property on any element you don't want to be page broken.

```<code>    page-break-inside: avoid;
</code>```

See the MDN documentation for more details on how to create a print stylesheet. https://developer.mozilla.org/en-US/docs/Web/Guide/Printing

OwnerDisplayName: Miguel Silva

Body:
I'm using css to creat columns with result query inside divs, but when I'm trying print the lasts divs every break, how to avoid this?

css:

     .div-em-colunas {
     -webkit-column-count:4; /* Chrome, Safari, Opera */
     -moz-column-count:4;    /* Firefox */
      column-count:4;         /* padrão */

html

<?=$linha['user']?>
<?=$linha['name']?>

image:

Body:
You need to use the page break inside property on any element you don't want to be page broken.

    page-break-inside: avoid;

See the MDN documentation for more details on how to create a print stylesheet. https://developer.mozilla.org/en-US/docs/Web/Guide/Printing


问:
Using operator 'and' or 'or' to check if elements exists
I'm a newbie on XPath. I discovered XPath because I need to make rules to SonarQube to analize my PL/SQL code. I'm trying to check if the where clause contains some of these operators: !=,  <>. I managed check if contains != or <> separately, but I need to add the 'OR' operator.

```<code>/*To catch <> operator*/
//WHERE_CLAUSE/EXPRESSION//*[self::NE_1]
</code>```

and

```<code>/*To catch != operator*/
//WHERE_CLAUSE/EXPRESSION//*[self::NE_2]
</code>```

What way to union the two expressions using 'OR'?

答:
This XPath,

```<code>//WHERE_CLAUSE/EXPRESSION//*[self::NE_1 or self::NE_2]
</code>```

will select all NE_1 and NE_2 descendants of //WHERE_CLAUSE/EXPRESSION.

Body:
I'm a newbie on XPath. I discovered XPath because I need to make rules to SonarQube to analize my PL/SQL code. I'm trying to check if the where clause contains some of these operators: !=,  <>. I managed check if contains != or <> separately, but I need to add the 'OR' operator.

/*To catch <> operator*/
//WHERE_CLAUSE/EXPRESSION//*[self::NE_1]

and

/*To catch != operator*/
//WHERE_CLAUSE/EXPRESSION//*[self::NE_2]

What way to union the two expressions using 'OR'?

Body:
This XPath,

//WHERE_CLAUSE/EXPRESSION//*[self::NE_1 or self::NE_2]

will select all NE_1 and NE_2 descendants of //WHERE_CLAUSE/EXPRESSION.


问:
Populate datalist with mysql fields based on input from another field without reloading page
I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.

I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.

```<code><form id="newsurveyform" method="post" action="submitnewsurvey.php">
        ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
    <datalist id="builders">
    <?php
        while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
        echo'<option value="'.$builderinforow['Builder'].'">';
    }
    ?>
    </datalist>

       Contact Name:
       <input list="contactnames" name="contactnames" required>
        <datalist id="contactnames">
        <div id="contactnamesoptions"> </div>
        </datalist>
       </form>

        <!-- AJAX, send builder value to php file-->
        <script>
        function findcontactnames(str) {
        if (str.length==0){
           document.getElementById("contactnames").innerHTML = "";
        return;}
        else{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("contactnamesoptions").innerHTML = this.responseText;
            }};
        xmlhttp.open("POST", "contactnames.php", true)
        xmlhttp.send(str);
           }
           }
        </script>
<?php
include 'dbconnector.php';

$buildername = $_POST["Builder"];

$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");

while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
          echo'<option value="'.$contactnamerow['ContactName'].'">';

}
  ?>
</code>```

Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.

Right now, it is not populating anything into the contact name field.

答:
In index.php

```<code>  <form id="newsurveyform" method="post" action="submitnewsurvey.php">
    ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>
    Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
    <datalist id="builders">
      <?php
        while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
          echo'<option value="'.$builderinforow['Builder'].'">';
        }
      ?>
    </datalist>

    Contact Name:
    <input list="contactnames" name="contactnames" required>
    <datalist id="contactnames">
      <div id="contactnamesoptions"> </div>
    </datalist>
  </form>

  <!-- AJAX, send builder value to php file-->
  <script>
    function findcontactnames(str) {
      if (str.length==0){
        document.getElementById("contactnames").innerHTML = "";
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          console.log(this);
          if (this.readyState == 4 && this.status == 200) {
            alert('Fired');
            document.getElementById("contactnamesoptions").innerHTML = this.responseText;
            // document.getElementById("contactnamesoptions").innerHTML = "working";
          }
        };
        xmlhttp.open("POST", "response.php", true)
        xmlhttp.send(str);
       }
     }
  </script>
</code>```

in response.php

```<code><?php echo "test"; ?>
</code>```

Once you've verified that works, query the database

EDIT:
Now that you've verified that, query the database in response.php

```<code>include 'dbconnector.php';
  $buildername = $_POST["Builder"];
  $contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
  $queryHTML = '';
  $result = 0;
  while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
    $result = 1;
    $queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
  }
  if ($result == 1) {
    echo $queryHTML;
  } else {
    echo 'No Builders found';
  }
</code>```

Note: Change the columnName in the query to your real column name

Body:
I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.

I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.

<form id="newsurveyform" method="post" action="submitnewsurvey.php">
        ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:* <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
    <datalist id="builders">
    <?php
        while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
        echo'<option value="'.$builderinforow['Builder'].'">';
    }
    ?>
    </datalist>

       Contact Name:
       <input list="contactnames" name="contactnames" required>
        <datalist id="contactnames">

        </datalist>
       </form>

<?php
include 'dbconnector.php';

$buildername = $_POST["Builder"];

$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");

while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
          echo'<option value="'.$contactnamerow['ContactName'].'">';

}
  ?>

Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.

Right now, it is not populating anything into the contact name field.

Body:
In index.php

  <form id="newsurveyform" method="post" action="submitnewsurvey.php">
    ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>&nbsp;
    Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
    <datalist id="builders">
      <?php
        while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
          echo'<option value="'.$builderinforow['Builder'].'">';
        }
      ?>
    </datalist>

    Contact Name:
    <input list="contactnames" name="contactnames" required>
    <datalist id="contactnames">
      <div id="contactnamesoptions"> </div>
    </datalist>
  </form>

  <!-- AJAX, send builder value to php file-->
  <script>
    function findcontactnames(str) {
      if (str.length==0){
        document.getElementById("contactnames").innerHTML = "";
        return;
      } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          console.log(this);
          if (this.readyState == 4 && this.status == 200) {
            alert('Fired');
            document.getElementById("contactnamesoptions").innerHTML = this.responseText;
            // document.getElementById("contactnamesoptions").innerHTML = "working";
          }
        };
        xmlhttp.open("POST", "response.php", true)
        xmlhttp.send(str);
       }
     }
  </script>

in response.php

<?php echo "test"; ?>

Once you've verified that works, query the database

EDIT:
Now that you've verified that, query the database in response.php

include 'dbconnector.php';
  $buildername = $_POST["Builder"];
  $contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
  $queryHTML = '';
  $result = 0;
  while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
    $result = 1;
    $queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
  }
  if ($result == 1) {
    echo $queryHTML;
  } else {
    echo 'No Builders found';
  }

Note: Change the columnName in the query to your real column name


问:
Attach description of columns in Apache Spark using parquet format
I read a parquet with :

```<code>df = spark.read.parquet(file_name)
</code>```

And get the columns with:

```<code>df.columns
</code>```

And returns a list of columns ['col1', 'col2', 'col3']

I read that parquet format is able to store some metadata in the file.

Is there a way to store and read extra metadata, for example, attach a human description of what is each column?

Thanks.

答:
There is no way to read or store arbitrary additional metadata in a Parquet file.

When metadata in a Parquet file is mentioned it is referring to the technical metadata associated with the field including the number of nested fields, type information, length information, etc. If you look at the SchemaElement class in the documentation for Parquet ( https://static.javadoc.io/org.apache.parquet/parquet-format/2.6.0/org/apache/parquet/format/SchemaElement.html) you will find all of the available metadata for each field in a schema. This does not include any human readable description beyond the field name.

A good overview of the Parquet metadata can be found in the "File Format" section here - https://parquet.apache.org/documentation/latest/

Body:
I read a parquet with :

df = spark.read.parquet(file_name)

And get the columns with:

df.columns

And returns a list of columns ['col1', 'col2', 'col3']

I read that parquet format is able to store some metadata in the file.

Is there a way to store and read extra metadata, for example, attach a human description of what is each column?

Thanks.


问:
Anything wrong with the loop - getting Maximum execution time of 30 seconds exceeded?
Just want to check if am doing something wrong here coz for small dataset the function works fine but a little more records and i get max executuion time error;

```<code>function getValue($products, $storeNum, $productKey) {
    foreach($products as $row)
    {
      if((int)$row->name === (int)$storeNum && (int)$row->product_key === (int)$productKey)
      {
        return $row->value;
      }
    }
    return 0;
}
</code>```

Input $products array is like this:

```<code>Array
(
    [0] => stdClass Object
        (
            [value] => 0
            [name] => 3195
            [product_key] => 13
        )

)
</code>```

PS: Function getvalue() is being called in another loop that creates the matrix of 400 (stores as Y-axis) by 50 (product names X-axis)

答:
It sounds like you're calling the getValue function 20000 times and iterating (worst case) the entire products array each time.

It should go much faster if you build the matrix in one iteration of $products. Here's a basic way to do that:

```<code>function makeMatrix($stores, $product_names, $products) {
    $matrix = [];

    // create the matrix from the lists of stores and product names
    foreach ($stores as $store) {
        foreach ($product_names as $product_name) {
            $matrix[$store][$product_name] = 0;
        }
    }

    // fill the matrix with the list of products
    foreach ($products as $product) {
        $matrix[$product->name][$product->product_key] = $product->value;
    }
    return $matrix;
}
</code>```

I think this should be faster because it runs as:

```<code>count(stores) * count(product_names) + count(products)
</code>```

And my theory is that the way you're currently doing it runs as:

```<code>count(stores) * count(product_names) * triangular_number(count(products))
</code>```

Body:
Just want to check if am doing something wrong here coz for small dataset the function works fine but a little more records and i get max executuion time error;

function getValue($products, $storeNum, $productKey) {
    foreach($products as $row)
    {
      if((int)$row->name === (int)$storeNum && (int)$row->product_key === (int)$productKey)
      {
        return $row->value;
      }
    }
    return 0;
}

Input $products array is like this:

Array
(
    [0] => stdClass Object
        (
            [value] => 0
            [name] => 3195
            [product_key] => 13
        )

)

PS: Function getvalue() is being called in another loop that creates the matrix of 400 (stores as Y-axis) by 50 (product names X-axis)

Body:
It sounds like you're calling the getValue function 20000 times and iterating (worst case) the entire products array each time.

It should go much faster if you build the matrix in one iteration of $products. Here's a basic way to do that:

function makeMatrix($stores, $product_names, $products) {
    $matrix = [];

    // create the matrix from the lists of stores and product names
    foreach ($stores as $store) {
        foreach ($product_names as $product_name) {
            $matrix[$store][$product_name] = 0;
        }
    }

    // fill the matrix with the list of products
    foreach ($products as $product) {
        $matrix[$product->name][$product->product_key] = $product->value;
    }
    return $matrix;
}

I think this should be faster because it runs as:

count(stores) * count(product_names) + count(products)

And my theory is that the way you're currently doing it runs as:

count(stores) * count(product_names) * triangular_number(count(products))


问:
Layout design issue
I have a problem in the layout design in android studio, in android studio I set 720x1280 in the design preview option. Its the first image. But when i build the apk and install it in the device, the same activity looks like the second image. Its like it's cut.

I need that in the first image, the blank space "expands" because i need to put the title long across in the second screen. The sentence is "Ingrese fecha de vencimiento" but only shows "Ingrese fecha de" .

How can i fix this?

答: It looks like you are missing a constraint to attach the right side of the TextView that says "Ingrese Fecha de vencimiento" to the right side of the container window.  This will allow that TextView to expand and contract as the container expands and contracts.  You should just have to click on the right side of the container and drag toward the right side of the TextView to create the constraint.</p>

Title: Layout design issue


问:
Read tab delimited data to array in C
I have an input file in text format that looks like:

```<code>G:  5   10  20  30
C:  24  49  4.0 30.0
</code>```

I'd like to set each of these to an array, array, respectively. I saw from this answer reading input parameters from a text file with C, a way to read some of the values, but how would I get the arrays G and C?

EDIT:

If I removed G:, and C: from the .txt file I could just run a for loop.

```<code>double *conc = (double*)malloc(properConfigs*sizeof(double));
double *G = (double*)malloc(properConfigs*sizeof(double));

for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &G[i]);
for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &conc[i]);
</code>```

This would work, but I'd like to be able to account for someone saving the .txt file in a different order or at some point adding more rows (with different parameters).

答:
I am not a fan of scanf, and would strongly encourage you to parse the line yourself.  If you insist on using scanf, I recommend using the sscanf variant for this so you can check the line beforehand to see which array to write.  I'm not sure why you're using named arrays at all, though.  C is not very good at introspection, and you can make your program more flexible without trying to tie your input to particular symbols.  Something like:

```<code>#include <stdio.h>
#include <stdlib.h>

#define properConfigs 4
void *Malloc(size_t s);
int
main(int argc, char **argv)
{
        FILE *fp = argc > 1 ? fopen(argv[1],"r") : stdin;
        double *G = Malloc( properConfigs * sizeof *G );
        double *C = Malloc( properConfigs * sizeof *G );
        int line_count = 0;
        char line[256];

        if( fp == NULL ) {
                perror(argv[1]);
                return 1;
        }
        while( line_count += 1, fgets( line, sizeof line, fp ) != NULL ) {
                double *target = NULL;
                switch(line[0]) {
                case 'G': target = G; break;
                case 'C': target = C; break;
                }
                if( target == NULL || 4 != sscanf(
                                line, "%*s%lf%lf%lf%lf",
                                target, target+1, target+2, target+3)) {
                        fprintf(stderr, "Bad input on line %d\n", line_count);
                }
        }
        for(int i=0; i < 4; i += 1 ) {
                printf ("G[%d] = %g\tC[%d] = %g\n", i, G[i], i, C[i]);
        }

        return ferror(fp);
}
void *Malloc(size_t s) {
        void *r = malloc(s);
        if(r == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
        }
        return r;
}
</code>```

Title: Read tab delimited data to array in C

Body:
I have an input file in text format that looks like:

G:  5   10  20  30
C:  24  49  4.0 30.0

I'd like to set each of these to an array, array, respectively. I saw from this answer reading input parameters from a text file with C, a way to read some of the values, but how would I get the arrays G and C?

EDIT:

If I removed G:, and C: from the .txt file I could just run a for loop.

double *conc = (double*)malloc(properConfigs*sizeof(double));
double *G = (double*)malloc(properConfigs*sizeof(double));

for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &G[i]);
for (int i=0;i<properConfigs;i++)
    fscanf(inputfile,"%lf", &conc[i]);

This would work, but I'd like to be able to account for someone saving the .txt file in a different order or at some point adding more rows (with different parameters).

Body:
I am not a fan of scanf, and would strongly encourage you to parse the line yourself.  If you insist on using scanf, I recommend using the sscanf variant for this so you can check the line beforehand to see which array to write.  I'm not sure why you're using named arrays at all, though.  C is not very good at introspection, and you can make your program more flexible without trying to tie your input to particular symbols.  Something like:

#include <stdio.h>
#include <stdlib.h>

#define properConfigs 4
void *Malloc(size_t s);
int
main(int argc, char **argv)
{
        FILE *fp = argc > 1 ? fopen(argv[1],"r") : stdin;
        double *G = Malloc( properConfigs * sizeof *G );
        double *C = Malloc( properConfigs * sizeof *G );
        int line_count = 0;
        char line[256];

        if( fp == NULL ) {
                perror(argv[1]);
                return 1;
        }
        while( line_count += 1, fgets( line, sizeof line, fp ) != NULL ) {
                double *target = NULL;
                switch(line[0]) {
                case 'G': target = G; break;
                case 'C': target = C; break;
                }
                if( target == NULL || 4 != sscanf(
                                line, "%*s%lf%lf%lf%lf",
                                target, target+1, target+2, target+3)) {
                        fprintf(stderr, "Bad input on line %d\n", line_count);
                }
        }
        for(int i=0; i < 4; i += 1 ) {
                printf ("G[%d] = %g\tC[%d] = %g\n", i, G[i], i, C[i]);
        }

        return ferror(fp);
}
void *Malloc(size_t s) {
        void *r = malloc(s);
        if(r == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
        }
        return r;
}


问:
How can I hide JavaScript from older browsers?
Because not all browsers support JavaScript, we need a way to hide JavaScript from those browsers. If we do not JavaScript from those browsers, those browsers will treat JavaScript as page's content and thus display that code on the web page. How could i do that?</p>

答:
Since JavaScript detection can be unreliable if done server-side, the best option is likely to use the  HTML tag. As detailed in this w3schools article, you could use something like:

```<code><script>
document.write("Hello World!")
</script>
<noscript>Your browser does not support JavaScript!</noscript>
</code>```

 is a generally well-supported HTML 4 tag and should be available in most major browsers, even older ones (since IE6+, Firefox 2+, Chrome 1+, etc.).

OwnerDisplayName: Nikos Belegrinos

Body:
Since JavaScript detection can be unreliable if done server-side, the best option is likely to use the <noscript> HTML tag. As detailed in this w3schools article, you could use something like:

<script>
document.write("Hello World!")
</script>
<noscript>Your browser does not support JavaScript!</noscript>

<noscript> is a generally well-supported HTML 4 tag and should be available in most major browsers, even older ones (since IE6+, Firefox 2+, Chrome 1+, etc.).

OwnerDisplayName: Anaksunaman