问:
How can I customize a data set for Google BigQuery? Can I export a file? How do I test it to see if it meets my needs?
I would like to improve the quality of existing data by using the Google BigQuery API to help validate the accuracy of existing data.

I dont see information on the types of data elements contained in the BigQuery and dont understand how to use an API if I just want to see what types of data are contained in there.

I tried looking for instructions and data elements in the Google Health Care API and Google BigQuery documentation and only saw how to set up a payment option.

I am a newbie at programming and wanted to do some preliminary research on these data sets prior to bringing them to our technical team.

I expect to see a list of relevant results based on a custom query.

答:
You can see the data types supported
 by Google BigQuery here and the conversion between different types here. </p>

<p>Also you can try out the BigQuery APIs in the OAuthPlayGround. </p>

Body:
You can see the data types supported
 by Google BigQuery here and the conversion between different types here.

Also you can try out the BigQuery APIs in the OAuthPlayGround.


来源: stackexchange

问:
How can parse JSon with special characters?
This my text in database:

```<code>"推奨切削条件 "
</code>```

in PHP, i using Json_encode:
Result:

```<code>{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};
</code>```

In javascript :

```<code>var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';//getData();
strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var jsonData = JSON.parse(strData)
</code>```

Error:

```<code>Uncaught SyntaxError: Unexpected token  in JSON at position 56
    at JSON.parse (<anonymous>)
</code>```

How can parse JSon with special characters?

Thanks all.

答:
i have to copy json to js

I have no idea why, but okay… You don't need to deal with it as JSON string inside Javascript at all then. JSON is a valid Javascript literal. So just paste your JSON into your Javascript without the quotes:

```<code>var data = {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};
</code>```

This is a perfectly valid Javascript object literal which requires no parsing.

If you need a valid Javascript string literal containing a JSON string, json_encode(json_encode(...)) it twice to get:

var strData = "{\"table1\":\"\\u63a8\\u5968\\u5207\\u524a\\u6761\\u4ef6 \\b\"}";
console.log(JSON.parse(strData));```

ContentLicense: CC BY-SA 4.0

Body:
This my text in database:

"推奨切削条件 "

in PHP, i using Json_encode:
Result:

{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};

In javascript :

var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';//getData();
strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var jsonData = JSON.parse(strData)

Error:

Uncaught SyntaxError: Unexpected token  in JSON at position 56
    at JSON.parse (<anonymous>)

How can parse JSon with special characters?

Thanks all.

Body:
i have to copy json to js

I have no idea why, but okay… You don't need to deal with it as JSON string inside Javascript at all then. JSON is a valid Javascript literal. So just paste your JSON into your Javascript without the quotes:

var data = {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};

This is a perfectly valid Javascript object literal which requires no parsing.

If you need a valid Javascript string literal containing a JSON string, json_encode(json_encode(...)) it twice to get:

var strData = "{\"table1\":\"\\u63a8\\u5968\\u5207\\u524a\\u6761\\u4ef6 \\b\"}";
console.log(JSON.parse(strData));


问:
Fastest way for generating fake files with given filesize
I'm looking for fastest way to generate fake files for stress test where is a possibility to pass file size. Currently I'm using simple

with open("{}".format(i), 'wb') as f: f.write(os.urandom(FILE_SIZE))

but for my case, creating each file takes too long. It seems to me that the Faker library does not have the method to generate fake files

EDIT: The code below is just a part of whole script so any CMD/OS commands are not a solution for my problem.

答:
You can follow the below to get command with explanation and then run the same command in for loop.

How to create a file with ANY given size in Linux?


问:
How to efficiently check whether a vector of numbers is in an interval defined by a data frame
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

```<code>set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}
</code>```

Thanks!

答:
Function findInterval has good performance and can get the job done.

See first how it works with just the first element of n1

```<code>i <- findInterval(n1[1], c(df.int$Upper.Limit, Inf))
j <- findInterval(n1[1], c(-Inf, df.int$Upper.Limit))

df.int$Upper.Limit[i]
#[1] 189000
n1[1]
#[1] 189041
df.int$Upper.Limit[j]
#[1] 189200

df.int$Upper.Limit[i] < n1[1] & n1[1] <= df.int$Upper.Limit[j]
#[1] TRUE
</code>```

Now a general purpose solution.

```<code>subsInterval <- function(x, DF, colLimits = 1, colValues = 2, lower = TRUE){
  vec <- if(lower)
    c(DF[[colLimits]], Inf)
  else
    c(-Inf, DF[[colLimits]])
  i <- findInterval(x, vec, left.open = TRUE)
  DF[[colValues]][i]
}

system.time(
  n2 <- subsInterval(n1, df.int)
)
#     user    system   elapsed
#    0.000     0.000     0.001

system.time(
  n3 <- subsInterval(n1, df.int, lower = FALSE)
)
#     user    system   elapsed
#        0         0         0
</code>```

Body:
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}

Thanks!

Body:
Function findInterval has good performance and can get the job done.

See first how it works with just the first element of n1

i <- findInterval(n1[1], c(df.int$Upper.Limit, Inf))
j <- findInterval(n1[1], c(-Inf, df.int$Upper.Limit))

df.int$Upper.Limit[i]
#[1] 189000
n1[1]
#[1] 189041
df.int$Upper.Limit[j]
#[1] 189200

df.int$Upper.Limit[i] < n1[1] & n1[1] <= df.int$Upper.Limit[j]
#[1] TRUE

Now a general purpose solution.

subsInterval <- function(x, DF, colLimits = 1, colValues = 2, lower = TRUE){
  vec <- if(lower)
    c(DF[[colLimits]], Inf)
  else
    c(-Inf, DF[[colLimits]])
  i <- findInterval(x, vec, left.open = TRUE)
  DF[[colValues]][i]
}

system.time(
  n2 <- subsInterval(n1, df.int)
)
#     user    system   elapsed
#    0.000     0.000     0.001

system.time(
  n3 <- subsInterval(n1, df.int, lower = FALSE)
)
#     user    system   elapsed
#        0         0         0


问:
Where can i set my code Logic with React/Redux
I'm doing a reddit copy with React and Redux and I started learn react/redux recently.

So I have some practical problems while I'm developing

Question: Where is the best program part to solve that logics problems (reducer, action, etc)?

Problem:

I need to sort topics I got from API, by Date Created or Vote Score. I started fetching data from my api on actions file.

actions/actions.js:

```<code>        export function getForumTopics(currentCategory, orderBy)
    {
        return (dispatch) => {
            if(currentCategory === all_categories)
            {
                fetch(LOCAL_API_URL + '/posts', {
                    headers,
                }).then(resp => resp.json())
                  .then(data => dispatch(getTopics(orderTopicBy(data, orderBy))))
            }
    }
}
</code>```

Then, i created and import that function from utils.

utils/utils.js

```<code>    export function orderTopicBy(topics, orderBy) {
    switch(orderBy)
    {
        case 'vote-score':
        {
            topics = topics.sort(function(a,b) {
            if(a.voteScore > b.voteScore)
                    return 1;
                else if(a.voteScore < b.voteScore)
                    return -1;
                return 0;
            });
        }
        //topic-created
        default:
            topics = topics.sort(function(a,b) {
            if(a.timestamp > b.timestamp)
                    return -1;
                else if(a.timestamp < b.timestamp)
                    return 1;
                return 0;
            });
    }
    return topics;
}
</code>```

So basically, if everthing works good, I get that data, sort and then dispatch an action to my reducer.

That sort part, is it ok to be on utils/utils? because I'm using more than one time, so I think that's a good approach.

And where I do that sort test? On action as I'm doing now, or I need to do on my reducer?

答: Using utils for sorting functions is a good practice, although I wouldn't writing it inside an action. I think the most reasonable place to use that sorting is inside the component right before dispatching the action.</p>

Body:
I'm doing a reddit copy with React and Redux and I started learn react/redux recently.

So I have some practical problems while I'm developing

Question: Where is the best program part to solve that logics problems (reducer, action, etc)?

Problem:

I need to sort topics I got from API, by Date Created or Vote Score. I started fetching data from my api on actions file.

actions/actions.js:

        export function getForumTopics(currentCategory, orderBy)
    {
        return (dispatch) => {
            if(currentCategory === all_categories)
            {
                fetch(LOCAL_API_URL + '/posts', {
                    headers,
                }).then(resp => resp.json())
                  .then(data => dispatch(getTopics(orderTopicBy(data, orderBy))))
            }
    }
}

Then, i created and import that function from utils.

utils/utils.js

    export function orderTopicBy(topics, orderBy) {
    switch(orderBy)
    {
        case 'vote-score':
        {
            topics = topics.sort(function(a,b) {
            if(a.voteScore > b.voteScore)
                    return 1;
                else if(a.voteScore  b.timestamp)
                    return -1;
                else if(a.timestamp < b.timestamp)
                    return 1;
                return 0;
            });
    }
    return topics;
}

So basically, if everthing works good, I get that data, sort and then dispatch an action to my reducer.

That sort part, is it ok to be on utils/utils? because I'm using more than one time, so I think that's a good approach.

And where I do that sort test? On action as I'm doing now, or I need to do on my reducer?


问:
Python Example for KNN or K-Means Clustering
I am looking at some sample data such as this:

Data:

```<code>ID  Name    ParValue    Coupon  Maturity    Issuer  Moodys  S&P_Fitch   Grade   Risk
37833100    Apple_Inc.  1049    95  2030    Apple_Inc.  Aaa AAA Investment  Highest_Quality
02079K107   Alphabet_Inc.   1055    99  2030    Alphabet_Inc.   Aa  AA  Investment  High_Quality
11659109    Alaska_Air_Group    996 98  2030    Alaska_Air_Group    A   A   Investment  Strong
931142103   Walmart_Stores,_Inc.    1195    99  2030    Walmart_Stores,_Inc.    Baa BBB Investment  Medium_Grade
495734523   Corp._Takeover  1108    97  2021    Corp._Takeover  Ba,_B   BB,_B   Junk    Speculative
193467211   Toys_R_Us   1109    105 2021    Toys_R_Us   Caa/Ca/C    CCC/CC/C    Junk    Highly_Speculative
576300972   Enron   1062    102 2021    Enron   C   D   Junk    In_Default
983457823   Economic_Consultants_Inc.               Economic_Consultants_Inc.   Baa BBB Investment  Medium_Grade
894652378   Forecast_Backtesters_Corp.              Forecast_Backtesters_Corp.  Aaa AAA Investment  Highest_Quality
</code>```

Image:

So, if WalMart has Baa, BBB, Investment, and Medium_Grade (for Moodys, S&P_Fitch, Grade, and Risk) and Economic_Consultants_Inc. has these same attributes, I can know that Economic_Consultants_Inc. has 1195, 99, and 2030 (for ParValue, Coupon, Maturity), even though these data points are missing.

This is probably a KNN problem, but I'm thinking K-Means could be useful too.  Basically, I'm trying to figure out how to update missing data points (ParValue, Coupon, & Maturity), like the ones colored pink in the image above, based on similar attributes.  Then, I want to group similar items together (K-Means problem).  Has someone here come across a good online example of how to do this?  I looked online today and found some examples using randomly generated numbers, but my data sets will NOT have randomly generated numbers.  I would appreciate any insight into how to solve this problem.

答: also you can use, missing value imputation using impyute package.</p>

Body:
I am looking at some sample data such as this:

Data:

ID  Name    ParValue    Coupon  Maturity    Issuer  Moodys  S&P_Fitch   Grade   Risk
37833100    Apple_Inc.  1049    95  2030    Apple_Inc.  Aaa AAA Investment  Highest_Quality
02079K107   Alphabet_Inc.   1055    99  2030    Alphabet_Inc.   Aa  AA  Investment  High_Quality
11659109    Alaska_Air_Group    996 98  2030    Alaska_Air_Group    A   A   Investment  Strong
931142103   Walmart_Stores,_Inc.    1195    99  2030    Walmart_Stores,_Inc.    Baa BBB Investment  Medium_Grade
495734523   Corp._Takeover  1108    97  2021    Corp._Takeover  Ba,_B   BB,_B   Junk    Speculative
193467211   Toys_R_Us   1109    105 2021    Toys_R_Us   Caa/Ca/C    CCC/CC/C    Junk    Highly_Speculative
576300972   Enron   1062    102 2021    Enron   C   D   Junk    In_Default
983457823   Economic_Consultants_Inc.               Economic_Consultants_Inc.   Baa BBB Investment  Medium_Grade
894652378   Forecast_Backtesters_Corp.              Forecast_Backtesters_Corp.  Aaa AAA Investment  Highest_Quality

Image:

So, if WalMart has Baa, BBB, Investment, and Medium_Grade (for Moodys, S&P_Fitch, Grade, and Risk) and Economic_Consultants_Inc. has these same attributes, I can know that Economic_Consultants_Inc. has 1195, 99, and 2030 (for ParValue, Coupon, Maturity), even though these data points are missing.

This is probably a KNN problem, but I'm thinking K-Means could be useful too.  Basically, I'm trying to figure out how to update missing data points (ParValue, Coupon, & Maturity), like the ones colored pink in the image above, based on similar attributes.  Then, I want to group similar items together (K-Means problem).  Has someone here come across a good online example of how to do this?  I looked online today and found some examples using randomly generated numbers, but my data sets will NOT have randomly generated numbers.  I would appreciate any insight into how to solve this problem.


问:
In JavaScript, how do I check that only one "@" is present in an input?
I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "@" and ".". Example: name@@.com would be invalid</p>

```<code>function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('@');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
    Output("emailOutput", "The Email you have entered is valid");
    }
else {
    Output("emailOutput", "The Email you have entered is invalid");
}
}
</code>```

答:
you can use: </p>

```<code>const isEmailValid = (email) => {
    const isValid = /\S+@\S+\.\S+/.test(email);
    return isValid;
}
</code>```

Body:
I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "@" and ".". Example: name@@.com would be invalid

function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('@');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
    Output("emailOutput", "The Email you have entered is valid");
    }
else {
    Output("emailOutput", "The Email you have entered is invalid");
}
}

Body:
you can use:

const isEmailValid = (email) => {
    const isValid = /\S+@\S+\.\S+/.test(email);
    return isValid;
}


问:
how do I set folder share programmatically in vb.net
I have Client-Server environment and developed a project for Client-Server.

I need to share a folder of my Server machine programmatically using VB.NET

Please help me.

答:
I have code that looks similar to this which works on vista and win2k3 machines, but when i try it on Windows server 2008 R2 (with recent updates) it fails with an "access denied" error. I've tried your exact code above and the same result. I am an Admin on the box and I have tried disabling UAC but without any effect.

(i know this isn't an answer, I have no power to comment)

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to pass array in the url?
I'd like to filter and want to pass an array to the url.

```<code>handleFilter = (search, page = 1) => {

        const requestOption = {
            method: "GET"
        };

        fetch("http://127.0.0.1:8000/api/home?search=" + JSON.stringify(search) + "&page=" + page, requestOption)
            .then(res => res.json())
            .then(data => (
                this.setState({
                    data
                })
            ))
    };
</code>```

Just want to pass the array of data to the api to call the query

答:
I don't know if this will be what exactly you need, but I would...
a.) Join it on a strange character, and pass it as a string.
b.) On the receiving side (client or server), split on that same character. </p>

Title: How to pass array in the url?

Body:
I'd like to filter and want to pass an array to the url.

handleFilter = (search, page = 1) => {

        const requestOption = {
            method: "GET"
        };

        fetch("http://127.0.0.1:8000/api/home?search=" + JSON.stringify(search) + "&page=" + page, requestOption)
            .then(res => res.json())
            .then(data => (
                this.setState({
                    data
                })
            ))
    };

Just want to pass the array of data to the api to call the query


Title: Converting array of lists to array of dictionary

Body:
I have data as follows

{"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

I want to convert above data as follows

[{"value": 1288.1639933233453},
{"value": 1255.1777295971826},
{"value": 1250.1075681742996},
{"value": 1283.9962801780075},
{"value": 1297.4411412000093}]

Body:
You've not mentioned that lists incide list will always have 1 element, so I think it'll be better to iterate over all lists incide list comprehension to not miss values:

d = {"array": [[1288.1639933233453], [1255.1777295971826], [1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

r = [{"value": v} for e in d["array"] for v in e]

Output:

[{'value': 1288.1639933233453}, {'value': 1255.1777295971826}, {'value': 1250.1075681742996}, {'value': 1283.9962801780075}, {'value': 1297.4411412000093}]


问:
PHP: How to display select options if no value from database
I am trying to display my dropdown with a value from the database, but if the value is null I want it to show my options.

Currently it keeps showing me the blank select option.

```<code><select class="form-control col-sm-5" id="freqlevels" name="freqlevels" value="<?php if ($customerinfo['freqlevel']) { echo h($customerinfo['freqlevel']);} else { echo "" ; } ?>"">
    <option value=""></option>
    <option value="Twice Weekly">Twice Weekly</option>
    <option value="Weekly">Weekly</option>
    <option value="Fortnightly">Fortnightly</option>
    <option value="Monthly">Monthly</option>
</select>
</code>```

Please can you suggest what I should do?

答:
put your condition outside the value

```<code><?php if ($customerinfo['freqlevel']) { echo value="$customerinfo['freqlevel']";}
</code>```

hope this will resolve your problem

Body:
I am trying to display my dropdown with a value from the database, but if the value is null I want it to show my options.

Currently it keeps showing me the blank select option.

<select class="form-control col-sm-5" id="freqlevels" name="freqlevels" value="<?php if ($customerinfo['freqlevel']) { echo h($customerinfo['freqlevel']);} else { echo "" ; } ?>"">
    <option value=""></option>
    <option value="Twice Weekly">Twice Weekly</option>
    <option value="Weekly">Weekly</option>
    <option value="Fortnightly">Fortnightly</option>
    <option value="Monthly">Monthly</option>
</select>

Please can you suggest what I should do?

Body:
put your condition outside the value

<?php if ($customerinfo['freqlevel']) { echo value="$customerinfo['freqlevel']";}

hope this will resolve your problem


答:
You need to make use of conditional statements.

```<code><select name="something" id="my-select">
    <option value="0">Everyone can see me</option>

    <?php if (empty($array['some_key'])) : ?>
        <option value="1">I'm only if some_key is empty</option>
        ..etc..
    <?php endif; ?>
</select>
</code>```

Then you can check values against the option value:

```<code><option value="<?php echo $key; ?>"
        <?php echo ($key === $_POST['some_key'] ? 'selected' : ''); ?>>
    Hello, world
</option>
</code>```

Title: PHP: How to display select options if no value from database

Body:
You need to make use of conditional statements.

<select name="something" id="my-select">
    <option value="0">Everyone can see me</option>

    <?php if (empty($array['some_key'])) : ?>
        <option value="1">I'm only if some_key is empty</option>
        ..etc..
    <?php endif; ?>
</select>

Then you can check values against the option value:

<option value="<?php echo $key; ?>"
        <?php echo ($key === $_POST['some_key'] ? 'selected' : ''); ?>>
    Hello, world
</option>


问:
How to publish specific files using Publish Build Artifact Task
I am Building C# Application using Visual Studio Build In Azure Pipeline.

My solution Contains multiple project (ManagerWeb & WebAPI).

I want to Publish Two Separate Artifact ManagerWeb & WebAPI respectively.

All the required File's are present in Build.ArtifactStagingDirectory.

How I can specify a pattern using which I can get Two Separate Artifact ?
Example All the File name with WebAPI in 1st Artifact & ManagerWeb in another.

The File name from ArtifactStaging Directory are as Below

```<code>Something.Manager.WebAPI.deploy.cmd
Something.Manager.WebAPI.deploy-readme.txt
Something.Manager.WebAPI.SetParameters.xml
Something.Manager.WebAPI.SourceManifest.xml
Something.Manager.WebAPI.zip

Something.ManagerWeb.deploy.cmd
Something.ManagerWeb.deploy-readme.txt
Something.ManagerWeb.SetParameters.xml
Something.ManagerWeb.SourceManifest.xml
Something.ManagerWeb.zip
</code>```

Any Help will be appreciable.

Thanks in Advance.

答:
Add two Copy Files steps which copy;

ManagerWeb files to $(Build.ArtifactStagingDirectory)\ManagerWeb

WebAPI files to $(Build.ArtifactStagingDirectory)\WebAPI

Then have two Publish Artifact steps to;

Publish $(Build.ArtifactStagingDirectory)\ManagerWeb as ManagerWeb

Publish $(Build.ArtifactStagingDirectory)\WebAPI as WebAPI

I've mocked this up and exported the YAML as follows;

```<code>pool:
  name: Hosted VS2017
steps:
- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)\ManagerWeb'
  inputs:
    SourceFolder: 'your/path/here/ManagerWeb'
    TargetFolder: '$(Build.ArtifactStagingDirectory)\ManagerWeb'

- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)\WebAPI'
  inputs:
    SourceFolder: 'your/path/here/WebAPI'
    TargetFolder: '$(Build.ArtifactStagingDirectory)\WebAPI'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: ManagerWeb'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)\ManagerWeb'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: WebAPI'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)\WebAPI'
</code>```

Body:
I am Building C# Application using Visual Studio Build In Azure Pipeline.

My solution Contains multiple project (ManagerWeb & WebAPI).

I want to Publish Two Separate Artifact ManagerWeb & WebAPI respectively.

All the required File's are present in Build.ArtifactStagingDirectory.

How I can specify a pattern using which I can get Two Separate Artifact ?
Example All the File name with WebAPI in 1st Artifact & ManagerWeb in another.

The File name from ArtifactStaging Directory are as Below

Something.Manager.WebAPI.deploy.cmd
Something.Manager.WebAPI.deploy-readme.txt
Something.Manager.WebAPI.SetParameters.xml
Something.Manager.WebAPI.SourceManifest.xml
Something.Manager.WebAPI.zip

Something.ManagerWeb.deploy.cmd
Something.ManagerWeb.deploy-readme.txt
Something.ManagerWeb.SetParameters.xml
Something.ManagerWeb.SourceManifest.xml
Something.ManagerWeb.zip

Any Help will be appreciable.

Thanks in Advance.

Body:
Add two Copy Files steps which copy;

ManagerWeb files to $(Build.ArtifactStagingDirectory)\ManagerWeb

WebAPI files to $(Build.ArtifactStagingDirectory)\WebAPI

Then have two Publish Artifact steps to;

Publish $(Build.ArtifactStagingDirectory)\ManagerWeb as ManagerWeb

Publish $(Build.ArtifactStagingDirectory)\WebAPI as WebAPI

I've mocked this up and exported the YAML as follows;

pool:
  name: Hosted VS2017
steps:
- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)\ManagerWeb'
  inputs:
    SourceFolder: 'your/path/here/ManagerWeb'
    TargetFolder: '$(Build.ArtifactStagingDirectory)\ManagerWeb'

- task: CopyFiles@2
  displayName: 'Copy Files to: $(Build.ArtifactStagingDirectory)\WebAPI'
  inputs:
    SourceFolder: 'your/path/here/WebAPI'
    TargetFolder: '$(Build.ArtifactStagingDirectory)\WebAPI'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: ManagerWeb'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)\ManagerWeb'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: WebAPI'
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)\WebAPI'


问:
Selecting a record with several values in two tables
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

```<code>WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR
</code>```

答:
You can use the following query as well.

```<code>WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)
--
-- query starts from here
--
SELECT
    T1.COLOUR
FROM
    (
        SELECT
            T1.COLOUR,
            LISTAGG(T1.VALUESY) WITHIN GROUP(
                ORDER BY
                    T1.VALUESY
            ) VAL
        FROM
            T1
        GROUP BY
            T1.COLOUR
    ) T1,
    (
        SELECT
            T2.COLOUR,
            LISTAGG(T2.VALUESY) WITHIN GROUP(
                ORDER BY
                    T2.VALUESY
            ) VAL
        FROM
            T2
        GROUP BY
            T2.COLOUR
    ) T2
WHERE
    T1.COLOUR = T2.COLOUR
    AND T1.VAL = T2.VAL;
</code>```

Thanks.

Body:
In two tables there are records (colors) with different values. I want the result to show only the color that has all the same values in both tables. If any of the values are missing, it should be completely rejected.

Another example:

Bellow code should return only BLUE

WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)

SELECT *
FROM t1
FULL OUTER JOIN t2 ON t2.VALUESY = t1.VALUESY AND t2.COLOUR = t1.COLOUR

Body:
You can use the following query as well.

WITH
t1 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('2') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL),

t2 as (SELECT 'RED' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'RED' as COLOUR, ('3') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('1') as VALUESY FROM DUAL
       UNION
       SELECT 'BLUE' as COLOUR, ('2') as VALUESY FROM DUAL)
--
-- query starts from here
--
SELECT
    T1.COLOUR
FROM
    (
        SELECT
            T1.COLOUR,
            LISTAGG(T1.VALUESY) WITHIN GROUP(
                ORDER BY
                    T1.VALUESY
            ) VAL
        FROM
            T1
        GROUP BY
            T1.COLOUR
    ) T1,
    (
        SELECT
            T2.COLOUR,
            LISTAGG(T2.VALUESY) WITHIN GROUP(
                ORDER BY
                    T2.VALUESY
            ) VAL
        FROM
            T2
        GROUP BY
            T2.COLOUR
    ) T2
WHERE
    T1.COLOUR = T2.COLOUR
    AND T1.VAL = T2.VAL;

Thanks.


问:
gulp 4 vinyl-ftp Unable to make data connection
I'm facing problem with uploading files, randomly it stops with different kind of errors: Unable to make data connection at Socket. (/aaa/node_modules/ftp/lib/connection.js:935:10) or Error: Client aborted. Sometimes it works when launched e.g. 10 times

```<code>var deployPaths =
{
    'aaa/public_html': [],
    'bbb/public_html': [],
};

var defaultTasks = [];

function deployMultiple(key) {

    var conn = ftp.create({
        host: 'site',
        user: 'xxxx',
        password: 'xxxxxx',
        parallel: 10,
        maxConnections: 5,
        log: plugins.util.log
    });

    var globs = [

        path + '/some_path/**',
        '!' + path + '/some_path/aa/**',
        '!' + path + '/some_path/bb/**',
        path + '/administrator/some_path/**',

    ];

    // using base = '.' will transfer everything to /public_html correctly
    // turn off buffering in gulp.src for best performance
    return gulp.src(globs, {base: path, buffer: false})
        .pipe(conn.newer(key)) // only upload newer files
        .pipe(conn.dest(key));

}

gulp.task('deploy-task', function (cb) {
    for (var key in deployPaths) {
        deployMultiple(key);
        cb();
    }

});

gulp.task('deploy',gulp.series('clean','git_export','deploy-task'));
</code>```

Please help, Thank you

答:
@miojamo

I tested my upload with the same error against 2 different hosting providers with vinyl-ftp and FileZilla and found that this the error happens only for one of the providers.

In short:

This is more likely to happen with very long uploads (~22,000 files in my case) due to the error on a provider's side.

At the same time being tested at another provider gives the other error (Timed out while making data connection...) instead of Unable to make data connection....

See my detailed explanations here in vinyl-ftp Github repo issue.

Hope that sheds some more light on the issue.

Body:
I'm facing problem with uploading files, randomly it stops with different kind of errors: Unable to make data connection at Socket. (/aaa/node_modules/ftp/lib/connection.js:935:10) or Error: Client aborted. Sometimes it works when launched e.g. 10 times

var deployPaths =
{
    'aaa/public_html': [],
    'bbb/public_html': [],
};

var defaultTasks = [];

function deployMultiple(key) {

    var conn = ftp.create({
        host: 'site',
        user: 'xxxx',
        password: 'xxxxxx',
        parallel: 10,
        maxConnections: 5,
        log: plugins.util.log
    });

    var globs = [

        path + '/some_path/**',
        '!' + path + '/some_path/aa/**',
        '!' + path + '/some_path/bb/**',
        path + '/administrator/some_path/**',

    ];

    // using base = '.' will transfer everything to /public_html correctly
    // turn off buffering in gulp.src for best performance
    return gulp.src(globs, {base: path, buffer: false})
        .pipe(conn.newer(key)) // only upload newer files
        .pipe(conn.dest(key));

}

gulp.task('deploy-task', function (cb) {
    for (var key in deployPaths) {
        deployMultiple(key);
        cb();
    }

});

gulp.task('deploy',gulp.series('clean','git_export','deploy-task'));

Please help, Thank you


问:
SUM of two rows returned by SQL subquery
I have created the following SQL query

```<code>SELECT ae.[intEntitlementID]
      ,SUM(decIncrease) - SUM([decDecrease]) as quantity
                ,(SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS VALUE
    ,(SUM(decIncrease) - SUM([decDecrease])) *
                (SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS TOTAL

  FROM [tblAllocationEvent] ae

  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID

  HAVING SUM(decIncrease) - SUM([decDecrease]) > 0
</code>```

Which returns the following

I now need to find the sum of the two rows on the TOTAL column.

I want the following data to be output. 73046.908322 + 1150.946103

Does anybody have any tips on how to SUM the two results returned by the sub query?

Thanks

答:
use ROLLUP

```<code>SELECT i, count(*) as c, sum(i) as s
FROM TEST
WHERE i<5
GROUP BY ROLLUP(i)
</code>```

gives:

```<code>i   c   s
1   1   1
2   1   2
3   1   3
4   1   4
NULL    4   10
</code>```

Body:
I have created the following SQL query

SELECT ae.[intEntitlementID]
      ,SUM(decIncrease) - SUM([decDecrease]) as quantity
                ,(SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS VALUE
    ,(SUM(decIncrease) - SUM([decDecrease])) *
                (SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS TOTAL

  FROM [tblAllocationEvent] ae

  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID

  HAVING SUM(decIncrease) - SUM([decDecrease]) > 0

Which returns the following

I now need to find the sum of the two rows on the TOTAL column.

I want the following data to be output. 73046.908322 + 1150.946103

Does anybody have any tips on how to SUM the two results returned by the sub query?

Thanks

Body:
use ROLLUP

SELECT i, count(*) as c, sum(i) as s
FROM TEST
WHERE i<5
GROUP BY ROLLUP(i)

gives:

i   c   s
1   1   1
2   1   2
3   1   3
4   1   4
NULL    4   10


答:
I recognise this is not what you are asking (and may not be relevant) but in-browser validation of an email address is achievable via:

```<code><input type="email" />
</code>```

which degrades gracefully to

```<code><input type="text" />
</code>```

Title: In JavaScript, how do I check that only one "@" is present in an input?

Body:
I recognise this is not what you are asking (and may not be relevant) but in-browser validation of an email address is achievable via:

<input type="email" />

which degrades gracefully to

<input type="text" />


问:
PHP - Indirect modification of overloaded property
I know this question has been asked several times, but none of them have a real answer for a workaround. Maybe there's one for my specific case.

I'm building a mapper class which uses the magic method __get() to lazy load other objects. It looks something like this:

```<code>public function __get ( $index )
{
    if ( isset ($this->vars[$index]) )
    {
        return $this->vars[$index];
    }

    // $index = 'role';
    $obj = $this->createNewObject ( $index );

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

In my code I do:

```<code>$user = createObject('user');
$user->role->rolename;
</code>```

This works so far. The User object doesn't have a property called 'role', so it uses the magic __get() method to create that object and it returns its property from the 'role' object.

But when i try to modify the 'rolename':

```<code>$user = createUser();
$user->role->rolename = 'Test';
</code>```

Then it gives me the following error:

Notice: Indirect modification of overloaded property has no effect

Not sure if this is still some bug in PHP or if it's "expected behaviour", but in any case it doesn't work the way I want. This is really a show stopper for me... Because how on earth am I able to change the properties of the lazy loaded objects??

EDIT:

The actual problem only seems to occur when I return an array which contains multiple objects.

I've added an example piece of code which reproduces the problem:

http://codepad.org/T1iPZm9t

You should really run this in your PHP environment the really see the 'error'. But there is something really interesting going on here.

I try to change the property of an object, which gives me the notice 'cant change overloaded property'. But if I echo the property after that I see that it actually DID change the value... Really weird...

答:
I agree with VinnyD that what you need to do is add "&" in front of your __get function, as to make it to return the needed result as a reference:

```<code>public function &__get ( $propertyname )
</code>```

But be aware of two things:

1) You should also do

```<code>return &$something;
</code>```

or you might still be returning a value and not a reference...

2) Remember that in any case that __get returns a reference this also means that the corresponding __set will NEVER be called; this is because php resolves this by using the reference returned by __get, which is called instead!

So:

```<code>$var = $object->NonExistentArrayProperty;
</code>```

means __get is called and, since __get has &__get and return &$something, $var is now, as intended, a reference to the overloaded property...

```<code>$object->NonExistentArrayProperty = array();
</code>```

works as expected and __set is called as expected...

But:

```<code>$object->NonExistentArrayProperty[] = $value;
</code>```

or

```<code>$object->NonExistentArrayProperty["index"] = $value;
</code>```

works as expected in the sense that the element will be correctly added or modified in the overloaded array property, BUT __set WILL NOT BE CALLED: __get will be called instead!

These two calls would NOT work if not using &__get and return &$something, but while they do work in this way, they NEVER call __set, but always call __get.

This is why I decided to return a reference

```<code>return &$something;
</code>```

when $something is an array(), or when the overloaded property has no special setter method, and instead return a value

```<code>return $something;
</code>```

when $something is NOT an array or has a special setter function.

In any case, this was quite tricky to understand properly for me! :)

Body:
I know this question has been asked several times, but none of them have a real answer for a workaround. Maybe there's one for my specific case.

I'm building a mapper class which uses the magic method __get() to lazy load other objects. It looks something like this:

public function __get ( $index )
{
    if ( isset ($this->vars[$index]) )
    {
        return $this->vars[$index];
    }

    // $index = 'role';
    $obj = $this->createNewObject ( $index );

    return $obj;
}

In my code I do:

$user = createObject('user');
$user->role->rolename;

This works so far. The User object doesn't have a property called 'role', so it uses the magic __get() method to create that object and it returns its property from the 'role' object.

But when i try to modify the 'rolename':

$user = createUser();
$user->role->rolename = 'Test';

Then it gives me the following error:

Notice: Indirect modification of overloaded property has no effect

Not sure if this is still some bug in PHP or if it's "expected behaviour", but in any case it doesn't work the way I want. This is really a show stopper for me... Because how on earth am I able to change the properties of the lazy loaded objects??

EDIT:

The actual problem only seems to occur when I return an array which contains multiple objects.

I've added an example piece of code which reproduces the problem:

http://codepad.org/T1iPZm9t

You should really run this in your PHP environment the really see the 'error'. But there is something really interesting going on here.

I try to change the property of an object, which gives me the notice 'cant change overloaded property'. But if I echo the property after that I see that it actually DID change the value... Really weird...

Body:
I agree with VinnyD that what you need to do is add "&" in front of your __get function, as to make it to return the needed result as a reference:

public function &__get ( $propertyname )

But be aware of two things:

1) You should also do

return &$something;

or you might still be returning a value and not a reference...

2) Remember that in any case that __get returns a reference this also means that the corresponding __set will NEVER be called; this is because php resolves this by using the reference returned by __get, which is called instead!

So:

$var = $object->NonExistentArrayProperty;

means __get is called and, since __get has &__get and return &$something, $var is now, as intended, a reference to the overloaded property...

$object->NonExistentArrayProperty = array();

works as expected and __set is called as expected...

But:

$object->NonExistentArrayProperty[] = $value;

or

$object->NonExistentArrayProperty["index"] = $value;

works as expected in the sense that the element will be correctly added or modified in the overloaded array property, BUT __set WILL NOT BE CALLED: __get will be called instead!

These two calls would NOT work if not using &__get and return &$something, but while they do work in this way, they NEVER call __set, but always call __get.

This is why I decided to return a reference

return &$something;

when $something is an array(), or when the overloaded property has no special setter method, and instead return a value

return $something;

when $something is NOT an array or has a special setter function.

In any case, this was quite tricky to understand properly for me! :)


问:
How to display drop down menu when any text from whole page is selected?
I want to display selection list menu when any text from any element is selected. I used "onselect" attribute but it seems to be only working only with "input" element. How can i show list similar to list when we right click anything on browser for every element?

It works when i select text in input element and not when i select text from h1 element.

```<code><!DOCTYPE html>
<html>
<body id="myText">

<h1 onselect="myFunction()">Select some of the text: <input type="text" value="Hello world!" /></h1>

<script>
function myFunction() {
  alert("You selected some text!");
}
</script>

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

答:
The onselect works only for input and textarea - https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onselect.

Instead you can use onselectionchange - https://developer.mozilla.org/en-US/docs/Web/API/Document/selectionchange_event.

document.addEventListener('selectionchange', () => {
    const {baseOffset, extentOffset} = document.getSelection();
    const node = document.getSelection().anchorNode;
    if(node) {
        const selectedText = node.data.slice(baseOffset, extentOffset);
        console.log(selectedText);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Select some of the text: </h1></code>```

Body:
I want to display selection list menu when any text from any element is selected. I used "onselect" attribute but it seems to be only working only with "input" element. How can i show list similar to list when we right click anything on browser for every element?

It works when i select text in input element and not when i select text from h1 element.

<!DOCTYPE html>

Select some of the text: <input type="text" value="Hello world!" />

Body:
The onselect works only for input and textarea - https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onselect.

Instead you can use onselectionchange - https://developer.mozilla.org/en-US/docs/Web/API/Document/selectionchange_event.

document.addEventListener('selectionchange', () => {
    const {baseOffset, extentOffset} = document.getSelection();
    const node = document.getSelection().anchorNode;
    if(node) {
        const selectedText = node.data.slice(baseOffset, extentOffset);
        console.log(selectedText);
    }
});

<h1>Select some of the text: </h1>


问:
CSS letter-spacing together with line-through
Is there any css/js solution how to center line through the text while using letter-spacing? While single line text it is possible to accomplish centered line-through thanks to pseudo element ::before or ::after, but that's not possible on block elements like
 or
.

h2, p {
  letter-spacing: 1em;
  text-decoration: line-through;
  text-align: center;
}

p {
  letter-spacing: .5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Random text</h2>
<p>Lorem ipsum dolor sit amet, at nemore aperiri cum. Regione honestatis ei quo, ne eos aliquid mediocrem, ne viris quodsi epicuri vel. Ex dolorem atomorum dissentiunt nam, iudico minimum cotidieque eum et, has novum mnesarchum id. Libris blandit liberavisse mei in. Ius viris posidonium ei, ut quas viris albucius eum, mei eu indoctum reformidans. Et usu sumo invidunt, cu vix veri dolore propriae.</p></code>```

答:
Here is an idea where you can rely on background and box-decoration-break to create the line-through and you can easily adjust its size and position. You will basically remove one letter spacing from the total width.

It's important to note that the background need to be applied to an inline element:

p {
  letter-spacing: .5em;
  text-align:center;
}

p span {
  background:
    linear-gradient(#000,#000) /* Coloration */
    0 calc(50% + 0.2ex) /* position */
    /
    calc(100% - .5em) 1px  /* width height */
    no-repeat;
 -webkit-box-decoration-break: clone;
  box-decoration-break: clone;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><span>Lorem ipsum dolor sit amet, at nemore aperiri cum. Regione honestatis ei quo, ne eos aliquid mediocrem, ne viris quodsi epicuri vel. Ex dolorem atomorum dissentiunt nam, iudico minimum cotidieque eum et, has novum mnesarchum id. Libris blandit liberavisse mei in. Ius viris posidonium ei, ut quas viris albucius eum, mei eu indoctum reformidans. Et usu sumo invidunt, cu vix veri dolore propriae.</span></p></code>```

Body:
Is there any css/js solution how to center line through the text while using letter-spacing? While single line text it is possible to accomplish centered line-through thanks to pseudo element ::before or ::after, but that's not possible on block elements like
 or
.

h2, p {
  letter-spacing: 1em;
  text-decoration: line-through;
  text-align: center;
}

p {
  letter-spacing: .5em;
}

Random text

Lorem ipsum dolor sit amet, at nemore aperiri cum. Regione honestatis ei quo, ne eos aliquid mediocrem, ne viris quodsi epicuri vel. Ex dolorem atomorum dissentiunt nam, iudico minimum cotidieque eum et, has novum mnesarchum id. Libris blandit liberavisse mei in. Ius viris posidonium ei, ut quas viris albucius eum, mei eu indoctum reformidans. Et usu sumo invidunt, cu vix veri dolore propriae.

Body:
Here is an idea where you can rely on background and box-decoration-break to create the line-through and you can easily adjust its size and position. You will basically remove one letter spacing from the total width.

It's important to note that the background need to be applied to an inline element:

p {
  letter-spacing: .5em;
  text-align:center;
}

p span {
  background:
    linear-gradient(#000,#000) /* Coloration */
    0 calc(50% + 0.2ex) /* position */
    /
    calc(100% - .5em) 1px  /* width height */
    no-repeat;
 -webkit-box-decoration-break: clone;
  box-decoration-break: clone;
}

<p><span>Lorem ipsum dolor sit amet, at nemore aperiri cum. Regione honestatis ei quo, ne eos aliquid mediocrem, ne viris quodsi epicuri vel. Ex dolorem atomorum dissentiunt nam, iudico minimum cotidieque eum et, has novum mnesarchum id. Libris blandit liberavisse mei in. Ius viris posidonium ei, ut quas viris albucius eum, mei eu indoctum reformidans. Et usu sumo invidunt, cu vix veri dolore propriae.</span></p>


问:
ADO.Net Destination connector
I'm looking into existing packages in SSIS for my team to streamline some of the ETL, and I came across a symbol which do not correspond to the connectors in the existing library. Has anyone come across the symbol that has the label of ADO destination below?

From what I have seen thus far, ADO.Net Destination has a specific connector with its own symbol like the below

The package is purely extracting source data from oracle DB, and then re-ingest it to another oracle DB using the ADO.Net connectors.

答:
I think that the first image is showing a custom component (based on the icon) and the label ADO destination is meaningless since it is wrote by the developer.

To check the component type, click on it and press F4 to show the properties tab, then check the component type on the top of properties.

Title: ADO.Net Destination connector


问:
Hide swagger bad response example model in net core 2.2
I upgrade my netcore 2.1 project to 2.2 and i have a problem with my swagger page.

Previously in swagger bad response it only show "Bad Request" without the model.

But after i upgraded to net core 2.2 there is a model shown in the bad request example.The image is below.

How do i hide it so that it just show the "Bad request".

I already tested using CustomApiConvention but no success so far.

```<code>    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesDefaultResponseType]
    public async Task<ActionResult<Employee>> GetEmployee(int id)
    {
        var employee = await _context.Employee.FindAsync(id);

        if (employee == null)
        {
            return NotFound();
        }

        return employee;
    }
</code>```

How do i hide it so that it just show the "Bad request"?

答:
To anyone who got the same problem. Just add this to your code.

```<code>services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(options =>
{
    options.SuppressMapClientErrors = true;
});
</code>```

This will disable ProblemDetails response.

https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes

Body:
I upgrade my netcore 2.1 project to 2.2 and i have a problem with my swagger page.

Previously in swagger bad response it only show "Bad Request" without the model.

But after i upgraded to net core 2.2 there is a model shown in the bad request example.The image is below.

How do i hide it so that it just show the "Bad request".

I already tested using CustomApiConvention but no success so far.

    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesDefaultResponseType]
    public async Task<ActionResult<Employee>> GetEmployee(int id)
    {
        var employee = await _context.Employee.FindAsync(id);

        if (employee == null)
        {
            return NotFound();
        }

        return employee;
    }

How do i hide it so that it just show the "Bad request"?

Body:
To anyone who got the same problem. Just add this to your code.

services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(options =>
{
    options.SuppressMapClientErrors = true;
});

This will disable ProblemDetails response.

https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes


问:
Accessing columns by primary key from another table
I'm a very beginner in java and am trying to build a simple API with spring. I can't find any clear description on how to implement an intuitive pk-fk relationship in the model files. The api is a restaurant application and items from the menu table have to be used in orders and shoppingcart.

I have written all the table definitions in the model files such as Menu, Prices, Orders, ShoppingCart and I need to use columns from Menu table that are not pk (such as item name) in the Orders table. As I understand a relationship can only be set with pk, but how do I access the other columns in Menu table from Orders table through pk?

```<code>@Entity
public class Menu {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    private String name;
    private float size;
    private String ingredients;
    private String dishCat;
    private String drinkCat;
    private Boolean drink;
    private String remarks;
    private String offer;

protected Menu() {

}

public Menu(String name, float size, String ingredients, String dishCat, String drinkCat, Boolean drink, String offer, String remarks) {
    this.name = name;
    this.size = size;
    this.ingredients = ingredients;
    this.dishCat = dishCat;
    this.drinkCat = drinkCat;
    this.drink = drink;
    this.offer = offer;
    this.remarks = remarks;
}

@Override
public String toString() {
    if (drink == false) {
        return String.format("%d. %s: %s - %s. Size: %f g. Ingredients: %s. Category: %s.", id, dishCat, name, offer, size, ingredients, remarks);
    }
    else {
        return String.format("%d. %s: %s - %s. Size: %f ml.", id, drinkCat, name, offer, size);
    }
}
    // Getters and setters, accessor methods
}
</code>```

答:
Once you have the ID of the Menu, you can call your DAO to retrieve it from the DB. Alternatively, you could add a transcient field in Order that you fill automatically when you retrieve the order:

```<code>@Transcient
 private transcient Menu menu;
</code>```

Anyway your Menu should have all its columns annotated with @Column.

Body:
I'm a very beginner in java and am trying to build a simple API with spring. I can't find any clear description on how to implement an intuitive pk-fk relationship in the model files. The api is a restaurant application and items from the menu table have to be used in orders and shoppingcart.

I have written all the table definitions in the model files such as Menu, Prices, Orders, ShoppingCart and I need to use columns from Menu table that are not pk (such as item name) in the Orders table. As I understand a relationship can only be set with pk, but how do I access the other columns in Menu table from Orders table through pk?

@Entity
public class Menu {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    private String name;
    private float size;
    private String ingredients;
    private String dishCat;
    private String drinkCat;
    private Boolean drink;
    private String remarks;
    private String offer;

protected Menu() {

}

public Menu(String name, float size, String ingredients, String dishCat, String drinkCat, Boolean drink, String offer, String remarks) {
    this.name = name;
    this.size = size;
    this.ingredients = ingredients;
    this.dishCat = dishCat;
    this.drinkCat = drinkCat;
    this.drink = drink;
    this.offer = offer;
    this.remarks = remarks;
}

@Override
public String toString() {
    if (drink == false) {
        return String.format("%d. %s: %s - %s. Size: %f g. Ingredients: %s. Category: %s.", id, dishCat, name, offer, size, ingredients, remarks);
    }
    else {
        return String.format("%d. %s: %s - %s. Size: %f ml.", id, drinkCat, name, offer, size);
    }
}
    // Getters and setters, accessor methods
}

Body:
Once you have the ID of the Menu, you can call your DAO to retrieve it from the DB. Alternatively, you could add a transcient field in Order that you fill automatically when you retrieve the order:

@Transcient
 private transcient Menu menu;

Anyway your Menu should have all its columns annotated with @Column.


问:
Could not connect to SMTP host: outlook.office365.com, port: 587; nested exception is: java.net.SocketException: Permission denied: connect
I have written code that sends email using outlook.office365.com. When I am running the program getting the following error.

javax.mail.MessagingException: Could not connect to SMTP host: outlook.office365.com, port: 587;
   nested exception is:

java.net.SocketException: Permission denied: connect

```<code>private static final String SERVIDOR_SMTP = "outlook.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx@xxx.com"; //Cofig  Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password

private final String from = "xxxx@xxx.com";
private final String to = "xxxx@xxx.com";

private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";

public void sendEmail() {
    final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
        }

    });

    try {
        final Message message = new MimeMessage(session);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject);
        message.setText(messageContent);
        message.setSentDate(new Date());
        Transport.send(message);
    } catch (final MessagingException ex) {
       System.out.println(" "+ex);
    }
}

public Properties getEmailProperties() {
    final Properties config = new Properties();
    config.put("mail.smtp.auth", "true");
    config.put("mail.smtp.starttls.enable", "true");
    config.put("mail.smtp.host", SERVIDOR_SMTP);
    config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
    return config;
}

public static void main(final String[] args) {
    new SendAttachmentInEmail().sendEmail();
}
</code>```

答:
I think, you don't have permission for access your email. For example while i try in my gmail account, if i don't open the setting that show at below, i get a authorization failed but if i open the setting, i can send e-mail with your code.

Please check your e-mail permission and settings.

settings picture

Body:
I have written code that sends email using outlook.office365.com. When I am running the program getting the following error.

javax.mail.MessagingException: Could not connect to SMTP host: outlook.office365.com, port: 587;
   nested exception is:

java.net.SocketException: Permission denied: connect

private static final String SERVIDOR_SMTP = "outlook.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx@xxx.com"; //Cofig  Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password

private final String from = "xxxx@xxx.com";
private final String to = "xxxx@xxx.com";

private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";

public void sendEmail() {
    final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
        }

    });

    try {
        final Message message = new MimeMessage(session);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject);
        message.setText(messageContent);
        message.setSentDate(new Date());
        Transport.send(message);
    } catch (final MessagingException ex) {
       System.out.println(" "+ex);
    }
}

public Properties getEmailProperties() {
    final Properties config = new Properties();
    config.put("mail.smtp.auth", "true");
    config.put("mail.smtp.starttls.enable", "true");
    config.put("mail.smtp.host", SERVIDOR_SMTP);
    config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
    return config;
}

public static void main(final String[] args) {
    new SendAttachmentInEmail().sendEmail();
}


答:
If you want send it exactly as GET method (not Post), you can form your URL like this:

```<code>"http://127.0.0.1:8000/api/home?search[]=value1&search[]=value2&search[]=value3"
</code>```

That is if you don't want send JSON string.

And what the problem with JSON version or POST method?

Title: How to pass array in the url?

Body:
I'd like to filter and want to pass an array to the url.

handleFilter = (search, page = 1) => {

        const requestOption = {
            method: "GET"
        };

        fetch("http://127.0.0.1:8000/api/home?search=" + JSON.stringify(search) + "&page=" + page, requestOption)
            .then(res => res.json())
            .then(data => (
                this.setState({
                    data
                })
            ))
    };

Just want to pass the array of data to the api to call the query

Body:
If you want send it exactly as GET method (not Post), you can form your URL like this:

"http://127.0.0.1:8000/api/home?search[]=value1&search[]=value2&search[]=value3"

That is if you don't want send JSON string.

And what the problem with JSON version or POST method?


问:
Overriding protected methods in Java
Test.java

```<code>package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}
</code>```

A.java:

```<code>package a;
public class A {
    protected void test() { }
}
</code>```

B.java:

```<code>package b;
public class B extends a.A {
    protected void test() { }
}
</code>```

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.

答:
Here you go JLS on protected keyword:
JLS protected description and JLS protected example.

Basically a protected modifier means that you can access field / method / ... 1) in a subclass of given class and 2) from the classes in the same package.

Because of 2) new A().test() works. But new B().test() doesn't work, because class B is in different package.

Title: Overriding protected methods in Java

Body:
Test.java

package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}

A.java:

package a;
public class A {
    protected void test() { }
}

B.java:

package b;
public class B extends a.A {
    protected void test() { }
}

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.


问:
Print multiple row outputs as column values
Suppose

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

print('Group  '+ A)
print('Number  '+ B)
print('Angle  '+ C)
print('Max value  ' + D)
</code>```

My actual output is in this form,

```<code>Group  Second
Number  Odd
Angle  Inclined
Max Value  Maximum

</code>```

Expected Output:
I want to arrange these indexes as column labels and store the output in a csv file as shown:

Like this if there are 'N' values, csv file should store all values 1 below the other

答:
Create DataFrame by constructor:

```<code>A='First'
B='Random'
C='Degree'
D='Largest'

c = ['Group', 'Number','Angle','Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)
   Group  Number   Angle Max value
0  First  Random  Degree   Largest
</code>```

And then DataFrame.to_csv:

```<code>df.to_csv('file', index=False)
</code>```

Or use python only:

```<code>import csv
with open("out.csv","w") as f:
    wr = csv.writer(f, delimiter=',')
    wr.writerow(c)
    wr.writerow([A,B,C,D])
</code>```

Body:
Suppose

A='First'
B='Random'
C='Degree'
D='Largest'

A='Second'
B='Odd'
C='Inclined'
D='Maximum'

print('Group  '+ A)
print('Number  '+ B)
print('Angle  '+ C)
print('Max value  ' + D)

My actual output is in this form,

Group  Second
Number  Odd
Angle  Inclined
Max Value  Maximum

Expected Output:
I want to arrange these indexes as column labels and store the output in a csv file as shown:

Like this if there are 'N' values, csv file should store all values 1 below the other

Body:
Create DataFrame by constructor:

A='First'
B='Random'
C='Degree'
D='Largest'

c = ['Group', 'Number','Angle','Max value']

df = pd.DataFrame([[A, B, C, D]], columns=c)
print (df)
   Group  Number   Angle Max value
0  First  Random  Degree   Largest

And then DataFrame.to_csv:

df.to_csv('file', index=False)

Or use python only:

import csv
with open("out.csv","w") as f:
    wr = csv.writer(f, delimiter=',')
    wr.writerow(c)
    wr.writerow([A,B,C,D])


问:
How to update value inside object from inputText
Sorry guys i'am still learning react native and i want update value of each qty(quantity) item from input, so i have this state,

```<code>this.state={
 selectedObject={
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },

}
</code>```

then i have this function to render the TextInput,

```<code>renderPage(){
 return this.state.selectedObject.items.map(item ,i)=>
   <View style={{margin:15}}>
     <Text>Name: {item.name}</Text>
     <TextInput style={styles.input} keyboardType='numeric' maxLength={10}
       value={?}
       onChangeText={?}
      }}/>
   </View>
  )
}
</code>```

and i dont know what to do inside the value and onchangeText,

This is what i tried, in the TextInput

```<code>renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
         value={itemqty[i].qty}
         onChangeText={(qty)=>{
         this.setState({items[i].qty: qty});
     }}/>
  </View>
  )
}
</code>```

after trying this i'am aware that value can't have '[i]' aswell as in the setState. Because i was trying so that the value qty will go to the respected items qty as well when setState it.

So what i expect is i can change the value of the quantity of the items from the input that are available in this case there are 2, but later on it can be 3,4,5,6 items with qty in each one and set it to the respected state.

Thank you

答:
You have to pass the modified state properties to setState.

PS: I had to update in order to reflect Junius L. comment about not changing component state.

```<code>renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
        value={item.qty}
        onChangeText={(qty)=>{
          let newSelectedObject = {...this.state.selectedObject};
          newSelectedObject.items = [...newSelectedObject.items];
          newSelectedObject.items[i] = {...newSelectedObject.items[i], qty};
          this.setState({selectedObject: newSelectedObject});
        }}/>
    </View>
  )
}
</code>```

Also, selectedObject is a state property. So the correct is

```<code>this.state={
 selectedObject:{
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },
}
</code>```

Body:
Sorry guys i'am still learning react native and i want update value of each qty(quantity) item from input, so i have this state,

this.state={
 selectedObject={
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },

}

then i have this function to render the TextInput,

renderPage(){
 return this.state.selectedObject.items.map(item ,i)=>
   <View style={{margin:15}}>
     <Text>Name: {item.name}</Text>
     <TextInput style={styles.input} keyboardType='numeric' maxLength={10}
       value={?}
       onChangeText={?}
      }}/>
   </View>
  )
}

and i dont know what to do inside the value and onchangeText,

This is what i tried, in the TextInput

renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
         value={itemqty[i].qty}
         onChangeText={(qty)=>{
         this.setState({items[i].qty: qty});
     }}/>
  </View>
  )
}

after trying this i'am aware that value can't have '[i]' aswell as in the setState. Because i was trying so that the value qty will go to the respected items qty as well when setState it.

So what i expect is i can change the value of the quantity of the items from the input that are available in this case there are 2, but later on it can be 3,4,5,6 items with qty in each one and set it to the respected state.

Thank you

Body:
You have to pass the modified state properties to setState.

PS: I had to update in order to reflect Junius L. comment about not changing component state.

renderPage(){
  const itemqty = this.state.selectedObject.items;
  return itemqty.map((item,i)=>
    <View style={{margin:15}}>
      <Text>Name: {item.name}</Text>
      <TextInput style={styles.input} keyboardType='numeric'
        value={item.qty}
        onChangeText={(qty)=>{
          let newSelectedObject = {...this.state.selectedObject};
          newSelectedObject.items = [...newSelectedObject.items];
          newSelectedObject.items[i] = {...newSelectedObject.items[i], qty};
          this.setState({selectedObject: newSelectedObject});
        }}/>
    </View>
  )
}

Also, selectedObject is a state property. So the correct is

this.state={
 selectedObject:{
   otherAttributes:'',
   items:[
     {name:'a',qty:''},
     {name:'b',qty:''},
   ],
  },
}


问:
How can I populate Array with Ms SQL query results in swift?
I'm new to writing programs with Xcode.
I am doing the MS SQL connection successfully, but how can I populate an Array variable with a defined query result. I want to show the string values that I populate to the Array variable on TableView.
I've come up to my code:

```<code>import UIKit
class SecondViewController: UIViewController,SQLClientDelegate {
    func error(_ error: String!, code: Int32, severity: Int32) {
        print("\(error!) \(code) \(severity)")
}
    @IBOutlet weak var userListTableView: UITableView!
    var client:SQLClient!
    var uNames: [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        client = SQLClient.sharedInstance()!
//Initially we call the DB data in internal memory.
        strIP = UserDefaults.standard.string(forKey: "DBServerIP")!
        strDBName = UserDefaults.standard.string(forKey: "DBName")!
        strUName = UserDefaults.standard.string(forKey: "DBUser")!
        strPass = UserDefaults.standard.string(forKey: "DBPass")!
}
    @IBAction func btnUserAct(_ sender: Any) {
        client = SQLClient.sharedInstance()!
        client.delegate = self
        client.connect(strIP,username: strUName,password: strPass,database: strDBName){ success in
            if success {
                self.client.execute("Select UserId from Usertbl order by Id") {
                results in
                    for table in results as! [[[String:AnyObject]]] {
                        for row in table {
                            for (columnName, value) in row {
                                print(value)
//Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
//How can I populate these values to the uNames Array variable?
}}}
                    self.client.disconnect()
}}}}}
extension SecondViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return uNames.count
}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = uNames[indexPath.row]
        return cell
}}
</code>```

I need your help.

答:
The SQLClien seems to return Objective-C classes like NSArray, NSNumber etc hence value is of type AnyObject. Assuming that the underlying column is of type int and then value is of type NSNumber I think you will need to convert it to a String in two steps

```<code>if let intVal = value as? Int {
    self.uNames.append(String(intVal)
}
</code>```

Body:
I'm new to writing programs with Xcode.
I am doing the MS SQL connection successfully, but how can I populate an Array variable with a defined query result. I want to show the string values that I populate to the Array variable on TableView.
I've come up to my code:

import UIKit
class SecondViewController: UIViewController,SQLClientDelegate {
    func error(_ error: String!, code: Int32, severity: Int32) {
        print("\(error!) \(code) \(severity)")
}
    @IBOutlet weak var userListTableView: UITableView!
    var client:SQLClient!
    var uNames: [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        client = SQLClient.sharedInstance()!
//Initially we call the DB data in internal memory.
        strIP = UserDefaults.standard.string(forKey: "DBServerIP")!
        strDBName = UserDefaults.standard.string(forKey: "DBName")!
        strUName = UserDefaults.standard.string(forKey: "DBUser")!
        strPass = UserDefaults.standard.string(forKey: "DBPass")!
}
    @IBAction func btnUserAct(_ sender: Any) {
        client = SQLClient.sharedInstance()!
        client.delegate = self
        client.connect(strIP,username: strUName,password: strPass,database: strDBName){ success in
            if success {
                self.client.execute("Select UserId from Usertbl order by Id") {
                results in
                    for table in results as! [[[String:AnyObject]]] {
                        for row in table {
                            for (columnName, value) in row {
                                print(value)
//Here, UserId data appears successfully in the Xcode Debug area. So connection successful.
//How can I populate these values to the uNames Array variable?
}}}
                    self.client.disconnect()
}}}}}
extension SecondViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return uNames.count
}
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = uNames[indexPath.row]
        return cell
}}

I need your help.

Body:
The SQLClien seems to return Objective-C classes like NSArray, NSNumber etc hence value is of type AnyObject. Assuming that the underlying column is of type int and then value is of type NSNumber I think you will need to convert it to a String in two steps

if let intVal = value as? Int {
    self.uNames.append(String(intVal)
}


问:
How to show event at frontend
I could successfully emitted event, but I don't know how to show those event.

My event is this

```<code>  event Sell (
    address indexed _buyer,
    uint256 indexed _value
  );
</code>```

I could get all event in console.

```<code>const event = await tokenSale.events.Sell({}, {
  fromBlock: 0,
  toBlock: 'latest',
})
event.on("data", (data) => console.log("data", data))
</code>```

I want to show _value in frontend.

Could you give me any advise, please?

答: There are lots of ways to render values in the front end. It depends on what language/library you are using. If you are using React, a nice tool for passing contract data to the front end is Drizzle</p>

Title: How to show event at frontend

Body:
I could successfully emitted event, but I don't know how to show those event.

My event is this

  event Sell (
    address indexed _buyer,
    uint256 indexed _value
  );

I could get all event in console.

const event = await tokenSale.events.Sell({}, {
  fromBlock: 0,
  toBlock: 'latest',
})
event.on("data", (data) => console.log("data", data))

I want to show _value in frontend.

Could you give me any advise, please?


问:
How to scale the page size from A3 to A4 in itext7 C #?
I tried to convert HTML to PDF at A4 page size. But the content is too long and PDF split into 2 pages. I just want it into one page. So my idea is convert to PDF A3 size, then scale down to A4 size.
But another problem is scaling down from A3 page size to A4 page size.</p>

答:
1) Convert your html to A3-sized document

2) Iterate through pages and copy each page as a formXObject

3) For each page formXObject:

a) scale it with 0.5 coefficient;

b) add to the resultant document.

The appopriate Java code is as follows (there should be no problem for you to port it to C#, since the iText's API is just the same):

```<code>    // 1
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos));
    pdfDocument.setDefaultPageSize(PageSize.A3);
    HtmlConverter.convertToPdf(new FileInputStream(sourcePath), pdfDocument);

    PdfDocument resultantDocument = new PdfDocument(new PdfWriter(destPath));

    pdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
    // 2
    for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
        PdfPage page = pdfDocument.getPage(i);
        PdfFormXObject formXObject = page.copyAsFormXObject(resultantDocument);
        PdfCanvas pdfCanvas = new PdfCanvas(resultantDocument.addNewPage());
        // 3a and 3b
        pdfCanvas.addXObject(formXObject, 0.5f, 0, 0, 0.5f, 0, 0);
    }

    pdfDocument.close();
    resultantDocument.close();
</code>```

Body:
1) Convert your html to A3-sized document

2) Iterate through pages and copy each page as a formXObject

3) For each page formXObject:

a) scale it with 0.5 coefficient;

b) add to the resultant document.

The appopriate Java code is as follows (there should be no problem for you to port it to C#, since the iText's API is just the same):

    // 1
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfDocument pdfDocument = new PdfDocument(new PdfWriter(baos));
    pdfDocument.setDefaultPageSize(PageSize.A3);
    HtmlConverter.convertToPdf(new FileInputStream(sourcePath), pdfDocument);

    PdfDocument resultantDocument = new PdfDocument(new PdfWriter(destPath));

    pdfDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
    // 2
    for (int i = 1; i <= pdfDocument.getNumberOfPages(); i++) {
        PdfPage page = pdfDocument.getPage(i);
        PdfFormXObject formXObject = page.copyAsFormXObject(resultantDocument);
        PdfCanvas pdfCanvas = new PdfCanvas(resultantDocument.addNewPage());
        // 3a and 3b
        pdfCanvas.addXObject(formXObject, 0.5f, 0, 0, 0.5f, 0, 0);
    }

    pdfDocument.close();
    resultantDocument.close();