问:
How do I obtain (recreate) the bearer token used in AzureDevOps Pipelines?
I have a failed yaml Infrastructure-as-Code deployment that is failing at the first yaml step:

```<code>- task: ArchiveFiles@1
  displayName: 'Archive createADPDC.ps1 DSC files '
  inputs:
    rootFolder: 'Core/Templates/createADPDC.ps1'
    includeRootFolder: false
    replaceExistingArchive: true
    archiveFile: '$(Build.ArtifactStagingDirectory)/createADPDC.ps1.zip'
</code>```

To troubleshoot this, I've started a line-by-line attempt to simulate what's being done on the hosted pipeline servers, and am getting stuck at the bearer token. Unless there is a better way to diagnose why files are missing from ArtifactStagingDirectory, I'm running the commands below to inspect the files and structure that's being downloaded.

```<code>git init "C:\a\1\s"
Initialized empty Git repository in C:/a/1/s/.git/
git remote add origin https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core
git config gc.auto 0
git config --get-all http.https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core.extraheader
git config --get-all http.proxy
git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --force --tags --prune --progress --no-recurse-submodules origin
fatal: Authentication failed for 'https://dev.azure.com/MyLabs/Core/_git/Core/'
</code>```

Question

Either:

What is a better way to determine or understand why the ArchiveFiles would return

[error]ENOENT: no such file or directory, stat 'D:\a\1\s\Core\Templates\createADPDC.ps1'

What is the correct way to obtain the bearer token (PAT?) for use in the command line located in the logs

答:
So it's probably a good idea to get a handle on the directory structure used within the pipeline.

\agent_work\1 $(Agent.BuildDirectory)

\agent_work\1\a $(Build.ArtifactStagingDirectory)

\agent_work\1\b $(Build.BinariesDirectory)

\agent_work\1\s $(Build.SourcesDirectory)

$(Agent.BuildDirectory) where all folders for a given build pipeline are created

$(Build.ArtifactStagingDirectory) artifacts are copied to before being pushed to their destination.

$(Build.BinariesDirectory) you can use as an output folder for compiled binaries

$(Build.SourcesDirectory) where your source code files are downloaded

Links for Variables and SystemAccessToken

From the error message, it looks like the rootFolder location is relative to the $(Build.SourcesDirectory). To get a good look at your files inside the $(Agent.BuildDirectory) I like to use the tree command.

```<code>- task: PowerShell@2
  displayName: tree $(Agent.BuildDirectory)
  inputs:
    targetType: 'inline'
    script: 'tree /F'
    pwsh: true
    workingDirectory: '$(Agent.BuildDirectory)'
</code>```

Body:
I have a failed yaml Infrastructure-as-Code deployment that is failing at the first yaml step:

- task: ArchiveFiles@1
  displayName: 'Archive createADPDC.ps1 DSC files '
  inputs:
    rootFolder: 'Core/Templates/createADPDC.ps1'
    includeRootFolder: false
    replaceExistingArchive: true
    archiveFile: '$(Build.ArtifactStagingDirectory)/createADPDC.ps1.zip'

To troubleshoot this, I've started a line-by-line attempt to simulate what's being done on the hosted pipeline servers, and am getting stuck at the bearer token. Unless there is a better way to diagnose why files are missing from ArtifactStagingDirectory, I'm running the commands below to inspect the files and structure that's being downloaded.

git init "C:\a\1\s"
Initialized empty Git repository in C:/a/1/s/.git/
git remote add origin https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core
git config gc.auto 0
git config --get-all http.https://MyLabs@dev.azure.com/MyLabs/Core/_git/Core.extraheader
git config --get-all http.proxy
git -c http.extraheader="AUTHORIZATION: bearer ***" fetch --force --tags --prune --progress --no-recurse-submodules origin
fatal: Authentication failed for 'https://dev.azure.com/MyLabs/Core/_git/Core/'

Question

Either:

What is a better way to determine or understand why the ArchiveFiles would return

[error]ENOENT: no such file or directory, stat 'D:\a\1\s\Core\Templates\createADPDC.ps1'

What is the correct way to obtain the bearer token (PAT?) for use in the command line located in the logs

Body:
So it's probably a good idea to get a handle on the directory structure used within the pipeline.

\agent_work\1 $(Agent.BuildDirectory)

\agent_work\1\a $(Build.ArtifactStagingDirectory)

\agent_work\1\b $(Build.BinariesDirectory)

\agent_work\1\s $(Build.SourcesDirectory)

$(Agent.BuildDirectory) where all folders for a given build pipeline are created

$(Build.ArtifactStagingDirectory) artifacts are copied to before being pushed to their destination.

$(Build.BinariesDirectory) you can use as an output folder for compiled binaries

$(Build.SourcesDirectory) where your source code files are downloaded

Links for Variables and SystemAccessToken

From the error message, it looks like the rootFolder location is relative to the $(Build.SourcesDirectory). To get a good look at your files inside the $(Agent.BuildDirectory) I like to use the tree command.

- task: PowerShell@2
  displayName: tree $(Agent.BuildDirectory)
  inputs:
    targetType: 'inline'
    script: 'tree /F'
    pwsh: true
    workingDirectory: '$(Agent.BuildDirectory)'


来源: stackexchange

问:
Recoding a string variable (e.g. "815") to a time variable (08:15) in R
I am looking for help recoding a string variable to be correctly formatted as a time variable using r. I have daily diary data for ~ 450 individuals, over the course of a week. They self-reported their bed and wake times, and I am trying to do 2 things with the data 1) see how bed and wake times vary over the course of the week, and 2) calculate 'sleep duration'; the number of hours that elapses between these bed and wake times.

My problem is finding a way to reformat the data. The bed and wake times are currently string variables, with no colon between hh and mm ("815" would mean 8:15 AM; "2345" would mean 11:45 PM; "15" would mean 12:15 AM). I don't necessarily care about getting the AM/PM in there, it's fine if everything gets reformatted to something like "23:45".

I cannot figure out which package/function/creative workaround would best be able to help with this. I did see some packages like chron or lubridate, but those functions seem like they would be more helpful for my second problem, calculating the time difference between the two variables. But I do need help recoding this string variable to something usable.

Thank you for any advice or help!!!

ContentLicense: CC BY-SA 4.0

Body:
Suppose we have these times:

times <- c("345", "600", "1159", "1502", "2359")

Then we can define a simple function:

as_time <- function(t) gsub("(^\\d:)", "0\\1", gsub("(\\d{2}$)", ":\\1", t))

So we can do

as_time(times)
#> [1] "03:45" "06:00" "11:59" "15:02" "23:59"


问:
Add 0 padding to a pointer address
Basically I have a hard coded address in decimal value, and I would like to convert that to a pointer, I have been following this link

But I am not getting it to run as I believe my address is being truncated i.e. the 0's in the address are being removed.

Is there any how I can maintain the 0's or is there a way where I can type cast my address stored in buff to a pointer?

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

int main(int argc, char *argv[]) {
    int address = 200000000;
    char buff[80];
    sprintf(buff, "0x%012x", address);
    printf("%s\n", buff);

    uint32_t * const Value = (uint32_t *)(uintptr_t)buff;
    // *Value = 10;

    printf("%p\n", Value); // Value is now storing the value of the variable buff, I dont want this

    uint32_t *const Value2 = (uint32_t *)(uintptr_t)0x00000bebc200;

    printf("%p\n", Value2); // my address gets truncated, dont want the address to be truncated
}
</code>```

答:
If %p presents only 8 hex digits for the address, then that is because a pointer on your platform is only 32 bits and in that case the leading zeros have no meaning as there are no address bus lines A32 to A40 to set to zero.  The bits are not "truncated", they are not there in they first place.

If you some odd reason you wish to present the address as 48 bits (12 hex digits) on a platform where 32 bits is sufficient then:

```<code>uintptr_t address = 200000000u ;
uint32_t* const Value = (uint32_t *)address ;
printf( "0x%12.12lX\n", (uintptr_t)Value ) ;
</code>```

Outputs:

```<code>0x00000BEBC200
</code>```

But that is only a matter of presentation, the value in address and Value are unchanged and remain 32 bits.

Title: Add 0 padding to a pointer address

Body:
Basically I have a hard coded address in decimal value, and I would like to convert that to a pointer, I have been following this link

But I am not getting it to run as I believe my address is being truncated i.e. the 0's in the address are being removed.

Is there any how I can maintain the 0's or is there a way where I can type cast my address stored in buff to a pointer?

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[]) {
    int address = 200000000;
    char buff[80];
    sprintf(buff, "0x%012x", address);
    printf("%s\n", buff);

    uint32_t * const Value = (uint32_t *)(uintptr_t)buff;
    // *Value = 10;

    printf("%p\n", Value); // Value is now storing the value of the variable buff, I dont want this

    uint32_t *const Value2 = (uint32_t *)(uintptr_t)0x00000bebc200;

    printf("%p\n", Value2); // my address gets truncated, dont want the address to be truncated
}

Body:
If %p presents only 8 hex digits for the address, then that is because a pointer on your platform is only 32 bits and in that case the leading zeros have no meaning as there are no address bus lines A32 to A40 to set to zero.  The bits are not "truncated", they are not there in they first place.

If you some odd reason you wish to present the address as 48 bits (12 hex digits) on a platform where 32 bits is sufficient then:

uintptr_t address = 200000000u ;
uint32_t* const Value = (uint32_t *)address ;
printf( "0x%12.12lX\n", (uintptr_t)Value ) ;

Outputs:

0x00000BEBC200

But that is only a matter of presentation, the value in address and Value are unchanged and remain 32 bits.


问:
Files deleted after push in GitHub remote repository
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

```<code>git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master
</code>```

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?

答:
So there are a few ways to fix an undesired commit. It looks like maybe your local git repo didn't have all the info in your remote repo, which caused your push to overwrite it.
In your terminal, use git log to look at the commit history for your local git. If it only lists your test commit, we'll need to find the last good commit (where all the files still existed) a different way.

Go to your github and navigate to your commit history.
You should see a commit prior to the last push "some init msg" that overwrote your other files. It will have a hex identifier (in blue) on the right. Copy it!

From your git terminal, you want to use the command:
git checkout copiedhex#

This will copy to your local repo the version with all the files. However, you'll be in a detached HEAD state, and should get a message to that effect. You'll want to make this into a new branch by using:
git checkout -b some_new_branch_name
Then you can proceed as normal (merge it with master or keep working separately, push etc)

More helpful info here: https://www.atlassian.com/git/tutorials/undoing-changes

Hope that helps!

Body:
I have my first Git repository that I have created online named myName/python-algorithms.

It was containing many Python scripts. I tried to add a file test.py from my local Ubuntu terminal with the commands:

git init
git config user.name "myName"
git config user.e-mail "myEmail@myEmail.se"
git add test.py
git commit -m "some init msg"
git remote add origin https://github.com/myname/Python_Algorithms.git
git remote -v
git push -f origin master

which deleted all my Python scripts and replaced them with the file test.py on GitHub.

Any idea how I can get back my scripts that were deleted?


问:
want to hide "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3" } from ping module output?
I want to hide "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3"} from the output of ping module.

答:
It's possible to configure DEFAULT_STDOUT_CALLBACK and " Set the main callback used to display Ansible output.". For example

```<code>$ cat playbook.yml
- hosts: test_01
  tasks:
    - ping:

$ export ANSIBLE_STDOUT_CALLBACK=actionable; ansible-playbook playbook.yml
PLAY [test_01] ***

PLAY RECAP ***
test_01: ok=2  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
</code>```

See other available callback plugins.

Body:
It's possible to configure DEFAULT_STDOUT_CALLBACK and " Set the main callback used to display Ansible output.". For example

$ cat playbook.yml
- hosts: test_01
  tasks:
    - ping:

$ export ANSIBLE_STDOUT_CALLBACK=actionable; ansible-playbook playbook.yml
PLAY [test_01] ***

PLAY RECAP ***
test_01: ok=2  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

See other available callback plugins.


问:
GNU make show only error
Is it possible to configure GNU make to only show error. make --no-print-directory suppresses all the Entering/Leaving messages. similarly I don't want to see "make[4]: Nothing to be done for install.". Just the build error.

thanks.

答:
make -s won't print any of the commands (as if every command was prefixed by @). If the commands themselves are printing output, try redirecting standard output away but keeping standard error.

```<code>make -s >/dev/null
</code>```

However my recommendation would be to let all the output through, because it can be very useful to figure out what's going on. Use a tool such as colormake to make it more readable.

ContentLicense: CC BY-SA 3.0

Title: GNU make show only error

Body:
make -s won't print any of the commands (as if every command was prefixed by @). If the commands themselves are printing output, try redirecting standard output away but keeping standard error.

make -s >/dev/null

However my recommendation would be to let all the output through, because it can be very useful to figure out what's going on. Use a tool such as colormake to make it more readable.


问:
Java String Split by \\s+ and by String Array
In this code a user will input some text. It then needs to be split by whitespace - I am currently using:

for (String inputSplit : userInput.split("[\\s+]")) {
    // stuff happens here
}

It now needs to also be split by any operator which is stored in a variable called ops.

private String[] ops = {"+", "-", "*", "/", "%", "^"};

I'd like to keep it referencing ops, otherwise if I change something there, I have to remember to change it in this string split part too.

How can I just add this to the expression so that it reads 'split by whitespace or any one of these ops'?

e.g. userInput.split("[\\s+]|[ops]")

Extra info:

I am new to Java

JDK Amazon Corretto 11

IntelliJ IDEA CE 2019.3.2

答:
store the separator in string with or condition and pass it   </p>

```<code>String ops = "\\s+|\+|\-|\*|\/|\%|\^"
userInput.split(ops)
</code>```

Body:
store the separator in string with or condition and pass it

String ops = "\\s+|\+|\-|\*|\/|\%|\^"
userInput.split(ops)


问:
Combine columns from a table into a JSON object
I have a table in athena with data

```<code>type   state   city  zipcode
-------------------------------
hot     az     phx    85281
hot     tx     dal    12345
cool    wa     sea    67890
cool    ny     nyc    67856
</code>```

I want the output to be like

```<code>type   Data
-------------
hot    {state: az, city:phx, zipcode: 85281}
hot    {state: tx, city:dal, zipcode: 12345}
cool   {state: wa, city:sea, zipcode: 67890}
cool   {state: ny, city:nyc, zipcode: 67856}
</code>```

I am trying to use the aggregate function but i'm unable to use it.

SELECT type, CAST(MAP(ARRAY['state', 'city', 'zipcode'], ARRAY[state,city,zipcode] ) AS JSON) FROM "test"."alldata"

but the query fails.

答:
If you have a mysql Version with 5.7 or higher : use

```<code>SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;
</code>```

```<code>CREATE TABLE alldata
    (`type` varchar(4), `state` varchar(2), `city` varchar(3), `zipcode` int)
;

INSERT INTO alldata
    (`type`, `state`, `city`, `zipcode`)
VALUES
    ('hot', 'az', 'phx', 85281),
    ('hot', 'tx', 'dal', 12345),
    ('cool', 'wa', 'sea', 67890),
    ('cool', 'ny', 'nyc', 67856)
;
</code>```
```
✓

✓
```

```<code>SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;
</code>```
```
type | json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
:--- | :----------------------------------------------------------------
hot  | {"city": "phx", "state": "az", "zipcode": 85281}
hot  | {"city": "dal", "state": "tx", "zipcode": 12345}
cool | {"city": "sea", "state": "wa", "zipcode": 67890}
cool | {"city": "nyc", "state": "ny", "zipcode": 67856}
```

db<>fiddle here

Body:
I have a table in athena with data

type   state   city  zipcode
-------------------------------
hot     az     phx    85281
hot     tx     dal    12345
cool    wa     sea    67890
cool    ny     nyc    67856

I want the output to be like

type   Data
-------------
hot    {state: az, city:phx, zipcode: 85281}
hot    {state: tx, city:dal, zipcode: 12345}
cool   {state: wa, city:sea, zipcode: 67890}
cool   {state: ny, city:nyc, zipcode: 67856}

I am trying to use the aggregate function but i'm unable to use it.

SELECT type, CAST(MAP(ARRAY['state', 'city', 'zipcode'], ARRAY[state,city,zipcode] ) AS JSON) FROM "test"."alldata"

but the query fails.

Body:
If you have a mysql Version with 5.7 or higher : use

SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;

CREATE TABLE alldata
    (`type` varchar(4), `state` varchar(2), `city` varchar(3), `zipcode` int)
;

INSERT INTO alldata
    (`type`, `state`, `city`, `zipcode`)
VALUES
    ('hot', 'az', 'phx', 85281),
    ('hot', 'tx', 'dal', 12345),
    ('cool', 'wa', 'sea', 67890),
    ('cool', 'ny', 'nyc', 67856)
;

✓

✓

SELECT `type`,json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
FROM alldata;

type | json_object('state', `state`, 'city', `city`,'zipcode',`zipcode`)
:--- | :----------------------------------------------------------------
hot  | {"city": "phx", "state": "az", "zipcode": 85281}
hot  | {"city": "dal", "state": "tx", "zipcode": 12345}
cool | {"city": "sea", "state": "wa", "zipcode": 67890}
cool | {"city": "nyc", "state": "ny", "zipcode": 67856}

db<>fiddle here


问:
change srsName from my WFS Source with Openlayers/Geoserver
I'm currently using WFS with Openlayers but the layers is at the wrong position, if I'm right the problem come from the srsName but how to change it?

Here is my code for the WFS:

```<code>var WFSSource = new VectorSource({
  format: new GeoJSON(),
  url: function(extent) {
    return 'http://localhost:8081/geoserver/occi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=occi%3Aocci&maxFeatures=5&outputFormat=application%2Fjson';
  },
  strategy: bboxStrategy,
});

var WFSLayer = new VectorLayer({
  source: WFSSource
});
</code>```

I had the same issue with WMS, but I just changed the SRC natif on Geoserver ( EPSG:2154 ) and everything went fine. Now I have the same issue which gives me the following result:

The geometry should be at the bottom of the country. I think VectorSource has a default srsname, but I don't know how to change it.
Btw on the this link: https://openlayers.org/en/latest/examples/vector-wfs.html
they show how to use WFS and he have this line of code:

```<code>url: function(extent) {
return 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
    'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
    'outputFormat=application/json&srsname=EPSG:3857&' +
    'bbox=' + extent.join(',') + ',EPSG:3857';
</code>```

},

where he define the srsName but doesn't work for me.

----- Update -----

After checking the projection here is what I found:

My Map has default projection -> code : "EPSG:3857" , units : meters

My TileWMS has no settings but the documentation say that the params are set
dynamically. The things is on Geoserver I use "EPSG:2154" but the Map and this TileWMS match perfectly I don't understand how.

My VectorSource has format -> dataProjection -> code : "EPSG:4326" , units : degrees

Now I'm trying to figure how to put everything with the same projection but I'm struggling a lot.

If I change the map projection with "EPSG:2154" ( the native SRC of my layer in Geoserver ) I have the following error:

Cannot read property 'getExtent' of null.

And if I try to change my VectorSource projection nothing happen, my VectorSource stay in "EPSG:4326"

```<code>var WFSSource = new VectorSource({
  format: new GeoJSON(),
  url: function(extent) {
    return 'http://localhost:8081/geoserver/occi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=occi%3Aocci&maxFeatures=5&outputFormat=application%2Fjson';
  },
  projection : "EPSG:2154",
  strategy: bboxStrategy
});
</code>```

答:
ol/Source and ol/View have projection. Default projection is EPSG:3857. If your data or basemap is diffrent then EPSG:3857 you should define it.</p>

```<code>import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';

const map = new Map({
  layers: [
    new VectorLayer({
        source: new VectorSource({
            projection: 'EPSG:3857',
        })
    })
  ],
  target: 'map',
  view: new View({
    projection: 'EPSG:3857',
  })
});
</code>```

Body:
I'm currently using WFS with Openlayers but the layers is at the wrong position, if I'm right the problem come from the srsName but how to change it?

Here is my code for the WFS:

var WFSSource = new VectorSource({
  format: new GeoJSON(),
  url: function(extent) {
    return 'http://localhost:8081/geoserver/occi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=occi%3Aocci&maxFeatures=5&outputFormat=application%2Fjson';
  },
  strategy: bboxStrategy,
});

var WFSLayer = new VectorLayer({
  source: WFSSource
});

I had the same issue with WMS, but I just changed the SRC natif on Geoserver ( EPSG:2154 ) and everything went fine. Now I have the same issue which gives me the following result:

The geometry should be at the bottom of the country. I think VectorSource has a default srsname, but I don't know how to change it.
Btw on the this link: https://openlayers.org/en/latest/examples/vector-wfs.html
they show how to use WFS and he have this line of code:

url: function(extent) {
return 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
    'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
    'outputFormat=application/json&srsname=EPSG:3857&' +
    'bbox=' + extent.join(',') + ',EPSG:3857';

},

where he define the srsName but doesn't work for me.

----- Update -----

After checking the projection here is what I found:

My Map has default projection -> code : "EPSG:3857" , units : meters

My TileWMS has no settings but the documentation say that the params are set
dynamically. The things is on Geoserver I use "EPSG:2154" but the Map and this TileWMS match perfectly I don't understand how.

My VectorSource has format -> dataProjection -> code : "EPSG:4326" , units : degrees

Now I'm trying to figure how to put everything with the same projection but I'm struggling a lot.

If I change the map projection with "EPSG:2154" ( the native SRC of my layer in Geoserver ) I have the following error:

Cannot read property 'getExtent' of null.

And if I try to change my VectorSource projection nothing happen, my VectorSource stay in "EPSG:4326"

var WFSSource = new VectorSource({
  format: new GeoJSON(),
  url: function(extent) {
    return 'http://localhost:8081/geoserver/occi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=occi%3Aocci&maxFeatures=5&outputFormat=application%2Fjson';
  },
  projection : "EPSG:2154",
  strategy: bboxStrategy
});

Body:
ol/Source and ol/View have projection. Default projection is EPSG:3857. If your data or basemap is diffrent then EPSG:3857 you should define it.

import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';

const map = new Map({
  layers: [
    new VectorLayer({
        source: new VectorSource({
            projection: 'EPSG:3857',
        })
    })
  ],
  target: 'map',
  view: new View({
    projection: 'EPSG:3857',
  })
});


问:
Three table join, subquery, or something easier?
I was wondering if someone could help me with this.

This is a quick representation of a much more complicated schema. I am looking to get this implementation which is part of a larger stored proc.

So basically I am looking to obtain a result set that includes ClientId, Company Name, Setting1, Setting2 and Setting3.

So if a Company Id does not exist in the Settings Override table, then they subscribe to their respective default settings. But if they DO have an ID in the SettingsOverride table then the result set should return those settings.

So for this example the Result Set would look like this:

答:
You can join twice:

```<code>select
    c.clientId,
    c.companyName,
    coalesce(so.setting1, df.setting1) setting1,
    coalesce(so.setting2, df.setting2) setting2,
    coalesce(so.setting3, df.setting3) setting3
from company c
inner join defaul_settings cs on cs.clientId = c.clientId
left join settings_override so on so.companyId = c.companyId
</code>```

The critical part is to left join table settings_override, so companies that have no override are not excluded from the resultset. Then, you can use colasce() to use the default when there is no override.

Body:
You can join twice:

select
    c.clientId,
    c.companyName,
    coalesce(so.setting1, df.setting1) setting1,
    coalesce(so.setting2, df.setting2) setting2,
    coalesce(so.setting3, df.setting3) setting3
from company c
inner join defaul_settings cs on cs.clientId = c.clientId
left join settings_override so on so.companyId = c.companyId

The critical part is to left join table settings_override, so companies that have no override are not excluded from the resultset. Then, you can use colasce() to use the default when there is no override.


问:
Return value to variable from function
I am looking to return a value to a varible when I call the function in nodejs.

The output I am looking for is "Calling From Glasgow to Euston"

The output I am getting is "Calling From undefined to undefined"

Code is the following.

```<code>function trainstation(stx, callBack) {
  MongoClient.connect(ttdb, function(err, db) {
  if (err) throw err;
   var dbo = db.db("ttdb");
   var collection = dbo.collection("tlc");
   var find = collection.find( { "Stanox" : stx } );
   find.toArray(function(err, result) {
     if (err) throw err;
    db.close();
    return callBack(result);
   });
 });
};

function gettrain(){
   var ts1 = trainstation(9531, function(x){
     return x[0]['Station Name'];
   });
   var ts2 = trainstation(31033, function(x){
   return x[0]['Station Name'];
   });
   console.log("Calling From", ts1, "to", ts2);
  };
gettrain();
</code>```

Thanks :)

答:
I don't use the MongoDB package and I don't have MongoDB up & running right now to test this, so I've written this code purely based on a quick read of the reference documentation. Perhaps you can test this and we'll fix any minor issues. Copy this code to a new source file and test it.

What I've done is to take advantage of the MongoDB package's promise features. You can see that the code is more linear and simpler to follow.

```<code>const MongoClient = require('mongodb').MongoClient;
const ttdb = 'mongodb://localhost:27017'; // or your DB URL

const trainstation = async (Stanox) => {
  const client = MongoClient(ttdb);
  await client.connect();
  const dbo = client.db("ttdb");
  const collection = dbo.collection("tlc");
  const result = await collection.find({Stanox}).toArray();
  client.close();
  return result;
};

const gettrain = async () => {
  const ts1 = await trainstation(9531);
  const ts2 = await trainstation(31033);
  const sn1 = ts1[0]['Station Name'];
  const sn2 = ts2[0]['Station Name'];
  console.log("Calling From", sn1, "to", sn2);
};

gettrain();
</code>```

Title: Return value to variable from function

Body:
I am looking to return a value to a varible when I call the function in nodejs.

The output I am looking for is "Calling From Glasgow to Euston"

The output I am getting is "Calling From undefined to undefined"

Code is the following.

function trainstation(stx, callBack) {
  MongoClient.connect(ttdb, function(err, db) {
  if (err) throw err;
   var dbo = db.db("ttdb");
   var collection = dbo.collection("tlc");
   var find = collection.find( { "Stanox" : stx } );
   find.toArray(function(err, result) {
     if (err) throw err;
    db.close();
    return callBack(result);
   });
 });
};

function gettrain(){
   var ts1 = trainstation(9531, function(x){
     return x[0]['Station Name'];
   });
   var ts2 = trainstation(31033, function(x){
   return x[0]['Station Name'];
   });
   console.log("Calling From", ts1, "to", ts2);
  };
gettrain();

Thanks :)

Body:
I don't use the MongoDB package and I don't have MongoDB up & running right now to test this, so I've written this code purely based on a quick read of the reference documentation. Perhaps you can test this and we'll fix any minor issues. Copy this code to a new source file and test it.

What I've done is to take advantage of the MongoDB package's promise features. You can see that the code is more linear and simpler to follow.

const MongoClient = require('mongodb').MongoClient;
const ttdb = 'mongodb://localhost:27017'; // or your DB URL

const trainstation = async (Stanox) => {
  const client = MongoClient(ttdb);
  await client.connect();
  const dbo = client.db("ttdb");
  const collection = dbo.collection("tlc");
  const result = await collection.find({Stanox}).toArray();
  client.close();
  return result;
};

const gettrain = async () => {
  const ts1 = await trainstation(9531);
  const ts2 = await trainstation(31033);
  const sn1 = ts1[0]['Station Name'];
  const sn2 = ts2[0]['Station Name'];
  console.log("Calling From", sn1, "to", sn2);
};

gettrain();


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答:
Lists in Perl are not data structures, they are positions in the source code, determined by the context around them.  Lists are basically the transient structures that Perl uses to move data around.  You interact with them with all of Perl's syntax, but you can not work with them as a data type.  The data type that is closest to a list is an array.

```<code>my @var    =    (1, 2, 3);  # parens needed for precedence, they do not create a list
   ^ an array    ^ a list

say 1, 2, 3;
    ^ a list

say @var;
    ^ a list (of one array, which will expand into 3 values before `say` is called)
</code>```

When you write [1, 2, 3] what you are doing is creating a scalar array reference.  That array reference is initialized with the list 1, 2, 3, and it is the same as creating a named array and taking a reference to it:

```<code>[1, 2, 3]   ~~   do {my @x = (1, 2, 3); \@x}
</code>```

Since the [...] construct creates a scalar, you should hold it in a scalar:

```<code>my $array = [1, 2, 3];

for my $elem (@$array) {   # lexical loop variable
    print $elem."\n";
}
</code>```

Since you want to operate on the whole array, and not just the reference, you place a @ in front of the $array which dereferences the stored array reference.

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

Body:
Lists in Perl are not data structures, they are positions in the source code, determined by the context around them.  Lists are basically the transient structures that Perl uses to move data around.  You interact with them with all of Perl's syntax, but you can not work with them as a data type.  The data type that is closest to a list is an array.

my @var    =    (1, 2, 3);  # parens needed for precedence, they do not create a list
   ^ an array    ^ a list

say 1, 2, 3;
    ^ a list

say @var;
    ^ a list (of one array, which will expand into 3 values before `say` is called)

When you write [1, 2, 3] what you are doing is creating a scalar array reference.  That array reference is initialized with the list 1, 2, 3, and it is the same as creating a named array and taking a reference to it:

[1, 2, 3]   ~~   do {my @x = (1, 2, 3); \@x}

Since the [...] construct creates a scalar, you should hold it in a scalar:

my $array = [1, 2, 3];

for my $elem (@$array) {   # lexical loop variable
    print $elem."\n";
}

Since you want to operate on the whole array, and not just the reference, you place a @ in front of the $array which dereferences the stored array reference.


问:
How can i get the same result as Hives from_unixtime in Impala?
I understand Imapla interpretes timestamps relative to the UTC timezone. I also know there is a setting where this behavior can be changed, so that impala interpretes timestamps relative to the local timezone. The problem is I cannot change this setting.

Is there a way to get the same result as i get in Hive in Impala?
Here is the Hive result:

```<code>select from_unixtime(1521938294)
--> 2018-03-25 01:38:14
</code>```

The local timezone is Europe/Vienna

答:
Great question. But the answer is tricky! I was researching this for sometime and below is my answer.

The date and time selected by you points to the time when the time shift happens for Vienna. i.e., the time gets shifted ahead by one hour.

You can check it by using the below links.

HERE1

HERE2

Coming to the time conversion in Impala without using any flags as you need, the syntax would like the below,

```<code>select from_utc_timestamp(cast(from_unixtime(1521938294) AS TIMESTAMP), 'Europe/Vienna');
[OR]
select from_utc_timestamp('2018-03-25 00:38:14', 'Europe/Vienna');

2018-03-25 01:38:00   <---EXPECTED OUTPUT
2018-03-25 02:38:00   <---ACTUAL OUTPUT IN IMPALA
</code>```

The above syntax does the job of converting the Unix Timestamp into Europe/Vienna Time, However there is a difference in the one hour difference in the result as shown above due to the difference between the time shift that happens in real life happens vs the conversion that happens in Impala.

Reason:

Time shift in Real life - 25th March, 2019 01:59:59 and then 25th March, 2019 03:00:00

Time shift in Impala    - 25th March, 2019 00:59:59 and then 25th March, 2019 02:00:00

Even though there seems to be a conversion issue in Impala, the syntax I provided above should work flawlessly for any dates in the year 2018 other than 25-March.

For Other dates:

```<code>select from_utc_timestamp('2018-03-26 00:38:14', 'Europe/Vienna')

2018-03-26 02:38:14   <---ACTUAL & CORRECT OUTPUT IN IMPALA
</code>```

Hope it helps!

Body:
I understand Imapla interpretes timestamps relative to the UTC timezone. I also know there is a setting where this behavior can be changed, so that impala interpretes timestamps relative to the local timezone. The problem is I cannot change this setting.

Is there a way to get the same result as i get in Hive in Impala?
Here is the Hive result:

select from_unixtime(1521938294)
--> 2018-03-25 01:38:14

The local timezone is Europe/Vienna

Body:
Great question. But the answer is tricky! I was researching this for sometime and below is my answer.

The date and time selected by you points to the time when the time shift happens for Vienna. i.e., the time gets shifted ahead by one hour.

You can check it by using the below links.

HERE1

HERE2

Coming to the time conversion in Impala without using any flags as you need, the syntax would like the below,

select from_utc_timestamp(cast(from_unixtime(1521938294) AS TIMESTAMP), 'Europe/Vienna');
[OR]
select from_utc_timestamp('2018-03-25 00:38:14', 'Europe/Vienna');

2018-03-25 01:38:00   <---EXPECTED OUTPUT
2018-03-25 02:38:00   <---ACTUAL OUTPUT IN IMPALA

The above syntax does the job of converting the Unix Timestamp into Europe/Vienna Time, However there is a difference in the one hour difference in the result as shown above due to the difference between the time shift that happens in real life happens vs the conversion that happens in Impala.

Reason:

Time shift in Real life - 25th March, 2019 01:59:59 and then 25th March, 2019 03:00:00

Time shift in Impala    - 25th March, 2019 00:59:59 and then 25th March, 2019 02:00:00

Even though there seems to be a conversion issue in Impala, the syntax I provided above should work flawlessly for any dates in the year 2018 other than 25-March.

For Other dates:

select from_utc_timestamp('2018-03-26 00:38:14', 'Europe/Vienna')

2018-03-26 02:38:14   <---ACTUAL & CORRECT OUTPUT IN IMPALA

Hope it helps!


问:
Is there a way of adding an HTML when the extension's icon is clicked
In fact,

I want to write a little chrome extension that gives me the dimension of the window.

So I decided to use a HTML code injected into the webpage when I click on the extension's icon

I tried many things but it doesn't work (the html injected does not appear)

This is my manifest.json for now:

```<code>{
    "name": "Dimension",
    "version": "1.0",
    "description": "Giving you the window dimensions live!",

    "permissions": [
      "tabs", "<all_urls>"
    ],
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "css": ["dimension.css"],
        "js": ["inject.js"]
      }
    ],
    "web_accessible_resources": ["dimension.html", "dimension.css", "dimension.js"],
    "browser_action": {},
    "manifest_version": 2
  }
</code>```

inject.js file:

```<code>console.log("inject script loaded")

chrome.browserAction.onClicked.addListener(inject)

function inject() {
    var iFrame  = document.createElement ("iframe");
    iFrame.src  = chrome.extension.getURL ("dimension.html");

    document.body.insertBefore (iFrame, document.body.firstChild);
    console.log('html injected')
}
</code>```

I also tried inject.js as the background script but it was opening the html file into the Extension Background environment (when you inspect the background script)

答:
Use the built-in devtools to inspect and debug your code. It should show an error about chrome.browserAction being undefined. This API can't be used in a content script: you need a background script for most extension API listeners.

To access the web page you need a content script but there's no need to declare it, simply use the programmatic injection, and there's also no need for those permissions. A single activeTab is sufficient in this scenario.

manifest.json

```<code>{
  "name": "Dimension",
  "version": "1.0",
  "description": "Giving you the window dimensions live!",
  "permissions": ["activeTab"],
  "web_accessible_resources": ["dimension.*"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {},
  "manifest_version": 2
}
</code>```

background.js

```<code>chrome.browserAction.onClicked.addListener(tab => {
  chrome.tabs.executeScript(tab.id, {file: 'inject.js'});
});
</code>```

In your inject.js file replace chrome.browserAction line with inject();

Body:
In fact,

I want to write a little chrome extension that gives me the dimension of the window.

So I decided to use a HTML code injected into the webpage when I click on the extension's icon

I tried many things but it doesn't work (the html injected does not appear)

This is my manifest.json for now:

{
    "name": "Dimension",
    "version": "1.0",
    "description": "Giving you the window dimensions live!",

    "permissions": [
      "tabs", "<all_urls>"
    ],
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "css": ["dimension.css"],
        "js": ["inject.js"]
      }
    ],
    "web_accessible_resources": ["dimension.html", "dimension.css", "dimension.js"],
    "browser_action": {},
    "manifest_version": 2
  }

inject.js file:

console.log("inject script loaded")

chrome.browserAction.onClicked.addListener(inject)

function inject() {
    var iFrame  = document.createElement ("iframe");
    iFrame.src  = chrome.extension.getURL ("dimension.html");

    document.body.insertBefore (iFrame, document.body.firstChild);
    console.log('html injected')
}

I also tried inject.js as the background script but it was opening the html file into the Extension Background environment (when you inspect the background script)

Body:
Use the built-in devtools to inspect and debug your code. It should show an error about chrome.browserAction being undefined. This API can't be used in a content script: you need a background script for most extension API listeners.

To access the web page you need a content script but there's no need to declare it, simply use the programmatic injection, and there's also no need for those permissions. A single activeTab is sufficient in this scenario.

manifest.json

{
  "name": "Dimension",
  "version": "1.0",
  "description": "Giving you the window dimensions live!",
  "permissions": ["activeTab"],
  "web_accessible_resources": ["dimension.*"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {},
  "manifest_version": 2
}

background.js

chrome.browserAction.onClicked.addListener(tab => {
  chrome.tabs.executeScript(tab.id, {file: 'inject.js'});
});

In your inject.js file replace chrome.browserAction line with inject();


问:
aws s3 notification include metadata information
I have a lambda function that gets notification whenever and s3 object gets added.  The function then reads some metadata of the s3 object.  Is there any way to include the metadata in the notification itself, rather than me having to go and read the head object.</p>

答: The event notification data structure does not include object metadata or tags, and there is not a way to enable their inclusion.</p>


问:
Using sed to print between delimiters
This is an extension of my previous question recommended by the answerer. Basically, I need sed to print text between delimiters. The delimiters could span multiple lines like:

```<code>(abc
d)
</code>```

Below are sample input and output.

Input

```<code>(123)
aa (a(b)cd)) (g) (c)fff
abcd(aabb
d)aa (aeb)oe
</code>```

correct output

```<code>123
a(b
aabb
d
</code>```

Note: I only want the text between the first pair of delimiters. If the delimiter spans two lines than I just want the text between first pair that span two lines and move on to the third (next) line. Thus, for the last line in the input I printed 'd' and skip (aeb) and move on to the next line.

答:
I used a sed script file (called sedscript) containing:

```<code>/^[^(]*([^)]*$/N
s/^[^(]*(\([^)]*\)).*/\1/p
</code>```

and the command line:

```<code>sed -n -f sedscript data
</code>```

Given the input:

```<code>(123)
aa (a(b)cd)) (g) (c)fff
abcd(aabb
d)aa (aeb)oe
</code>```

It produced the output:

```<code>123
a(b
aabb
d
</code>```

You can do it on a single command line with:

```<code>sed -n -e '/^[^(]*([^)]*$/N' -e 's/^[^(]*(\([^)]*\)).*/\1/p' data
</code>```

The first pattern looks for lines containing an open parenthesis without a close parenthesis after it, and reads the next line into memory and starts over.  It repeats that until there is a close parenthesis in the data (or EOF).  The second pattern looks for the stuff before an open parenthesis, the open parenthesis, remembers the data from there to the first close parenthesis, followed by the close parenthesis and any other stuff; it replaces that with the remembered string and prints it.  Anything else is not printed (-n).

Title: Using sed to print between delimiters

Body:
This is an extension of my previous question recommended by the answerer. Basically, I need sed to print text between delimiters. The delimiters could span multiple lines like:

(abc
d)

Below are sample input and output.

Input

(123)
aa (a(b)cd)) (g) (c)fff
abcd(aabb
d)aa (aeb)oe

correct output

123
a(b
aabb
d

Note: I only want the text between the first pair of delimiters. If the delimiter spans two lines than I just want the text between first pair that span two lines and move on to the third (next) line. Thus, for the last line in the input I printed 'd' and skip (aeb) and move on to the next line.

Body:
I used a sed script file (called sedscript) containing:

/^[^(]*([^)]*$/N
s/^[^(]*(\([^)]*\)).*/\1/p

and the command line:

sed -n -f sedscript data

Given the input:

(123)
aa (a(b)cd)) (g) (c)fff
abcd(aabb
d)aa (aeb)oe

It produced the output:

123
a(b
aabb
d

You can do it on a single command line with:

sed -n -e '/^[^(]*([^)]*$/N' -e 's/^[^(]*(\([^)]*\)).*/\1/p' data

The first pattern looks for lines containing an open parenthesis without a close parenthesis after it, and reads the next line into memory and starts over.  It repeats that until there is a close parenthesis in the data (or EOF).  The second pattern looks for the stuff before an open parenthesis, the open parenthesis, remembers the data from there to the first close parenthesis, followed by the close parenthesis and any other stuff; it replaces that with the remembered string and prints it.  Anything else is not printed (-n).


问:
How can I define a background image to fill the screen and remove edges on the left and right in React with Material UI?
I'm using Material-UI with React. In the login page I want to fill the background of the page behind a Paper component with an image.
I set the backgroundSize of the image to cover but it still leaves a white edge on the left and the right side of the screen.

This is my Login component:

```<code>const style = theme => ({
    content: {
        minHeight: '900px',
        backgroundImage: `url(${imageUrl})`,
        backgroundPosition: '50%',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
    },
    paper: {
        flexGrow: 1,
        padding: theme.spacing(2),
        maxWidth: 300,
        margin: 'auto',
    },
});

class Login extends Component {

    componentDidMount() {
        if (localStorage.getItem('usertoken') !== null) {
            this.props.history.push('/');
        }
    }

    render() {
        const {classes} = this.props;
        return (
        <div className={classes.content}>
                <br/>
                <Typography variant='h3'>Login</Typography>
                <br/>
                <Paper className={classes.paper}>
                    <Grid container direction='column' justify='space-between' alignItems='center' spacing={1}>
                     //Formik Field inside
                    </Grid>
                </Paper>
       </div>
)}}
Login.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(style)(Login);
</code>```

My app.js looks like this:

```<code>
<ErrorHandler>
                <ThemeProvider theme={customTheme}>
                    <Router history={history}>
                        <MainHeader/>
                        <Switch>
                            <Route path='/login' component={Login}/>
                            <Route component={NotFoundPage}/>
                        </Switch>
                        <Footer/>
                    </Router>
                </ThemeProvider>
</ErrorHandler>

</code>```

I'm not defining any margin in the app.js.

Thank you very much in advance!

答:
If you are not worried about aspect ratio

```<code>let w = window.innerWidth;
let h = window.innerHeight;
...
backgroundSize: w + 'px ' + h + 'px';
</code>```

There are a few ways to deal with it - this might also help https://stackoverflow.com/a/25496015/4241624

Body:
I'm using Material-UI with React. In the login page I want to fill the background of the page behind a Paper component with an image.
I set the backgroundSize of the image to cover but it still leaves a white edge on the left and the right side of the screen.

This is my Login component:

const style = theme => ({
    content: {
        minHeight: '900px',
        backgroundImage: `url(${imageUrl})`,
        backgroundPosition: '50%',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
    },
    paper: {
        flexGrow: 1,
        padding: theme.spacing(2),
        maxWidth: 300,
        margin: 'auto',
    },
});

class Login extends Component {

    componentDidMount() {
        if (localStorage.getItem('usertoken') !== null) {
            this.props.history.push('/');
        }
    }

    render() {
        const {classes} = this.props;
        return (

                <Typography variant='h3'>Login</Typography>

                <Paper className={classes.paper}>
                    <Grid container direction='column' justify='space-between' alignItems='center' spacing={1}>
                     //Formik Field inside
                    </Grid>
                </Paper>

)}}
Login.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(style)(Login);

My app.js looks like this:

<ErrorHandler>
                <ThemeProvider theme={customTheme}>
                    <Router history={history}>
                        <MainHeader/>
                        <Switch>
                            <Route path='/login' component={Login}/>
                            <Route component={NotFoundPage}/>
                        </Switch>

                    </Router>
                </ThemeProvider>
</ErrorHandler>

I'm not defining any margin in the app.js.

Thank you very much in advance!

Body:
If you are not worried about aspect ratio

let w = window.innerWidth;
let h = window.innerHeight;
...
backgroundSize: w + 'px ' + h + 'px';

There are a few ways to deal with it - this might also help https://stackoverflow.com/a/25496015/4241624


问:
Office365: Checklist and Workflow
We use Office365 and am looking to create a number of equipment inspection checklists where a user would go to a One-Drive link, open a checklist template, use the checklist during equipment inspection and make comments, then upon completion save the document with a machine generated name (apparatus and date-based) to a folder on One-Drive.  In addition, if an item(s) on the checklist is out of spec, a separate email will be sent to a specified email address with info about the defect.

I have looked at MS Forms and it seems very clunky for this application as there are many items on the checklist.  I could create it as an macro-automated Word document, but that seems a bit old-fashioned.

What is the right way to do this?  Are there any examples of this that I could learn from? Thank you.

答:
You should build this as a standard custom list in a SharePoint site.  Each of your checklist items becomes a separate field in the list, and thus every New entry in the list is one complete checklist.  I know this seems a little sideways since your checklist items are columns -- but the New Item form and Edit form present the fields for that item in a vertical fashion making it appear more like a check list that the user can interact with.  This then gives you a table listing of everyone's checklist that you could filter and sort and even fire Power Automate Flows based on statuses.  Once complete, you can use a Flow to generate a Word document or PDF document and save it in a library or OneDrive.

You can provide users with a hyperlink directly to that list's entry form (e.g. https://yourtenant.sharepoint.com/sites/checklistsite/lists/checklist/NewForm.aspx).  If the default entry form does not meet your needs, you can always customize the list form with PowerApps.

Title: Office365: Checklist and Workflow


问:
How to overflow the image inside a div in the top and bottom and not just in left and right?
I'm trying to make the image overflow not just in left and right but also in the top and bottom.
I'm not sure if the problem is in my css or html.

```<code>.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 190% auto;
    }
</code>```

.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 190% auto;
    }
    .sectionForm form {
        width: 400px;
        box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
        border-radius: 40px;
        background-color: white;
    }
    .form-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 66px 0 50px 0;
    }
    footer {
        height: 1500px;
    }

    .form-container input {
        border: none;
        border-bottom: 1px solid #828282;
        padding: 26px 0;
        margin-bottom: 100px;
        font-size: 20px;
        color: #4F4F4F;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br>
<br>
<br>
<br>
<br>

<div class="sectionForm">
        <form>
            <div class="form-container">
                <input type="text" id="fname" name="fname" value="Nome">
                <input type="text" id="lname" name="lname" value="E-mail">
                <input type="text" id="lname" name="lname" value="Assunto">

            </div>
        </form>
    </div>

    <br>
<br>
<br>
<br>
<br></code>```

答:
So i just needed to add padding to it

```<code>background-size: 160% auto;
padding: 112px;
</code>```

.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 160% auto;
    padding: 112px;
    }
    .sectionForm form {
        width: 400px;
        box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
        border-radius: 40px;
        background-color: white;
    }
    .form-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 66px 0 50px 0;
    }
    footer {
        height: 1500px;
    }

    .form-container input {
        border: none;
        border-bottom: 1px solid #828282;
        padding: 26px 0;
        margin-bottom: 100px;
        font-size: 20px;
        color: #4F4F4F;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br>
<br>
<br>
<br>
<br>

<div class="sectionForm">
        <form>
            <div class="form-container">
                <input type="text" id="fname" name="fname" value="Nome">
                <input type="text" id="lname" name="lname" value="E-mail">
                <input type="text" id="lname" name="lname" value="Assunto">

            </div>
        </form>
    </div>

    <br>
<br>
<br>
<br>
<br></code>```

Body:
I'm trying to make the image overflow not just in left and right but also in the top and bottom.
I'm not sure if the problem is in my css or html.

.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 190% auto;
    }

.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 190% auto;
    }
    .sectionForm form {
        width: 400px;
        box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
        border-radius: 40px;
        background-color: white;
    }
    .form-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 66px 0 50px 0;
    }
    footer {
        height: 1500px;
    }

    .form-container input {
        border: none;
        border-bottom: 1px solid #828282;
        padding: 26px 0;
        margin-bottom: 100px;
        font-size: 20px;
        color: #4F4F4F;
    }

        <form>

                <input type="text" id="fname" name="fname" value="Nome">
                <input type="text" id="lname" name="lname" value="E-mail">
                <input type="text" id="lname" name="lname" value="Assunto">

        </form>

Body:
So i just needed to add padding to it

background-size: 160% auto;
padding: 112px;

.sectionForm {
        margin: 0 auto;
  background: url("https://image.flaticon.com/icons/svg/1914/1914882.svg") no-repeat center center;
    background-size: 160% auto;
    padding: 112px;
    }
    .sectionForm form {
        width: 400px;
        box-shadow: 0px 4px 30px rgba(0, 0, 0, 0.2);
        border-radius: 40px;
        background-color: white;
    }
    .form-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 66px 0 50px 0;
    }
    footer {
        height: 1500px;
    }

    .form-container input {
        border: none;
        border-bottom: 1px solid #828282;
        padding: 26px 0;
        margin-bottom: 100px;
        font-size: 20px;
        color: #4F4F4F;
    }

<br>
<br>
<br>
<br>
<br>

<div class="sectionForm">
        <form>
            <div class="form-container">
                <input type="text" id="fname" name="fname" value="Nome">
                <input type="text" id="lname" name="lname" value="E-mail">
                <input type="text" id="lname" name="lname" value="Assunto">

            </div>
        </form>
    </div>

    <br>
<br>
<br>
<br>
<br>


问:
Android Studio get a txt file from web in widget
I am new to android studio and just want an app to do one thing: check if the bytewerk is open (domain is stats.bytewerk.org/status.txt just one word either open or closed) and display it on a widget. But I tried all kind of httpconections like volley or okhttp, but never got a result. I already added the uses permission in the manifest.

1:

```<code>public class StatusWidget<appWidgetId> extends AppWidgetProvider {

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) throws IOException {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
        new GetNotePadFileFromServer().execute();

        //views.setViewVisibility(R.id.bytewerk_online, 0);
        appWidgetManager.updateAppWidget(appWidgetId, views);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            try {

                updateAppWidget(context, appWidgetManager, appWidgetId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
    String TextHolder;
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL("http://stats.bytewerk.org/status.txt");

            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
            TextHolder = "";
            String TextHolder2 = "";
            while ((TextHolder2 = bufferReader.readLine()) != null) {

                TextHolder += TextHolder2;
            }
            bufferReader.close();

        } catch (MalformedURLException malformedURLException) {

            // TODO Auto-generated catch block
            malformedURLException.printStackTrace();
            TextHolder = malformedURLException.toString();

        } catch (IOException iOException) {

            // TODO Auto-generated catch block
            iOException.printStackTrace();

            TextHolder = iOException.toString();
        }

        return null;

    }

    @Override
    protected void onPostExecute(Void finalTextHolder) {

        textView.setText(TextHolder);

        super.onPostExecute(finalTextHolder);
    }
</code>```

2:

```<code>final TextView textView = (TextView) findViewById(R.id.text);
// ...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        textView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        textView.setText("That didn't work!");
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);
</code>```

And the other examples on the offical website
of course i already implemented

```<code>dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}
</code>```

答:
this was my solution:</p>

```<code>    static void updateAppWidget(Context context, final AppWidgetManager appWidgetManager,
                                final int appWidgetId) {
        final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
// ...

// Instantiate the RequestQueue.
       RequestQueue queue = Volley.newRequestQueue(context);
        String url ="http://stats.bytewerk.org/status.txt";
// Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        if (response.equals("open")) {
                            views.setViewVisibility(R.id.status_online, 1);
                        } else {
                            views.setViewVisibility(R.id.status_offline, 1);
                        }
                        //views.setTextViewText(R.id.text, "Yeah!" + response);
                        appWidgetManager.updateAppWidget(appWidgetId, views);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                views.setViewVisibility(R.id.status_nointernet, 1);
                appWidgetManager.updateAppWidget(appWidgetId, views);

            }
        });
        queue.add(stringRequest);
</code>```

Body:
I am new to android studio and just want an app to do one thing: check if the bytewerk is open (domain is stats.bytewerk.org/status.txt just one word either open or closed) and display it on a widget. But I tried all kind of httpconections like volley or okhttp, but never got a result. I already added the uses permission in the manifest.

1:

public class StatusWidget<appWidgetId> extends AppWidgetProvider {

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) throws IOException {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
        new GetNotePadFileFromServer().execute();

        //views.setViewVisibility(R.id.bytewerk_online, 0);
        appWidgetManager.updateAppWidget(appWidgetId, views);

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        for (int appWidgetId : appWidgetIds) {
            try {

                updateAppWidget(context, appWidgetManager, appWidgetId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}public class GetNotePadFileFromServer extends AsyncTask<Void, Void, Void> {
    String TextHolder;
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL("http://stats.bytewerk.org/status.txt");

            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(url.openStream()));
            TextHolder = "";
            String TextHolder2 = "";
            while ((TextHolder2 = bufferReader.readLine()) != null) {

                TextHolder += TextHolder2;
            }
            bufferReader.close();

        } catch (MalformedURLException malformedURLException) {

            // TODO Auto-generated catch block
            malformedURLException.printStackTrace();
            TextHolder = malformedURLException.toString();

        } catch (IOException iOException) {

            // TODO Auto-generated catch block
            iOException.printStackTrace();

            TextHolder = iOException.toString();
        }

        return null;

    }

    @Override
    protected void onPostExecute(Void finalTextHolder) {

        textView.setText(TextHolder);

        super.onPostExecute(finalTextHolder);
    }

2:

final TextView textView = (TextView) findViewById(R.id.text);
// ...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        textView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        textView.setText("That didn't work!");
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);

And the other examples on the offical website
of course i already implemented

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

Body:
this was my solution:

    static void updateAppWidget(Context context, final AppWidgetManager appWidgetManager,
                                final int appWidgetId) {
        final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_widget);
// ...

// Instantiate the RequestQueue.
       RequestQueue queue = Volley.newRequestQueue(context);
        String url ="http://stats.bytewerk.org/status.txt";
// Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        if (response.equals("open")) {
                            views.setViewVisibility(R.id.status_online, 1);
                        } else {
                            views.setViewVisibility(R.id.status_offline, 1);
                        }
                        //views.setTextViewText(R.id.text, "Yeah!" + response);
                        appWidgetManager.updateAppWidget(appWidgetId, views);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                views.setViewVisibility(R.id.status_nointernet, 1);
                appWidgetManager.updateAppWidget(appWidgetId, views);

            }
        });
        queue.add(stringRequest);


问:
What does "return a" in this recursive combinations function does?
I went over this function over and over in Chrome debugger and still can't understand what return a does. Thanks for helping me out!

Here's some clarification:
I understand the first round. The anonymous function gets called with the following parameters:

active = "", rest = "abc", a = []

It then calls itself til rest is empty, when it populates the a array:

active = "abc", rest = "", a = ["abc"]

At this point we arrive to return a, and the debugger jumps to the second fn call in the else statement instead of the first if statement. The parameters already look like this:

active = "ab", rest = "c", a = ["abc"]

This is the part I don't understand at all. I know the recursion is only over when active and rest is empty, but after return a the if statements don't even get checked in the debugger, it just highlights the mentioned second function call, and at that point "c" is already assigned to rest. I guess the reason why this function doesn't produce duplicates also lies here, but that might be another question if not. Anyway, thanks again for the help!

```<code>combinations("abc");

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}
</code>```

答:
In this case the recursion construct is written oddly and the "return a" is merely to smuggle out the mutated array, the same object initially supplied, back to the helper function so that a direct return can be used on the inner recursive function call. (In most contexts, and especially those discussed in recursion primers, recursive functions usually utilize the returned value.)

Here is a cleaner re-write using the helper function more. I also removed all explicit return statements because they were not adding value here.

```<code>function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest) {
            // base case #1 - implicit return, no recursive call
        } else if (!rest) {
            // base case #2 - implicit return, no recursive call
            a.push(active);
        } else {
            // recursive case, where function is called again
            // (the object "a" is modified in recursion;
            //  result of recursion not directly used)
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
    }

    var o = [];     // only one output object created..
    fn("", str, o); // ..mutated..
    return o;       // ..and returned to caller.
}
</code>```

It should then be easy to observe that passing "a" to the recursive function is not needed (ie. it could access "o" in the enclosing scope) because there is no new object assigned to "a" after the initial result array is created.

There is a subtle difference in the re-write will (more correctly) return an empty array for an empty input string.

Body:
I went over this function over and over in Chrome debugger and still can't understand what return a does. Thanks for helping me out!

Here's some clarification:
I understand the first round. The anonymous function gets called with the following parameters:

active = "", rest = "abc", a = []

It then calls itself til rest is empty, when it populates the a array:

active = "abc", rest = "", a = ["abc"]

At this point we arrive to return a, and the debugger jumps to the second fn call in the else statement instead of the first if statement. The parameters already look like this:

active = "ab", rest = "c", a = ["abc"]

This is the part I don't understand at all. I know the recursion is only over when active and rest is empty, but after return a the if statements don't even get checked in the debugger, it just highlights the mentioned second function call, and at that point "c" is already assigned to rest. I guess the reason why this function doesn't produce duplicates also lies here, but that might be another question if not. Anyway, thanks again for the help!

combinations("abc");

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest)
            return;
        if (!rest) {
            a.push(active);
        } else {
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
        return a;
    }
    return fn("", str, []);
}

Body:
In this case the recursion construct is written oddly and the "return a" is merely to smuggle out the mutated array, the same object initially supplied, back to the helper function so that a direct return can be used on the inner recursive function call. (In most contexts, and especially those discussed in recursion primers, recursive functions usually utilize the returned value.)

Here is a cleaner re-write using the helper function more. I also removed all explicit return statements because they were not adding value here.

function combinations(str) {
    var fn = function(active, rest, a) {
        if (!active && !rest) {
            // base case #1 - implicit return, no recursive call
        } else if (!rest) {
            // base case #2 - implicit return, no recursive call
            a.push(active);
        } else {
            // recursive case, where function is called again
            // (the object "a" is modified in recursion;
            //  result of recursion not directly used)
            fn(active + rest[0], rest.slice(1), a);
            fn(active, rest.slice(1), a);
        }
    }

    var o = [];     // only one output object created..
    fn("", str, o); // ..mutated..
    return o;       // ..and returned to caller.
}

It should then be easy to observe that passing "a" to the recursive function is not needed (ie. it could access "o" in the enclosing scope) because there is no new object assigned to "a" after the initial result array is created.

There is a subtle difference in the re-write will (more correctly) return an empty array for an empty input string.


问:
Unnecessary NullReferenceException?
Why do I get a NullReferenceException in the following code?

```<code>private string FileR ( string name )
{
    string[] content = ReadSite(name, Protocol.read, url);
    Request_Template newCon;
    string[] final = new string[content.Length];

    for (int i = 0; i < content.Length; i++)
    {
        if (content[i].Equals(null))
        {
            return "content [" + i + "] returns null";
        }
        newCon = JsonSerializer.Deserialize<Request_Template>(content[i]);

        if (newCon.Sender.Contains(myAccount.Username))
        {
            newCon.Sender = "Me";
        }

        string sender = newCon.Sender;
        string message = newCon.Message;
        final[i] = sender + ":\t" + message;
    }

    string nFinal = string.Concat(final);

    Thread.Sleep(10);
    return nFinal;
}

string[] ReadSite(string filename, Protocol p, string uri)
{
    Read_Template temp = new Read_Template
    {
        Chat = filename,
        Code = key1
    };
    string myUrl = JsonSerializer.Serialize(temp);

    WebClient web = new WebClient();
    Stream stream = web.OpenRead(uri + "/" + myUrl);

    int length = 0;
    while (new StreamReader(stream).ReadLine() != null)
    {
        length++;
    }
    string[] content = new string[length];

    using (StreamReader reader = new StreamReader(stream))
    {
        for (int i = 0; i < length; i++)
        {
            content[i] = reader.ReadLine();
        }
    }

    return content;
}
</code>```

I've tried using the debugging tools with no avail.  When I ran the code, it said that the error came from string [] final = new string [content.Length];
 and for (int i = 0; i < content.Length; i++).That lead me to assume that content was null. But when I used the watch window and it said that the variable content cannot be determined. How do I fix this?

答:
```<code>private string FileR ( string name )
{
    // ReadSite always returns a content that has length 0 or more. string[] content will never equals null.
    // TEST: string[] test = new string[0]; test == null -> False
    string[] content = ReadSite(name, Protocol.read, url);
    Request_Template newCon;

    string[] final = new string[content.Length];

    // if content.Length == 0, this loop will never occur and you wont get any NREs.
    for (int i = 0; i < content.Length; i++)
    {
        // It is highly unlikely that a reader.ReadLine() would generate a null but
        // just in case it does, use == null instead of .Equals() method. When content[i] == null, you cannot use .Equals() method since nulls dont have Equals method.
        if (content[i].Equals(null))
        {
            return "content [" + i + "] returns null";
        }

        // If you have checked that content[i] is Not empty space or null, you might
        //end up with newCon == null if Deserialization fails. Cover this around try / catch.
        newCon = JsonSerializer.Deserialize<Request_Template>(content[i]);

        // If deserialization fails, this will throw NRE because nulls wont have
        // Sender as a property or array. Check if newCon == null or not. Also,
        // check if Sender was correctly initialized as an array/list.. as it could
        // be null. nulls wont have Contains as a method.
        if (newCon.Sender.Contains(myAccount.Username))
        {
            newCon.Sender = "Me";
        }

        string sender = newCon.Sender;
        string message = newCon.Message;

        // This should work correctly as its dependent on content.length. If the
        // loop is happening, then there is at least one final element that can be updated.
        final[i] = sender + ":\t" + message;
    }

    string nFinal = string.Concat(final);

    Thread.Sleep(10);
    return nFinal;
}
</code>```

Title: Unnecessary NullReferenceException?

Body:
Why do I get a NullReferenceException in the following code?

private string FileR ( string name )
{
    string[] content = ReadSite(name, Protocol.read, url);
    Request_Template newCon;
    string[] final = new string[content.Length];

    for (int i = 0; i < content.Length; i++)
    {
        if (content[i].Equals(null))
        {
            return "content [" + i + "] returns null";
        }
        newCon = JsonSerializer.Deserialize<Request_Template>(content[i]);

        if (newCon.Sender.Contains(myAccount.Username))
        {
            newCon.Sender = "Me";
        }

        string sender = newCon.Sender;
        string message = newCon.Message;
        final[i] = sender + ":\t" + message;
    }

    string nFinal = string.Concat(final);

    Thread.Sleep(10);
    return nFinal;
}

string[] ReadSite(string filename, Protocol p, string uri)
{
    Read_Template temp = new Read_Template
    {
        Chat = filename,
        Code = key1
    };
    string myUrl = JsonSerializer.Serialize(temp);

    WebClient web = new WebClient();
    Stream stream = web.OpenRead(uri + "/" + myUrl);

    int length = 0;
    while (new StreamReader(stream).ReadLine() != null)
    {
        length++;
    }
    string[] content = new string[length];

    using (StreamReader reader = new StreamReader(stream))
    {
        for (int i = 0; i < length; i++)
        {
            content[i] = reader.ReadLine();
        }
    }

    return content;
}

I've tried using the debugging tools with no avail.  When I ran the code, it said that the error came from string [] final = new string [content.Length];
 and for (int i = 0; i < content.Length; i++).That lead me to assume that content was null. But when I used the watch window and it said that the variable content cannot be determined. How do I fix this?


问:
Code doesn't funtion right in PHP 7.3. Best way ti fix where it is backwards compatible with PHP 7.1 and 7.2, count() error
This is code within a laravel framework

```<code> 'mat_tactic_id' => count($request['red-mat_tactic_id']) > 0 ? implode(',',$request['red-mat_tactic_id']) : $request['red-mat_tactic_id'],
</code>```

Here is the exception

ErrorException (E_WARNING) count(): Parameter must be an array or an
  object that implements Countable

I have tried is_Countable and that will fix but only in 7.3 it is not backwards compatible.

Any thoughts?

答:
You can check if it is even set and if it is an array like so:

```<code>isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])
</code>```

That means counting would work like this:

```<code>count((isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])) ? $request['red-mat_tactic_id'] : [])
</code>```

To have it better readable you would probably break that into two lines:

```<code>$isValueSet = $request['red-mat_tactic_id'] && is_array($request['red-mat_tactic_id'];
count(isValueSet ? $request['red-mat_tactic_id'] : [])
</code>```

Depending on what exactly the content of the array index is, this could be simplified to:

```<code>count($request['red-mat_tactic_id'] ?? [])
</code>```

Using the null coalescing operator.

Body:
This is code within a laravel framework

 'mat_tactic_id' => count($request['red-mat_tactic_id']) > 0 ? implode(',',$request['red-mat_tactic_id']) : $request['red-mat_tactic_id'],

Here is the exception

ErrorException (E_WARNING) count(): Parameter must be an array or an
  object that implements Countable

I have tried is_Countable and that will fix but only in 7.3 it is not backwards compatible.

Any thoughts?

Body:
You can check if it is even set and if it is an array like so:

isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])

That means counting would work like this:

count((isset($request['red-mat_tactic_id']) && is_array($request['red-mat_tactic_id'])) ? $request['red-mat_tactic_id'] : [])

To have it better readable you would probably break that into two lines:

$isValueSet = $request['red-mat_tactic_id'] && is_array($request['red-mat_tactic_id'];
count(isValueSet ? $request['red-mat_tactic_id'] : [])

Depending on what exactly the content of the array index is, this could be simplified to:

count($request['red-mat_tactic_id'] ?? [])

Using the null coalescing operator.


问:
Problem with primary keys Java Hibernate?
I'm using Hibernate and Java to implement a database.

I have created the following two annotations:

```<code>    @Entity public class Cargo implements Serializable{
    @Id
    @GeneratedValue
    private Long id;
    private String cargo;

    @OneToOne(mappedBy="cargo")
    private Funcionario funcionario;
}
</code>```

and

```<code>@Entity public class Funcionario implements Serializable{

@Id @GeneratedValue private Long id;
private String nome;
private String sexo;
private String telefone;
@OneToOne
private Cargo cargo;
}
</code>```

Then I try to insert data with the following code:

```<code> EntityManagerFactory factory = Persistence.createEntityManagerFactory("BD04PU");
        EntityManager manager = factory.createEntityManager();
        manager.getTransaction().begin();

        Cargo novoCargo = new Cargo();
        Funcionario novoFuncionario = new Funcionario();

        Scanner entrada = new Scanner(System.in);

        System.out.print("\nCargo: ");

        novoCargo.setCargo(entrada.nextLine());
        manager.persist(novoCargo);

        System.out.print("\nNome: ");
        novoFuncionario.setNome(entrada.nextLine());

        System.out.print("\nSexo: ");
        novoFuncionario.setSexo(entrada.nextLine());

        System.out.print("\nTelefone: ");
        novoFuncionario.setTelefone(entrada.nextLine());

        novoFuncionario.setCargo(novoCargo);

        manager.persist(novoFuncionario);
        manager.getTransaction().commit();
        factory.close();

</code>```

but as the result the foreign keys of Cargo and Funcionario count as follows: Cargo starts with 1 whereas Funcionario starts with 2, then Cargo primary key becomes 3 and Funcionario primary key becomes 4.

It is as if both primary keys were the same.

Why is that so? How to fix it?

Above, the Cargo id should be used as a foreign key in the Funcionario table.

答:
You're reusing the same sequence in both entities, to separate them, you can use

```<code>@Entity
public class Cargo implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cargo_generator")
    @SequenceGenerator(name="cargo_generator", sequenceName = "cargo_seq", allocationSize=50)
    private Long id;
    private String cargo;

    @OneToOne(mappedBy="cargo")
    private Funcionario funcionario;
}
</code>```

and

```<code>@Entity
public class Funcionario implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "funcionario_generator")
    @SequenceGenerator(name="funcionario_generator", sequenceName = "funcionario_seq", allocationSize=50)
    private Long id;
    private String nome;
    private String sexo;
    private String telefone;
    @OneToOne
    private Cargo cargo;

}
</code>```

If you're creating the schema manually, you would have to define the sequences: cargo_seq and funcionario_seq.

Body:
I'm using Hibernate and Java to implement a database.

I have created the following two annotations:

    @Entity public class Cargo implements Serializable{
    @Id
    @GeneratedValue
    private Long id;
    private String cargo;

    @OneToOne(mappedBy="cargo")
    private Funcionario funcionario;
}

and

@Entity public class Funcionario implements Serializable{

@Id @GeneratedValue private Long id;
private String nome;
private String sexo;
private String telefone;
@OneToOne
private Cargo cargo;
}

Then I try to insert data with the following code:

 EntityManagerFactory factory = Persistence.createEntityManagerFactory("BD04PU");
        EntityManager manager = factory.createEntityManager();
        manager.getTransaction().begin();

        Cargo novoCargo = new Cargo();
        Funcionario novoFuncionario = new Funcionario();

        Scanner entrada = new Scanner(System.in);

        System.out.print("\nCargo: ");

        novoCargo.setCargo(entrada.nextLine());
        manager.persist(novoCargo);

        System.out.print("\nNome: ");
        novoFuncionario.setNome(entrada.nextLine());

        System.out.print("\nSexo: ");
        novoFuncionario.setSexo(entrada.nextLine());

        System.out.print("\nTelefone: ");
        novoFuncionario.setTelefone(entrada.nextLine());

        novoFuncionario.setCargo(novoCargo);

        manager.persist(novoFuncionario);
        manager.getTransaction().commit();
        factory.close();

but as the result the foreign keys of Cargo and Funcionario count as follows: Cargo starts with 1 whereas Funcionario starts with 2, then Cargo primary key becomes 3 and Funcionario primary key becomes 4.

It is as if both primary keys were the same.

Why is that so? How to fix it?

Above, the Cargo id should be used as a foreign key in the Funcionario table.

Body:
You're reusing the same sequence in both entities, to separate them, you can use

@Entity
public class Cargo implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cargo_generator")
    @SequenceGenerator(name="cargo_generator", sequenceName = "cargo_seq", allocationSize=50)
    private Long id;
    private String cargo;

    @OneToOne(mappedBy="cargo")
    private Funcionario funcionario;
}

and

@Entity
public class Funcionario implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "funcionario_generator")
    @SequenceGenerator(name="funcionario_generator", sequenceName = "funcionario_seq", allocationSize=50)
    private Long id;
    private String nome;
    private String sexo;
    private String telefone;
    @OneToOne
    private Cargo cargo;

}

If you're creating the schema manually, you would have to define the sequences: cargo_seq and funcionario_seq.


问:
Is it normal for a field return by API request to be gone?
Is it naive to expect API requests to always return a field that previously existed.
I can understand the need to introduce new fields, but is it ok to delete an entire field and without warning??

When building an app that relies on api results, how I have to safeguard against fields disappearing when a major functionality depends on result of that field?

答:
It is the not normal as it is a breaking change to the clients that are already use this field. So if the API provider removes some fields without notifying you , you have no effective ways to detect it. Of course , you can always check the API return all the fields in the API response as said in the API documentation but it is very silly approach. I would simply returning some runtime exception saying that there is an unexpected system error.

Normally as an API provider , it should somehow have some strategies to manage removing fields such as :

Notify clients that this field will be deprecated now and will be removed soon and give them some reasonable time span to update their client to migrate out of the deprecated fields.

Monitor the field usage in production. If it is sure a field is really not used by anybody , this field can be safely removed.


问:
mysql: implement function into query
i'm having a database which is storing geo-data like countries, cities.
i would like to use modrewrite with links like:
mysite.com/europe/austria/vienna

now the problem: in german, some countries contain umlauts like austria = österreich
(i can't use umlauts in urls)

so my question:
is there a way to create a function inside the database which replaces all special characters when querying like "where validUrl(country)='oesterreich' ?
which would replace ö->oe

my only idea so far is adding an extra database field for modrewrite which would hold "oesterreich"

any ideas? thanks

答:
It won't help you, because though you can replace ü with ue in German, you can't do such things with diacritics in other languages. You can however encode these characters so they are valid in the url. See urlencode and urldecode for this.

Also, when you set the collation of the column to unicode_ci, you should be able to select similar strings, so WHERE YourField = 'enquête' should match 'enquete' too. 'österreich' will probably match 'osterreich' but not 'oesterreich'. MySQL is probably not smart enough to know whether this word is French or German.

You could choose a specifically german collation, but this won't suit your goal. It may still be interesting to read this text on collations, since it shows the difference between two german collations.

Title: mysql: implement function into query


问:
GridView RowCommand event not firing
I have a GridView that looks something like this:

```<code><asp:GridView
    ID="GridView1"
    AllowPaging="true"
    OnRowCommand="RowCommand"
    OnPageIndexChanging="gridView_PageIndexChanging"
    Runat="server">
    <Columns>
        ...
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" ButtonType="Button" CommandName="ItemExport" CommandArgument='<%# Eval("EXPORT") %>'
                    Text="Export" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
 </asp:GridView>
</code>```

Here is RowCommand:

```<code>protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ItemExport")
    {
        // etc.
    }
}
</code>```

Clicking the button is not firing the RowCommand event at all. However, RowCommand fires when I click a page index in the GridView's pager.

答: Did them all and got nowhere then discovered this:  onrowcommand="GridView1_RowCommand"  on the GridView1 definition line in html. </p>

Title: GridView RowCommand event not firing

Body:
I have a GridView that looks something like this:

<asp:GridView
    ID="GridView1"
    AllowPaging="true"
    OnRowCommand="RowCommand"
    OnPageIndexChanging="gridView_PageIndexChanging"
    Runat="server">
    <Columns>
        ...
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" ButtonType="Button" CommandName="ItemExport" CommandArgument='<%# Eval("EXPORT") %>'
                    Text="Export" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
 </asp:GridView>

Here is RowCommand:

protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ItemExport")
    {
        // etc.
    }
}

Clicking the button is not firing the RowCommand event at all. However, RowCommand fires when I click a page index in the GridView's pager.


问:
Making text in a cell a button javascript
is there anyway to make this extra td a button so that every "show" is clickable?

```<code>$(document).ready(function(){
                $.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data){
                  var custData = '';
                  $.each(data, function(key, value){
                    custData += '<tr>';
                    custData += '<td>' +value.name+'</td>';
                    custData += '<td>' +value.address+'</td>';
                    custData += '<td>' +value.cityStateZip+'</td>';
                    custData += '<td>' +value.latLang+'</td>';
                    custData += '<td>' +(value.image || "No image available")+'</td>';
                    custData += '<td>' +"show"+ '</td>'; // this is what I need a button
                    custData += '</tr>';
                  });
</code>```

I'm worried that I messed up by adding that extra column alongside the others being created with json data, but I'm not sure how else to add a button for every row.

答:
I'm not sure I understand your question. But here is an example for you that prints row numbers when clicked 'show'.

```<code>function printRowNumber(row) {
alert('Row:' + row);
return false;
}

$(document).ready(function() {
const appDiv = document.getElementById('app');
$.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data) {
    var custData = '';
    $.each(data, function(key, value) {
        custData += '<tr>';
        custData += '<td>' + value.name + '</td>';
        custData += '<td>' + value.address + '</td>';
        custData += '<td>' + value.cityStateZip + '</td>';
        custData += '<td>' + value.latLang + '</td>';
        custData += '<td>' + (value.image || "No image available") + '</td>';
        custData += '<td>' + '<a href="javascript:void" onClick=printRowNumber(' + key + ')>show</a>' + '</td>'; // this is what I need a button
        custData += '</tr>';

    });
    appDiv.insertAdjacentHTML('beforeend', '<table>' + custData + '</table>');

})});
</code>```

If you want to use button instead of 'show' you can replace a tag with button.

```<code>    custData += '<td>' +'<button onClick=printRowNumber('+key+')>show</button>'+ '</td>';
</code>```

Body:
is there anyway to make this extra td a button so that every "show" is clickable?

$(document).ready(function(){
                $.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data){
                  var custData = '';
                  $.each(data, function(key, value){
                    custData += '
';
                    custData += '' +value.name+'	';
                    custData += '' +value.address+'	';
                    custData += '' +value.cityStateZip+'	';
                    custData += '' +value.latLang+'	';
                    custData += '' +(value.image || "No image available")+'	';
                    custData += '' +"show"+ '	'; // this is what I need a button
                    custData += '
';
                  });

I'm worried that I messed up by adding that extra column alongside the others being created with json data, but I'm not sure how else to add a button for every row.

Body:
I'm not sure I understand your question. But here is an example for you that prints row numbers when clicked 'show'.

function printRowNumber(row) {
alert('Row:' + row);
return false;
}

$(document).ready(function() {
const appDiv = document.getElementById('app');
$.getJSON("http://cs1.utm.edu/~bbradley/map1/customers1.json", function(data) {
    var custData = '';
    $.each(data, function(key, value) {
        custData += '<tr>';
        custData += '<td>' + value.name + '</td>';
        custData += '<td>' + value.address + '</td>';
        custData += '<td>' + value.cityStateZip + '</td>';
        custData += '<td>' + value.latLang + '</td>';
        custData += '<td>' + (value.image || "No image available") + '</td>';
        custData += '<td>' + '<a href="javascript:void" onClick=printRowNumber(' + key + ')>show</a>' + '</td>'; // this is what I need a button
        custData += '</tr>';

    });
    appDiv.insertAdjacentHTML('beforeend', '<table>' + custData + '</table>');

})});

If you want to use button instead of 'show' you can replace a tag with button.

    custData += '<td>' +'<button onClick=printRowNumber('+key+')>show</button>'+ '</td>';