问:
Take the cell values more than one from ".CSV" to Powershell
I have . csv table in below;

```<code>name;location;id;number
space;usa;123;110001
sky;canada;124;110002
plane;peru;126;1100011
cloud;italy;127;1111033
</code>```

I want to reach the in 'name' column cell values for example 'space' cell in csv file , if it finds the 'space' after the I want to take its the location and/or id value in same ".csv" file by Powershell.

I used for $A = Import-Csv -Pathcode for take the .csv file. But I can not reach the name columnn or any cell as clearly.
$A.name or $A.location is not working in powershell I tried.

Thanks

答:
Another alternative, if I am understanding the request correctly.
If you would like to find the row with the name sky, then:

Note: test.csv contains the provided input.

```<code>Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky'

name location id  number
---- -------- --  ------
sky  canada   124 110002
</code>```

this would return all the rows with Name equal to sky.

Of course you may use the operator -like so to utilize the wildcard, i.e.

```<code>Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -like 's*'

name  location id  number
----  -------- --  ------
space usa      123 110001
sky   canada   124 110002
</code>```

This would return all the names starting with letter s.

If you need only the location, then you may use Select-Object

```<code>Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky' | Select-Object -Property Location

location
--------
canada
</code>```

Or address the property directly:

```<code>(Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky').Location

canada
</code>```

Or:

```<code>$result = Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky'
$result.location

canada
</code>```

Hope it helps.

Body:
I have . csv table in below;

name;location;id;number
space;usa;123;110001
sky;canada;124;110002
plane;peru;126;1100011
cloud;italy;127;1111033

I want to reach the in 'name' column cell values for example 'space' cell in csv file , if it finds the 'space' after the I want to take its the location and/or id value in same ".csv" file by Powershell.

I used for $A = Import-Csv -Pathcode for take the .csv file. But I can not reach the name columnn or any cell as clearly.
$A.name or $A.location is not working in powershell I tried.

Thanks

Body:
Another alternative, if I am understanding the request correctly.
If you would like to find the row with the name sky, then:

Note: test.csv contains the provided input.

Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky'

name location id  number
---- -------- --  ------
sky  canada   124 110002

this would return all the rows with Name equal to sky.

Of course you may use the operator -like so to utilize the wildcard, i.e.

Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -like 's*'

name  location id  number
----  -------- --  ------
space usa      123 110001
sky   canada   124 110002

This would return all the names starting with letter s.

If you need only the location, then you may use Select-Object

Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky' | Select-Object -Property Location

location
--------
canada

Or address the property directly:

(Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky').Location

canada

Or:

$result = Import-Csv -Path .\test.csv -Delimiter ';' | Where-Object -Property Name -eq 'sky'
$result.location

canada

Hope it helps.


来源: stackexchange

问:
This application does not have the debuggable attribute enabled in its manifest
Cannot debug application com.domain.test on device samsung-gt_i9300-323020cfc86b804f.
This application does not have the debuggable attribute enabled in its manifest.
If you have manually set it in the manifest, then remove it and let the IDE automatically assign it.
If you are using Gradle, make sure that your current variant is debuggable.</p>

答:
In build.gradle</p>

```<code>debug {
        debuggable true
        signingConfig signingConfigs.debug
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In build.gradle

debug {
        debuggable true
        signingConfig signingConfigs.debug
    }

ContentLicense: CC BY-SA 4.0


问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答:
You'll have to Use the HTTPWebRequest object to connect to the site and scrape the information from the response.

Look for html tags or class names that wrap the content you are trying to find, then use either regexes or string functions to get the required data.

Good example here:


问:
Message "flutter run: No connected devices"
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

```<code>flutter run
No connected devices.
</code>```

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.
```

Is there a solution to this problem?

答:
This works for me:

Go to Settings > Developer options > Disable USB debugging > Re-enable USB debugging

Body:
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

flutter run
No connected devices.

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.

Is there a solution to this problem?


问:
ArrayList added item is replaced by the next item in for loop
I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)

This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.

```<code>public class Serv
{
    @Autowired
    GrpHeader objGrpHeader;

    @Autowired
    CompPesoOutgoingMsg objMsg;

    @Autowired
    OutwardMessage objOutwardMessage;

    public List<OutwardMessage> outgoingMessagesAsSingleTrx()
    {
        List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
        List<OutwardMessage> myTrxList = new ArrayList<>();

        for (OutgoingMsg_Obj outgoingMsg : trxList)
        {
            BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
            trxAmt = (trxAmt).divide(new BigDecimal(100));

            GrpHeader grpHeader = objGrpHeader;
            CompPesoOutgoingMsg outMsg2 = objMsg;
            OutwardMessage objOutwardMessage2 = objOutwardMessage;

            outgoingMsg.setRmtInf(objRmtInf);
            outgoingMsg.setPmtTpInf(objPmtTpInf);

            outMsg2.setHeader(grpHeader);
            outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
            objOutwardMessage2.setObjMsg(outMsg2);

            **//Here, Correct object details are printed**
            log.info("outwardMsg 100 {} ", objOutwardMessage2);

            //Add Item to the list
            myTrxList.add(objOutwardMessage2);

            for (OutwardMessage outwardMsgx : myTrxList)
            {
                //1. When this loop executed first time, first object details are printed
                //2. When printed second time, first added object is no more. And second added object is there twice.
                log.info("outwardMsg 101 {} ", outwardMsgx);
            }
        }
        return myTrxList;
    }
}
</code>```

答:
Since no new object is created for each iteration, the same objOutwardMessage2 value is getting replaced each time.

Try

```<code>OutwardMessage objOutwardMessage2 = new OutwardMessage();
</code>```

and copy the value of objOutwardMessage to the newly created objOutwardMessage2.

Body:
I am facing a very strange situation. I add an object to an arrayList in a loop, but it is replaced by the next object. Actually second item is duplicated. ( It replaces the first item as well as inserts another object to the ArrayList.)

This is my code. I have done the debugging and included the comments where needed. Could someone point out why this happens? I am taking the object details from the database and those are working as expected.

public class Serv
{
    @Autowired
    GrpHeader objGrpHeader;

    @Autowired
    CompPesoOutgoingMsg objMsg;

    @Autowired
    OutwardMessage objOutwardMessage;

    public List<OutwardMessage> outgoingMessagesAsSingleTrx()
    {
        List<OutgoingMsg_Obj> trxList = myRepo.getTrx("5");
        List<OutwardMessage> myTrxList = new ArrayList<>();

        for (OutgoingMsg_Obj outgoingMsg : trxList)
        {
            BigDecimal trxAmt = outgoingMsg.getIntrBkSttlmAmt().getTrxn_amt();
            trxAmt = (trxAmt).divide(new BigDecimal(100));

            GrpHeader grpHeader = objGrpHeader;
            CompPesoOutgoingMsg outMsg2 = objMsg;
            OutwardMessage objOutwardMessage2 = objOutwardMessage;

            outgoingMsg.setRmtInf(objRmtInf);
            outgoingMsg.setPmtTpInf(objPmtTpInf);

            outMsg2.setHeader(grpHeader);
            outMsg2.setCdtTrfTxInf(Arrays.asList(outgoingMsg));
            objOutwardMessage2.setObjMsg(outMsg2);

            **//Here, Correct object details are printed**
            log.info("outwardMsg 100 {} ", objOutwardMessage2);

            //Add Item to the list
            myTrxList.add(objOutwardMessage2);

            for (OutwardMessage outwardMsgx : myTrxList)
            {
                //1. When this loop executed first time, first object details are printed
                //2. When printed second time, first added object is no more. And second added object is there twice.
                log.info("outwardMsg 101 {} ", outwardMsgx);
            }
        }
        return myTrxList;
    }
}

Body:
Since no new object is created for each iteration, the same objOutwardMessage2 value is getting replaced each time.

Try

OutwardMessage objOutwardMessage2 = new OutwardMessage();

and copy the value of objOutwardMessage to the newly created objOutwardMessage2.


问:
com.amazonaws.AmazonClientException: Unable to execute HTTP request: No such host is known (spark-tunes.s3a.ap-south-1.amazonaws.com)
I am trying to read a json file stored in S3 bucket from spark in local mode via pycharm. But I'm getting the below error message:

"py4j.protocol.Py4JJavaError: An error occurred while calling o37.json.
  : com.amazonaws.AmazonClientException: Unable to execute HTTP request: No such host is known (spark-tunes.s3a.ap-south-1.amazonaws.com)"

(spark-tunes is my S3 bucket name).

Below is the code I executed. Please help me to know if I'm missing something.

spark = SparkSession.builder.appName('DF Read').config('spark.master', 'local').getOrCreate()

spark._jsc.hadoopConfiguration().set("fs.s3a.access.key", "access_key")
spark._jsc.hadoopConfiguration().set("fs.s3a.secret.key", "secret_key")

spark._jsc.hadoopConfiguration().set("fs.s3a.endpoint", "s3a.ap-south-1.amazonaws.com")
spark._jsc.hadoopConfiguration().set("com.amazonaws.services.s3a.enableV4", "true")
spark._jsc.hadoopConfiguration().set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")

df = spark.read.json("s3a://bucket-name/folder_name/*.json")

df.show(5)
```

答:
try setting fs.s3a.path.style.access to false and instead of prefixing the bucket name to the host, the aws s3 client will use paths under the endpoint

also: drop the fs.s3a.impl line. That is superstition passed down across stack overflow examples. It's not needed. really.


问:
RegEx for jsDoc comments
Can't find any usable RegExp example to match all jsDoc comment blocks within a text file.

Basically, it needs to find all blocks that satisfy the following rules:

Starts with /**, followed by one or more line breaks

Ends with */

Within the block there can be anything, including code examples and HTML.

I tried the code from jsdoc-regex, but it didn't work:

```<code>/[^\S\r\n]*\/(?:\*{2})([\W\w]+?)\*\/([\W\w]+?)?(?=\s+\/\*{1,2}|$)/g;
</code>```

NOTE:

I am parsing generic text files, not necessarily JavaScript, so I can't use  JS parsers like Esprima.

UPDATE:

To rephrase my question, I'm stuck trying to define a RegEx rule that says the expression must end with */, while there can be anything prior to it (within the block), i.e. by anything in this case means anything except */.

SOLUTION:

Thanks to you the answer by @m93a, his implementation has become a valuable addition to decomment, option ignore.

答:
In addition to @m39a's answer. If you are using a language or Regex library that doesn't support look-around. You can use this:
\/\*\*\s*\n([^\*]|\*[^\/])*\*\/

Check it out at Regex101: https://regex101.com/r/TMr78R/1

Title: RegEx for jsDoc comments

Body:
Can't find any usable RegExp example to match all jsDoc comment blocks within a text file.

Basically, it needs to find all blocks that satisfy the following rules:

Starts with /**, followed by one or more line breaks

Ends with */

Within the block there can be anything, including code examples and HTML.

I tried the code from jsdoc-regex, but it didn't work:

/[^\S\r\n]*\/(?:\*{2})([\W\w]+?)\*\/([\W\w]+?)?(?=\s+\/\*{1,2}|$)/g;

NOTE:

I am parsing generic text files, not necessarily JavaScript, so I can't use  JS parsers like Esprima.

UPDATE:

To rephrase my question, I'm stuck trying to define a RegEx rule that says the expression must end with */, while there can be anything prior to it (within the block), i.e. by anything in this case means anything except */.

SOLUTION:

Thanks to you the answer by @m93a, his implementation has become a valuable addition to decomment, option ignore.


问:
how to invoke user's (non-outlook) email application from .NET program
My C# application needs to email problem reports from the user's machine to a support tech.  There is no common SMTP server available, so I don't think I can use System.Net.Mail;  instead the message must be sent using the user's own email program and account.  I could use office automation to launch outlook and compose a message.  But what if the user is not using outlook?  Is there any more general mechanism that is supported by multiple email clients?  Or is there a library that knows how to detect and invoke various clients?

EDIT: as this for submitting problem reports, I need to include attachments or (at worst) a long message body...

答: for new line body use %0A and for New Paragraph use %0A%0A.

ContentLicense: CC BY-SA 2.5


问:
Issue while Running transactions through Node Explorer via cordapp-example flows :ExampleFlow$Initiator
link to imageI tried with the Beta version of Corda Node explorer for a visual UI of the operating nodes,peers,notary and the vaults.

It is working fine.

When I am performing the transactions over CLI, It is getting reflected on the Node Explorer,but facing issue while trying to transact over UI.

I am trying to do a transaction with ExampleFlow$Iniator flow, but I am not getting the option to create a transaction over UI.

Will it not work with the cordapps of samples/cordapp-example?

答:
Yes, it should work with the cordapp-example. To be able to run flows you need to provide the path of the folder containing the cordapp in the Settings tab.

Have a look at the demo here: https://www.youtube.com/watch?v=cn2lhS8pjRs


问:
Force line break after first word in a div in React component
I am working with a
 where data comes as simple text from an outer source. For instance
Business in three different continents.
 . Now I need to show this text like below:

```<code>         Business

in four different countries
</code>```

Must have: text-align: center; and line break always after the first word only.

Problem Since I have only one HTML element as in
 to work with I can not add \n inside the
 content. This would only either be after or before the entire line of text if I use pseudo element &::before / &::after (for the @emotion/styled I am using) and not after the first word. Since CSS can't count words it seems this issue can not be solved with CSS only. Also the
 container width has to adjust to the second line, hence I can't use display:block because it will be applied to the entire line of text. Saw in other posts to add two white spaces to force line break but this can't be done just after first word since I don't have any nested HTML element, like

Btw, can react-markdown help?

What is the best way to solve this problem?

答:
My proposed solution would be:

```<code>class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'Business in three different continents.'
    };
  }
  componentDidMount(){
    let first=this.state.name.split(" ")[0];
    this.setState({
      name: first+"\n"+this.state.name.replace(first,'')
    });
  }
  render() {
    return (
      <div class="new-line">
      {this.state.name}
      </div>
    );
  }
}
</code>```

In CSS style:

```<code>.new-line {
  white-space: pre-line;
  text-align: center;
}
</code>```

Working stackblitz

please let me know if this is helpful

Body:
I am working with a
 where data comes as simple text from an outer source. For instance
Business in three different continents.
 . Now I need to show this text like below:

         Business

in four different countries

Must have: text-align: center; and line break always after the first word only.

Problem Since I have only one HTML element as in
 to work with I can not add \n inside the
 content. This would only either be after or before the entire line of text if I use pseudo element &::before / &::after (for the @emotion/styled I am using) and not after the first word. Since CSS can't count words it seems this issue can not be solved with CSS only. Also the
 container width has to adjust to the second line, hence I can't use display:block because it will be applied to the entire line of text. Saw in other posts to add two white spaces to force line break but this can't be done just after first word since I don't have any nested HTML element, like

Btw, can react-markdown help?

What is the best way to solve this problem?

Body:
My proposed solution would be:

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'Business in three different continents.'
    };
  }
  componentDidMount(){
    let first=this.state.name.split(" ")[0];
    this.setState({
      name: first+"\n"+this.state.name.replace(first,'')
    });
  }
  render() {
    return (
      <div class="new-line">
      {this.state.name}
      </div>
    );
  }
}

In CSS style:

.new-line {
  white-space: pre-line;
  text-align: center;
}

Working stackblitz

please let me know if this is helpful


问:
File Uploading to Google Drive
I am just starting with the Google Drive API. The quick start is quite handy, but it only explains file listing feature.

Cannot find the file upload feature in the Upload file data page.

The RI documentation for Google::Apis only contains hundreds of new line characters (1128 to be specific), and nothing interesting.

How do I upload files to google drive using the Ruby API?

答:
Here are two upload examples using Drive V2 (one resumable, one not), and here you can see the method you should be using in V3 (create_file instead of insert_file), as well as an explanation of all the possible parameters you can provide.

The first example could be written in V3 like this:

```<code>drive_service.create_file({title: 'My Favorite Movie'}, upload_source: 'mymovie.m4v',
                  content_type: 'video/mp4')
</code>```

Reference:

Class: Google::Apis::DriveV3

create_file

Title: File Uploading to Google Drive

Body:
Here are two upload examples using Drive V2 (one resumable, one not), and here you can see the method you should be using in V3 (create_file instead of insert_file), as well as an explanation of all the possible parameters you can provide.

The first example could be written in V3 like this:

drive_service.create_file({title: 'My Favorite Movie'}, upload_source: 'mymovie.m4v',
                  content_type: 'video/mp4')

Reference:

Class: Google::Apis::DriveV3

create_file


问:
one week information of alertlofile
I want to view the ORA errors in alertlogfile of past 7 (monday-sunday)days,
by writting in shell scripts.
Can anybody help me.

Thanks

答:
Something like:

```<code>sed -n -e '/start_time/,/end_time/ {/ORA/ p}' logfile
</code>```

or with awk

```<code>$ start="Fri Feb 27 08:00:00 2009"
$ end="Fri Mar 6 08:00:00 2009"

$ awk -v prev="$start" -v last="$end" '$0 ~ prev,$0 ~ last' logfile
</code>```

A more sophisticated script looking for last date entries in ORA file is available here, but also at dba-oracle.com

This does not answer exactly your request but might give you some clues to start your own script.

OwnerDisplayName: Raju

Title: one week information of alertlofile

Body:
Something like:

sed -n -e '/start_time/,/end_time/ {/ORA/ p}' logfile

or with awk

$ start="Fri Feb 27 08:00:00 2009"
$ end="Fri Mar 6 08:00:00 2009"

$ awk -v prev="$start" -v last="$end" '$0 ~ prev,$0 ~ last' logfile

A more sophisticated script looking for last date entries in ORA file is available here, but also at dba-oracle.com

This does not answer exactly your request but might give you some clues to start your own script.

OwnerDisplayName: VonC

LastEditorDisplayName: VonC


问:
Promote nuget package to a DevOps feed view via PowerShell
I'm trying to figure out a programmatic way to promote my Nuget packages to pre-defined views in Azure DevOps package feed. I found this link but without any examples. I am using PowerShell and getting this error when I try to invoke the documented PATCH command:

The requested resource does not support http method 'PATCH'."

This is what I've tried:

```<code>$pkgUri = "https://pkgs.dev.azure.com/$tfsOrganization/$tfsProjectName/_apis/packaging/feeds/$PackageFeedName/nuget/packages/$pkgName/versions/$pkgVersion?api-version=5.1-preview.1"

$json = '{ "views": { "op":"add", "path":"/views/-", "value":"' + 'PreRelease' + '" } }'

$promotePackage = Invoke-RestMethod -Uri $allPackagesApiUrl -ContentType "application/json" -Method PATCH -Headers @{Authorization = "Basic $token"} -Body $json
</code>```

答:
The Rest API you are using is the right one. For example take a look at below code snippet:

```<code>function Set-PackageQuality
{
 [CmdletBinding()]
 [OutputType([object])]
 param
 (
 [string] $feedName="",
 [string] $packageId="",
 [string] $packageVersion="",
 [string] $packageQuality=""

 )

$token = New-VSTSAuthenticationToken
 $releaseViewURL = "$basepackageurl/$feedName/nuget/packages/$packageId/
versions/$($packageVersion)?api-version=5.0-preview.1"

}
</code>```

More detail take a look at this blog -- Programmatically promote your package quality with Release Views in VSTS

Body:
I'm trying to figure out a programmatic way to promote my Nuget packages to pre-defined views in Azure DevOps package feed. I found this link but without any examples. I am using PowerShell and getting this error when I try to invoke the documented PATCH command:

The requested resource does not support http method 'PATCH'."

This is what I've tried:

$pkgUri = "https://pkgs.dev.azure.com/$tfsOrganization/$tfsProjectName/_apis/packaging/feeds/$PackageFeedName/nuget/packages/$pkgName/versions/$pkgVersion?api-version=5.1-preview.1"

$json = '{ "views": { "op":"add", "path":"/views/-", "value":"' + 'PreRelease' + '" } }'

$promotePackage = Invoke-RestMethod -Uri $allPackagesApiUrl -ContentType "application/json" -Method PATCH -Headers @{Authorization = "Basic $token"} -Body $json

Body:
The Rest API you are using is the right one. For example take a look at below code snippet:

function Set-PackageQuality
{
 [CmdletBinding()]
 [OutputType([object])]
 param
 (
 [string] $feedName="",
 [string] $packageId="",
 [string] $packageVersion="",
 [string] $packageQuality=""

 )

$token = New-VSTSAuthenticationToken
 $releaseViewURL = "$basepackageurl/$feedName/nuget/packages/$packageId/
versions/$($packageVersion)?api-version=5.0-preview.1"

}

More detail take a look at this blog -- Programmatically promote your package quality with Release Views in VSTS


问:
issue decoding an image using jpeg_js
my environment:

```<code>ubuntu 18.04
rtx 2080ti
cuda 10.1
node v12.16.3
tfjs 1.7.4
</code>```

the saved_model is efficientdet-d0,

and the step of inference is in inference step

for parsing image data with js,i convert img.png to img.jpg,and the result of saved_model is same with saved_model result

the command convert saved_model to tfjs_graph_model is

```<code>tensorflowjs_converter --input_format=tf_saved_model /tmp/saved_model ~/DATA/http_models/specDetection/
</code>```

and my test code is

```<code>var tfc = require("@tensorflow/tfjs-converter");
var tf  = require("@tensorflow/tfjs-core");
var jpeg_js = require("jpeg-js");
var fs = require("fs");

async function loadModel() {
    var modelUrl = "http://localhost:8000/model.json"
    var model = await tfc.loadGraphModel(modelUrl);
    return model;
}

async function detect() {
    var model = await loadModel();
    var img = fs.readFileSync("~/SRC/automl_test/efficientdet/img.jpg");
    const input = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false});

    const batched = tf.tidy(() => {
        const img = tf.browser.fromPixels(input);
        // Reshape to a single-element batch so we can pass it to executeAsync.
        return img.expandDims(0);
    });

    const result = await model.executeAsync({'image_arrays:0':batched},['detections:0']);
    console.log(result);
}

detect();
</code>```

when detect object in img.jpg with my test code,nothing detected --- the size of result is 0

what do i do to sovle this problem?

thanks for any cue

edit:

code 1:

```<code> var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");

    var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false})
    var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},3);
    batched = batched.slice([0,0,0],[-1,-1,3]);
    var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
    result = tf.slice(result,[0,0,1],[1,-1,4]);
</code>```

code 2:

```<code>var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");

    var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:true})
    var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},4);
    batched = batched.slice([0,0,0],[-1,-1,3]);
    var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
    result = tf.slice(result,[0,0,1],[1,-1,4]);
</code>```

code 1 got a bad result and code 2 got a correct result.
code 2 decode jpg with formatAsRGBA:true,and set numChannels=4 in tf.browser.fromPixels.  jpeg-js must decode jpg to RGBA to work correctly.
i think it is a bug of jpeg-js.or i am not familiar with jpg encoding?

答:
The tensor is not well generated. fromPixels is mostly used to get a tensor from an htmlImageElement. Printing a summary of the tensor and compare it with the one generated for python can suffice to tell that.

Is there an issue with jpeg-js ?

First we need to know how the imageData works. An image Data pixel is a 4 numerical values R, G, B, A. When using the data decoded by jpeg_js.decode as argument of tf.browser.fromPixel with 3 channels (formatAsRGBA:false), it is considered as an image data. Let's consider the data [a, b, c, d, e, f] = jpeg_js.decode("path", {formatAsRGBA:false}) and the tensor t created from it
t = tf.browser.fromPixels({data, width: 2, height: 1}). How it is interpreted ? tf.browser.fromPixels, will create an ImageDate of height: 1 and of width: 2. Consequently, the imageData will be of size 1 * 2 * 4 (instead of 1 * 2 * 3) and has all its values set to 0. Then it will copy the data decoded to the imageData. So imageData = [a, b, c, d, e, f, 0, 0].
As a result, the slice (t.slice([0, 0, 0], [-1, -1, 3]) will be [a, b, c, e, f, 0].
Neither is jpeg_js the issue, nor tf.browser.fromPixels. This is how imageData works

What can be done ?

keep the alpha channel of the decoded image formatAsRGBA:true

Instead of using tf.browser.fromPixels, use directly tf.tensor to create the tensor

const img = tf.tensor(input.data, [input.height, input.width, 3])
```

<hr>

<p>Another option is to use<code>tensorflow-node</code>. And <code>tf.node.decodeImage</code> can decode an image from a tensor.</p>

<pre class="lang-js prettyprint-override"><code>const img = fs.readFileSync("path/of/image");
const tensor = tf.node.decodeImage(img)
// use the tensor for prediction
</code>```

Unlike jpeg-js that works only for image in jpeg encoding format, it can decode a wider range of images

Title: issue decoding an image using jpeg_js

Body:
my environment:

ubuntu 18.04
rtx 2080ti
cuda 10.1
node v12.16.3
tfjs 1.7.4

the saved_model is efficientdet-d0,

and the step of inference is in inference step

for parsing image data with js,i convert img.png to img.jpg,and the result of saved_model is same with saved_model result

the command convert saved_model to tfjs_graph_model is

tensorflowjs_converter --input_format=tf_saved_model /tmp/saved_model ~/DATA/http_models/specDetection/

and my test code is

var tfc = require("@tensorflow/tfjs-converter");
var tf  = require("@tensorflow/tfjs-core");
var jpeg_js = require("jpeg-js");
var fs = require("fs");

async function loadModel() {
    var modelUrl = "http://localhost:8000/model.json"
    var model = await tfc.loadGraphModel(modelUrl);
    return model;
}

async function detect() {
    var model = await loadModel();
    var img = fs.readFileSync("~/SRC/automl_test/efficientdet/img.jpg");
    const input = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false});

    const batched = tf.tidy(() => {
        const img = tf.browser.fromPixels(input);
        // Reshape to a single-element batch so we can pass it to executeAsync.
        return img.expandDims(0);
    });

    const result = await model.executeAsync({'image_arrays:0':batched},['detections:0']);
    console.log(result);
}

detect();

when detect object in img.jpg with my test code,nothing detected --- the size of result is 0

what do i do to sovle this problem?

thanks for any cue

edit:

code 1:

 var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");

    var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:false})
    var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},3);
    batched = batched.slice([0,0,0],[-1,-1,3]);
    var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
    result = tf.slice(result,[0,0,1],[1,-1,4]);

code 2:

var img = fs.readFileSync("~/DATA/http_models/specDetection/test.jpg");

    var dataJpegJs = jpeg_js.decode(img,{useTArray:true,formatAsRGBA:true})
    var batched = tf.browser.fromPixels({data:dataJpegJs.data, width: dataJpegJs.width, height:dataJpegJs.height},4);
    batched = batched.slice([0,0,0],[-1,-1,3]);
    var result = await model.executeAsync({'image_arrays:0':batched.expandDims(0)},['detections:0']);
    result = tf.slice(result,[0,0,1],[1,-1,4]);

code 1 got a bad result and code 2 got a correct result.
code 2 decode jpg with formatAsRGBA:true,and set numChannels=4 in tf.browser.fromPixels.  jpeg-js must decode jpg to RGBA to work correctly.
i think it is a bug of jpeg-js.or i am not familiar with jpg encoding?

Body:
The tensor is not well generated. fromPixels is mostly used to get a tensor from an htmlImageElement. Printing a summary of the tensor and compare it with the one generated for python can suffice to tell that.

Is there an issue with jpeg-js ?

First we need to know how the imageData works. An image Data pixel is a 4 numerical values R, G, B, A. When using the data decoded by jpeg_js.decode as argument of tf.browser.fromPixel with 3 channels (formatAsRGBA:false), it is considered as an image data. Let's consider the data [a, b, c, d, e, f] = jpeg_js.decode("path", {formatAsRGBA:false}) and the tensor t created from it
t = tf.browser.fromPixels({data, width: 2, height: 1}). How it is interpreted ? tf.browser.fromPixels, will create an ImageDate of height: 1 and of width: 2. Consequently, the imageData will be of size 1 * 2 * 4 (instead of 1 * 2 * 3) and has all its values set to 0. Then it will copy the data decoded to the imageData. So imageData = [a, b, c, d, e, f, 0, 0].
As a result, the slice (t.slice([0, 0, 0], [-1, -1, 3]) will be [a, b, c, e, f, 0].
Neither is jpeg_js the issue, nor tf.browser.fromPixels. This is how imageData works

What can be done ?

keep the alpha channel of the decoded image formatAsRGBA:true

Instead of using tf.browser.fromPixels, use directly tf.tensor to create the tensor

const img = tf.tensor(input.data, [input.height, input.width, 3])

Another option is to usetensorflow-node. And tf.node.decodeImage can decode an image from a tensor.

const img = fs.readFileSync("path/of/image");
const tensor = tf.node.decodeImage(img)
// use the tensor for prediction

Unlike jpeg-js that works only for image in jpeg encoding format, it can decode a wider range of images


问:
How to show the part of the errorbar lines which are within the plot margins using `ggplot2`?
I have a grid of plots, all with the same y and x-axis scale. The plots represent time in the x-axe and mean values in the y-axe with their standard errors. My problem is that some errorbars are not entirely within the plot margins, and I wonder if there is some way to represent the part of the errorlines that are within the plot margins. Below I give a fake example and code to play with:

```<code>df <- data.frame(time=seq(-15,15,1),
                 mean=c(0.49,0.5,0.53,0.55,0.57,0.59,0.61,0.63,0.65,0.67,0.69,0.71,0.73,0.75,0.77,0.79,0.77,0.75,0.73,0.71,0.69,0.67,0.65,0.63,0.61,0.59,0.57,0.55,0.53,0.51,0.49),
                 sd=c(0.09,0.087,0.082,0.08,0.023,0.011,0.010,0.009,0.008,0.007,0.006,0.005,0.004,0.003,0.002,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.010,0.011,0.023,0.08,0.084,0.087,0.09))

Plot <-  ggplot(df, aes(x=time, y=mean)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
  geom_point(size=1) +
  geom_line () +
  theme_bw() +
  scale_y_continuous(limits = c(0.49, 0.85), breaks = c(0.5, 0.65,0.8))

Plot
</code>```

答:
You need to set coord_cartesian limits rather than scale_y_continuous limits:

ggplot(df, aes(x=time, y=mean)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
  geom_point(size=1) +
  geom_line () +
  theme_bw() +
  scale_y_continuous(breaks = c(0.5, 0.65,0.8)) +
  coord_cartesian(ylim = c(0.49, 0.85))
```

Body:
I have a grid of plots, all with the same y and x-axis scale. The plots represent time in the x-axe and mean values in the y-axe with their standard errors. My problem is that some errorbars are not entirely within the plot margins, and I wonder if there is some way to represent the part of the errorlines that are within the plot margins. Below I give a fake example and code to play with:

df <- data.frame(time=seq(-15,15,1),
                 mean=c(0.49,0.5,0.53,0.55,0.57,0.59,0.61,0.63,0.65,0.67,0.69,0.71,0.73,0.75,0.77,0.79,0.77,0.75,0.73,0.71,0.69,0.67,0.65,0.63,0.61,0.59,0.57,0.55,0.53,0.51,0.49),
                 sd=c(0.09,0.087,0.082,0.08,0.023,0.011,0.010,0.009,0.008,0.007,0.006,0.005,0.004,0.003,0.002,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.010,0.011,0.023,0.08,0.084,0.087,0.09))

Plot <-  ggplot(df, aes(x=time, y=mean)) +
  geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.3) +
  geom_point(size=1) +
  geom_line () +
  theme_bw() +
  scale_y_continuous(limits = c(0.49, 0.85), breaks = c(0.5, 0.65,0.8))

Plot


问:
Line graphs in R Help Legend
So I am currently plotting data from a excel sheet using R. The problem I am having is in regards to the legend. Here is the Picture: https://i.stack.imgur.com/Key98.jpg As you can see in the legend, the values go as follows: PP1, PP10, PP15, PP3, PP30, PP5. I have been trying to make it go in numerical order as PP1, PP3, PP5, PP10,PP15, PP30. I am not sure how to fix this problem as I am very new to R coding. Any help would be greatly appreciated!! This is how i have my Excel sheet formated: https://i.stack.imgur.com/OfNaY.jpg Here is my Code:  </p>

```<code>library("dplyr")
install.packages("ggplot2")
library("ggplot2")
install.packages("tidyverse")
library("tidyverse")
install.packages('reshape')
library('reshape')

    # import data
    NPPdata <- read.csv("C:\\Users\\rrami\\Desktop\\R-Data\\NPPdata.csv", header = TRUE)

    ggplot(NPPdata , aes(x = N_Gradient, y=Values, colour = Group))+
          geom_errorbar(aes(ymin=Values-Stdvalue, ymax=Values+Stdvalue), lwd =1.2)+
          geom_line(lwd=1.5)+
          ggtitle("Year 1 MONO Phrag [Branch Prob 0.1]")+
          theme(plot.title = element_text(hjust =0.5)) +
          labs(x = "N-Gradient", y ="INV%")+
           theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
            axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16))
</code>```

答:
I've made an example with "iris". As you can see, on the second figure 'scale_fill_discrete' is used to change the order of the labels

```<code>library (tidyverse)

data(iris)

figure_1 <- iris %>%
  gather(key = floral_components, value = values, -Species) %>%
  ggplot(aes(x = floral_components, y = values, fill = Species)) +
  geom_bar(stat='identity') +
  labs(x = "Floral Components",
        y = "Values",
        fill = "Species")
</code>```

```<code>figure_2 <- iris %>%
  gather(key = floral_components, value = values, -Species) %>%
  ggplot(aes(x = floral_components, y = values, fill = Species)) +
  geom_bar(stat='identity') +
  labs(x = "Floral Components",
       y = "Values",
       fill = "Species") +
  scale_fill_discrete(labels = c("versicolor", "virginica", "setosa"))
</code>```

Title: Line graphs in R Help Legend

Body:
So I am currently plotting data from a excel sheet using R. The problem I am having is in regards to the legend. Here is the Picture: https://i.stack.imgur.com/Key98.jpg As you can see in the legend, the values go as follows: PP1, PP10, PP15, PP3, PP30, PP5. I have been trying to make it go in numerical order as PP1, PP3, PP5, PP10,PP15, PP30. I am not sure how to fix this problem as I am very new to R coding. Any help would be greatly appreciated!! This is how i have my Excel sheet formated: https://i.stack.imgur.com/OfNaY.jpg Here is my Code:

library("dplyr")
install.packages("ggplot2")
library("ggplot2")
install.packages("tidyverse")
library("tidyverse")
install.packages('reshape')
library('reshape')

    # import data
    NPPdata <- read.csv("C:\\Users\\rrami\\Desktop\\R-Data\\NPPdata.csv", header = TRUE)

    ggplot(NPPdata , aes(x = N_Gradient, y=Values, colour = Group))+
          geom_errorbar(aes(ymin=Values-Stdvalue, ymax=Values+Stdvalue), lwd =1.2)+
          geom_line(lwd=1.5)+
          ggtitle("Year 1 MONO Phrag [Branch Prob 0.1]")+
          theme(plot.title = element_text(hjust =0.5)) +
          labs(x = "N-Gradient", y ="INV%")+
           theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
            axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16))

Body:
I've made an example with "iris". As you can see, on the second figure 'scale_fill_discrete' is used to change the order of the labels

library (tidyverse)

data(iris)

figure_1 <- iris %>%
  gather(key = floral_components, value = values, -Species) %>%
  ggplot(aes(x = floral_components, y = values, fill = Species)) +
  geom_bar(stat='identity') +
  labs(x = "Floral Components",
        y = "Values",
        fill = "Species")

figure_2 <- iris %>%
  gather(key = floral_components, value = values, -Species) %>%
  ggplot(aes(x = floral_components, y = values, fill = Species)) +
  geom_bar(stat='identity') +
  labs(x = "Floral Components",
       y = "Values",
       fill = "Species") +
  scale_fill_discrete(labels = c("versicolor", "virginica", "setosa"))


问:
debuggging eclipse plugin dependancy
I am creating an eclipse plugin that calls some classes from a Java project. I have added this Java project as a required project on my build path.
When I create an eclipse plugin jar using an ant script, everything works fine.
However when I try to debug the code at run time or open the eclipse as a run time application, the classes from the Java project are not accessible. I get a NoClassDefFoundException.

Is there something I am missing while adding the dependancy?

答:
Eclipse is based on OSGi, and as a rule of thumb, bundles can only see other bundles.  Usually for including 3rd party jars in an eclipse plugin, you have 2 choices:

1) Include the jar in your eclipse project.  Add it to the build.properties.  Edit the MANIFEST.MF and add it to the Classpath section on the Runtime tab.

2) turn the 3rd party jar into a bundle so that your eclipse plugin can require it.  You can use File>New>Other...>Plug-in Development>Plug-in from Existing JAR.  The simplest form of an OSGi bundle is just the original jar with OSGi headers added to its MANIFEST.MF.

EDIT:

Remember also you have to honour the 3rd party jar license with whichever option you choose.

Title: debuggging eclipse plugin dependancy


问:
bash shell execution
I am using

sed -s n v

Nothing works for me

答:
The -i flag is only in GNU Sed.

```<code>cat file | tr ']' '[' > temp
mv temp file
</code>```

The above should work for you.

Title: bash shell execution

Body:
The -i flag is only in GNU Sed.

cat file | tr ']' '[' > temp
mv temp file

The above should work for you.


问:
How to evaluate the passed prop to the styled component using react and typescript?
i want to add a background color to the styled component div if state active is true.

i am doing it like so

```<code>function Main() {
    const [active, setActive] = useState(false);
    return (
        <ChildComponent
            active={active}/>
    );
}

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color: grey';}
`;
</code>```

This works fine. but instead of just passing string grey to background color i want to pass props like below.

```<code>const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color:'${(props: any) =>
    props.theme.colors.grey.light3}};

`;
</code>```

This is not the right syntax to do it. could someone help me fix this thanks.

答:
You can nest template literals within template literals as long as they're located inside an interpolated expression block (${...}).

So your code should look like this:

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active, ...props }) => active && `background-color: ${(props: any) =>
    props.theme.colors.grey.light3}`};

`;
```

Body:
i want to add a background color to the styled component div if state active is true.

i am doing it like so

function Main() {
    const [active, setActive] = useState(false);
    return (
        <ChildComponent
            active={active}/>
    );
}

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color: grey';}
`;

This works fine. but instead of just passing string grey to background color i want to pass props like below.

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color:'${(props: any) =>
    props.theme.colors.grey.light3}};

`;

This is not the right syntax to do it. could someone help me fix this thanks.


问:
Can't resolve a local npm module made by npm pack
I created a local module using npm pack, which created a package: "org-header-0.0.3.tgz"

In a React project, I added org-header to its package.json:

```<code>"dependencies": {
  "org-header": "file:[path-to-org-header]/org-header-0.0.3.tgz",
 ...
}
</code>```

It installs fine. However, when I try to use it:

```<code>import Header from 'org-header';

...
</code>```

However when I do npm run start:

```<code>Failed to compile.

./src/components/Layout.js
Module not found: Can't resolve 'org-header' in '/Users/imyjimmy/***/src/components'
</code>```

Could it be because:

I did not structure the org-header project correctly

Webpack is doing something weird

Both?

答:
I also encounter the same issue the other day. Just post my solution here if it helps.

So I'm testing a local dependency (project B) update in my main project (project A) through

npm pack --> generate the tgz file

refer the tgz file in the project A's package.json as above question shows

run npm install in project A to unpack the package -- installation works fine

run into below error when npm develop

Generating development JavaScript bundle failed
Can't resolve 'project B' in '/Users/xxx@xxx.com/projectA/src/pages'
```

What this error indicates is that the package Project A does not exist.
This is weird because when I ran npm list project B  I actually got the confirmation that it exists.

The solution is to explicitly install project B again e.g.npm install project B , instead of running npm install after you change the package.json in step 3.

I don't know if it's webpack got confused by the 2 packages or somewhat, but the solution solved my problem .

Body:
I created a local module using npm pack, which created a package: "org-header-0.0.3.tgz"

In a React project, I added org-header to its package.json:

"dependencies": {
  "org-header": "file:[path-to-org-header]/org-header-0.0.3.tgz",
 ...
}

It installs fine. However, when I try to use it:

import Header from 'org-header';

...

However when I do npm run start:

Failed to compile.

./src/components/Layout.js
Module not found: Can't resolve 'org-header' in '/Users/imyjimmy/***/src/components'

Could it be because:

I did not structure the org-header project correctly

Webpack is doing something weird

Both?

Body:
I also encounter the same issue the other day. Just post my solution here if it helps.

So I'm testing a local dependency (project B) update in my main project (project A) through

npm pack --> generate the tgz file

refer the tgz file in the project A's package.json as above question shows

run npm install in project A to unpack the package -- installation works fine

run into below error when npm develop

Generating development JavaScript bundle failed
Can't resolve 'project B' in '/Users/xxx@xxx.com/projectA/src/pages'

What this error indicates is that the package Project A does not exist.
This is weird because when I ran npm list project B  I actually got the confirmation that it exists.

The solution is to explicitly install project B again e.g.npm install project B , instead of running npm install after you change the package.json in step 3.

I don't know if it's webpack got confused by the 2 packages or somewhat, but the solution solved my problem .


问:
Select 2: How to create an option which already exists in the list
I have a select with tags:true, multiple, populated from a database. Now new option can be created only if it is not already exists in the list. Created option is first in the list new option while not exists But I can't create option with the same text which is shown here

How could I achieve this?

Updated: link to the tagging documentation https://select2.org/tagging

答:
You need to set value, and then it works:

```<code>var lastId = $(".selectExample option").length + 1
var newState = new Option('Orange', lastId, true, true);
$(".selectExample").append(newState).trigger('change');
</code>```

See full example in playground: https://jsfiddle.net/denisstukalov/phnk05od/9/#&togetherjs=sfjozzpr9N

Body:
You need to set value, and then it works:

var lastId = $(".selectExample option").length + 1
var newState = new Option('Orange', lastId, true, true);
$(".selectExample").append(newState).trigger('change');

See full example in playground: https://jsfiddle.net/denisstukalov/phnk05od/9/#&togetherjs=sfjozzpr9N


问:
OutOfMemoryException In Azure Function
I am pulling data from workday using code below and storing them in User List for processing :

```<code>  Workday_Common_HeaderType header = new Workday_Common_HeaderType();
            //Fill the Workday header at your wish (omitted for code clarity)

            header.Include_Reference_Descriptors_In_ResponseSpecified = true;
            header.Include_Reference_Descriptors_In_Response = true;
            //Setting up request criteria to use Country
            var request = new Get_Workers_RequestType { version = "v33.2" };
            gremlinQueries.Clear();
            //Fill the Workday request at your wish (omitted for code clarity)
            request.Response_Filter = new Response_FilterType();
            request.Response_Group = new Worker_Response_GroupType();
            request.Response_Group.Include_Management_Chain_Data = true;
            request.Response_Group.Include_Management_Chain_DataSpecified = true;
            request.Response_Group.Include_Multiple_Managers_in_Management_Chain_DataSpecified = true;
            request.Response_Group.Include_Multiple_Managers_in_Management_Chain_Data = true;
            request.Response_Group.Include_Personal_InformationSpecified = true;
            request.Response_Group.Include_Personal_Information = true;
            request.Response_Group.Include_Employment_InformationSpecified = true;
            request.Response_Group.Include_Employment_Information = true;
            request.Response_Group.Include_RolesSpecified = true;
            //request.Response_Group.Include_Development_ItemsSpecified = true;
            //request.Response_Group.Include_Development_Items = true;
            request.Response_Group.Include_RolesSpecified = true;
            request.Response_Group.Include_Roles = true;
            request.Response_Group.Include_OrganizationsSpecified = true;
            request.Response_Group.Include_Organizations = true;
            request.Response_Group.Include_Employment_InformationSpecified = true;

            request.Response_Group.Include_Employment_Information = true;
           int totalResults = 0;
            for (int i = 1; i < totalPages; i++)
            {

                request.Response_Filter.Page = i;
                request.Response_Filter.Count = test ? 14 : 500; //500 page count per request
                //   request.Response_Group.Include_Management_Chain_Data
                request.Response_Filter.CountSpecified = true;
                request.Response_Filter.PageSpecified = true;
                //Invoke HR getworker api via Proxy

                var workers = proxy.Get_Workers(header, request);
                if (test != true)
                    totalPages = (int)workers.Response_Results.Total_Pages + 1;
                totalResults = (int)workers.Response_Results.Total_Results;
                if (workers.Response_Data == null)
                {
                    break;
                }

                foreach (var worker in workers.Response_Data)
                {

                    User user = new User();
                    user.StillHired = worker.Worker_Data.Employment_Data.Worker_Status_Data.Active;
                    user.HireDate = worker.Worker_Data.Employment_Data.Worker_Status_Data.Hire_Date;
</code>```

now locally I run it with no issues but when I deploy it in Azure I receive error outofmemory exception after an hour also the function status is always error.
Function is running using an AppServicePlan 7GB memory.
Exception :

Exception while executing function: ExportWorkday System.OutOfMemoryException at Human_ResourcesPort.Get_Workers

答:
You can view the memory utilization in Azure portal->your app service-> Metrics.

If the memory is exhausted, you can scale up the service plan or move the function app to another hosting plan to solve this issue.

If the issue still exist, you can run the function app locally and monitor the memory usage to see if there are some issues of the code itself.

Title: OutOfMemoryException In Azure Function

Body:
I am pulling data from workday using code below and storing them in User List for processing :

  Workday_Common_HeaderType header = new Workday_Common_HeaderType();
            //Fill the Workday header at your wish (omitted for code clarity)

            header.Include_Reference_Descriptors_In_ResponseSpecified = true;
            header.Include_Reference_Descriptors_In_Response = true;
            //Setting up request criteria to use Country
            var request = new Get_Workers_RequestType { version = "v33.2" };
            gremlinQueries.Clear();
            //Fill the Workday request at your wish (omitted for code clarity)
            request.Response_Filter = new Response_FilterType();
            request.Response_Group = new Worker_Response_GroupType();
            request.Response_Group.Include_Management_Chain_Data = true;
            request.Response_Group.Include_Management_Chain_DataSpecified = true;
            request.Response_Group.Include_Multiple_Managers_in_Management_Chain_DataSpecified = true;
            request.Response_Group.Include_Multiple_Managers_in_Management_Chain_Data = true;
            request.Response_Group.Include_Personal_InformationSpecified = true;
            request.Response_Group.Include_Personal_Information = true;
            request.Response_Group.Include_Employment_InformationSpecified = true;
            request.Response_Group.Include_Employment_Information = true;
            request.Response_Group.Include_RolesSpecified = true;
            //request.Response_Group.Include_Development_ItemsSpecified = true;
            //request.Response_Group.Include_Development_Items = true;
            request.Response_Group.Include_RolesSpecified = true;
            request.Response_Group.Include_Roles = true;
            request.Response_Group.Include_OrganizationsSpecified = true;
            request.Response_Group.Include_Organizations = true;
            request.Response_Group.Include_Employment_InformationSpecified = true;

            request.Response_Group.Include_Employment_Information = true;
           int totalResults = 0;
            for (int i = 1; i < totalPages; i++)
            {

                request.Response_Filter.Page = i;
                request.Response_Filter.Count = test ? 14 : 500; //500 page count per request
                //   request.Response_Group.Include_Management_Chain_Data
                request.Response_Filter.CountSpecified = true;
                request.Response_Filter.PageSpecified = true;
                //Invoke HR getworker api via Proxy

                var workers = proxy.Get_Workers(header, request);
                if (test != true)
                    totalPages = (int)workers.Response_Results.Total_Pages + 1;
                totalResults = (int)workers.Response_Results.Total_Results;
                if (workers.Response_Data == null)
                {
                    break;
                }

                foreach (var worker in workers.Response_Data)
                {

                    User user = new User();
                    user.StillHired = worker.Worker_Data.Employment_Data.Worker_Status_Data.Active;
                    user.HireDate = worker.Worker_Data.Employment_Data.Worker_Status_Data.Hire_Date;

now locally I run it with no issues but when I deploy it in Azure I receive error outofmemory exception after an hour also the function status is always error.
Function is running using an AppServicePlan 7GB memory.
Exception :

Exception while executing function: ExportWorkday System.OutOfMemoryException at Human_ResourcesPort.Get_Workers


问:
A valid provisioning profile for this executable was not found for debug mode
I am getting this error while I am trying to debug my app on device.

I created development provisioning profile as it is mentioned at the developer portal. My development device is selected in the profile and I am selecting the correct profile from Target's code signing identity menu. I recreated provisioning profile for several times and also removed and reinstalled it and recreated the project but I am getting that whenever I try to debug on device.

Btw, the adhoc distribution provision profile works.

I spent my whole day to find out a solution but nothing. Anyone have a solution?

答:
In my case, I was setting "Embed Without Signing" on some frameworks in "Project -> General -> Frameworks, Libraries, and Embedded Content" tab, which causes unknown conflicts in the project.

It finally works when I set "Embed and Sign" to those frameworks which needed to be embedded.


问:
can't load svg from filepath in json file
I'm trying to load SVG image from JSON file that contains a path like this -

```<code><img src="../images/filename.svg"/>
</code>```

and the image doesn't load.

When i try to do this it works-

```<code><img src="/static/media/filename.9f72c13b.svg"/>
</code>```

What is the difference? Why does the second work and the first doesn't ?
Is there a way to change all of the first paths to be like the second?

Thank you!

答:
../ in a path means one level up from the current folder. So your first path is a relative path, and the second one is an absolute path. Besides, those are pointing to 2 different file-names (filename.svg and filename.9f72c13b.svg). First, you need to figure out to which file you want to refer, and then make sure it's present in that your specified location.

Is there a way to change all of the first paths to be like the second?

Yes, you can just use a simple text-replacing feature of your text-editor, say for example notepad++ which can do replace text with regular expressions and in multiple files simultaneously.

A note about the 'current directory': it's a bad idea to rely on assumptions about it, because on some platforms it may not be what you want, or it may even change from version to version.

Body:
I'm trying to load SVG image from JSON file that contains a path like this -

and the image doesn't load.

When i try to do this it works-

What is the difference? Why does the second work and the first doesn't ?
Is there a way to change all of the first paths to be like the second?

Thank you!


问:
How to access a parent value inside an array in yup validation
I have defined a yup schema

```<code>export const ValidationSchema = yup.object().shape({
    dateTo: yup
        .date()
        .required(MandatoryFieldMessage)

   uebernachtungen: yup.array().of(
     yup.object().shape({
     ort: yup
            .string()
            .trim()
            .max(100, Maximum100CharactersMessage)
            .required(MandatoryFieldMessage),

    bis: yup
            .date()
            .required(MandatoryFieldMessage)
            .max(yup.ref("dateTo"), "display message") }))
})
</code>```

I just want to use the value of dateTo inside the array, so that all the bis in the uebernachtungen will not be allow do have a value greater than dateTo.

The problem is that I can access items inside the array like ort but I cannot access items out of it like dateTo.

So in this case yup.ref("dateTo") will return undefined but yup.ref("ort") will be correct. It seems that array has its own context and I cannot access to the parent context.

How would be this possible?

答:
I came through similar issue. I used this workthrough with success.

Idea: Pass whole form-data as a context to the schema and access any form value using

this.options.context

```<code> const ValidationSchema = yup.object().shape({
     dateTo: yup
         .date()
         .required(MandatoryFieldMessage)

     uebernachtungen: yup.array().of(
         yup.object().shape({
             ort: yup
                 .string()
                 .trim()
                 .max(100, Maximum100CharactersMessage)
                 .required(MandatoryFieldMessage),

             bis: yup
                 .date()
                 .required(MandatoryFieldMessage)
                 .test('dateToCheck', 'display message', function (value) {
                    // access dateTo from passed context
                   if(value>this.options.context.dateTo) return false
                   return true }),

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

Passing Context

Without Formik

Send your Form data as a context while validating

```<code> ValidationSchema.validateSync(data, {context: form_data})
</code>```

With Formik

Use validate instead of validationSchema

Pass your Form data as 4th argument in validateYupSchema which represents context and can be accessed later in schema.

Pass your schema as 2nd argument in validateYupSchema.

```<code>    <Formik
      validate={(value) => {
        try {
          validateYupSchema(value, ValidationSchema, true, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />
</code>```

Body:
I have defined a yup schema

export const ValidationSchema = yup.object().shape({
    dateTo: yup
        .date()
        .required(MandatoryFieldMessage)

   uebernachtungen: yup.array().of(
     yup.object().shape({
     ort: yup
            .string()
            .trim()
            .max(100, Maximum100CharactersMessage)
            .required(MandatoryFieldMessage),

    bis: yup
            .date()
            .required(MandatoryFieldMessage)
            .max(yup.ref("dateTo"), "display message") }))
})

I just want to use the value of dateTo inside the array, so that all the bis in the uebernachtungen will not be allow do have a value greater than dateTo.

The problem is that I can access items inside the array like ort but I cannot access items out of it like dateTo.

So in this case yup.ref("dateTo") will return undefined but yup.ref("ort") will be correct. It seems that array has its own context and I cannot access to the parent context.

How would be this possible?

Body:
I came through similar issue. I used this workthrough with success.

Idea: Pass whole form-data as a context to the schema and access any form value using

this.options.context

 const ValidationSchema = yup.object().shape({
     dateTo: yup
         .date()
         .required(MandatoryFieldMessage)

     uebernachtungen: yup.array().of(
         yup.object().shape({
             ort: yup
                 .string()
                 .trim()
                 .max(100, Maximum100CharactersMessage)
                 .required(MandatoryFieldMessage),

             bis: yup
                 .date()
                 .required(MandatoryFieldMessage)
                 .test('dateToCheck', 'display message', function (value) {
                    // access dateTo from passed context
                   if(value>this.options.context.dateTo) return false
                   return true }),

         })) })

Passing Context

Without Formik

Send your Form data as a context while validating

 ValidationSchema.validateSync(data, {context: form_data})

With Formik

Use validate instead of validationSchema

Pass your Form data as 4th argument in validateYupSchema which represents context and can be accessed later in schema.

Pass your schema as 2nd argument in validateYupSchema.

    <Formik
      validate={(value) => {
        try {
          validateYupSchema(value, ValidationSchema, true, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />


问:
How to read file using NPOI
I found NPOI is very good to write Excel files with C#.

But I want to open, read and modify Excel files in C#.

How can I do this?

答:
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions</p>

```<code>var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
  // map singleItem
  return new OrderDetails()
  {
    Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),

    // use reusable mapper for re-curring scenarios
    Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),

    Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
    Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
    Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
    UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
    Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),

    // read date and total as string, as they're displayed/formatted on the excel
    DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
    TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
  };
});
</code>```

Title: How to read file using NPOI

Body:
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions

var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
  // map singleItem
  return new OrderDetails()
  {
    Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),

    // use reusable mapper for re-curring scenarios
    Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),

    Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
    Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
    Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
    UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
    Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),

    // read date and total as string, as they're displayed/formatted on the excel
    DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
    TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
  };
});


问:
Resilience4j Retry+Spring Boot 2 application.yml config not applied
I'm using Resilience4j @Retry combined with @CircuitBreaker.
I use annotations in SpringBoot 2 and my configuration is in application.yml.
I have a fallback method in the @Retry annotation, but not in the @CircuitBreaker (That's the way to make them work together because of the aspect order as per my findings).

The @CircuitBreaker works fine using my configuration in application.yml.
The Retry also works but does use only the default config values and do not reflect the values in the application.yml (EX.: maxAttempts is 3 instead of 5).

Any idea what I may be doing wrong here, please?

In the code:

```<code>@CircuitBreaker(name = "myService")
@Retry(name = "myService", fallbackMethod="myServiceFallback")
public HttpEntity myService(final String url) throws MyException{
//My logic
}
</code>```

The config in application.yml

答:
Sorted out.

I was using
maxAttempts in the configuration as mentioned here :
https://resilience4j.readme.io/docs/retry

Where the proper config name is maxRetryAttempts as shown here:
https://github.com/resilience4j/resilience4j-spring-boot2-demo/blob/master/src/main/resources/application.yml

```<code>resilience4j.retry:
    configs:
        default:
            maxRetryAttempts: 3
            waitDuration: 100
...
</code>```

Body:
I'm using Resilience4j @Retry combined with @CircuitBreaker.
I use annotations in SpringBoot 2 and my configuration is in application.yml.
I have a fallback method in the @Retry annotation, but not in the @CircuitBreaker (That's the way to make them work together because of the aspect order as per my findings).

The @CircuitBreaker works fine using my configuration in application.yml.
The Retry also works but does use only the default config values and do not reflect the values in the application.yml (EX.: maxAttempts is 3 instead of 5).

Any idea what I may be doing wrong here, please?

In the code:

@CircuitBreaker(name = "myService")
@Retry(name = "myService", fallbackMethod="myServiceFallback")
public HttpEntity myService(final String url) throws MyException{
//My logic
}

The config in application.yml

Body:
Sorted out.

I was using
maxAttempts in the configuration as mentioned here :
https://resilience4j.readme.io/docs/retry

Where the proper config name is maxRetryAttempts as shown here:
https://github.com/resilience4j/resilience4j-spring-boot2-demo/blob/master/src/main/resources/application.yml

resilience4j.retry:
    configs:
        default:
            maxRetryAttempts: 3
            waitDuration: 100
...


问:
Checkbox update value only works on false to true, not on true to false, React, mongoDB
I use a state as a form to update boolean data in MongoDB.
Only works when the value is updated from false to true, not work from true to false.
Is there somebody who can help me out? Thanks a lot.

Here is my state as a form

```<code>const [user, setUser] = useState({
    name: '',
    email: '',
    password: '',
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false,
  });
</code>```

Here is onChange func

```<code> const onChangeCB = (e) => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };
</code>```

The checkbox

```<code>   <input
        type='checkbox'
        name='cases'
        checked={cases === true}
        onChange={onChangeCB}
      />{' '}
      Case{' '}
      <input
        type='checkbox'
        name='mtrl'
        checked={mtrl === true}
        onChange={onChangeCB}
      />{' '}
      Material{' '}
      <input
        type='checkbox'
        name='cst'
        checked={cst === true}
        onChange={onChangeCB}
      />{' '}
      Cunsumption{' '}
      <input
        type='checkbox'
        name='mp'
        checked={mp === true}
        onChange={onChangeCB}
      />{' '}
      Material Price{' '}
      <input
        type='checkbox'
        name='po'
        checked={po === true}
        onChange={onChangeCB}
      />{' '}
</code>```

答:
```<code>const onChangeCB = (e) => {
    const { name, checked } = e.target;
    setUser({ ...user, [name]: checked ? true : false });
};
</code>```

Body:
I use a state as a form to update boolean data in MongoDB.
Only works when the value is updated from false to true, not work from true to false.
Is there somebody who can help me out? Thanks a lot.

Here is my state as a form

const [user, setUser] = useState({
    name: '',
    email: '',
    password: '',
    cases: false,
    mtrl: false,
    cst: false,
    mp: false,
    po: false,
  });

Here is onChange func

 const onChangeCB = (e) => {
    if (!e.target.checked) {
      setUser({ ...user, [e.target.name]: false });
    } else if (e.target.checked) {
      setUser({ ...user, [e.target.name]: true });
    }
  };

The checkbox

   <input
        type='checkbox'
        name='cases'
        checked={cases === true}
        onChange={onChangeCB}
      />{' '}
      Case{' '}
      <input
        type='checkbox'
        name='mtrl'
        checked={mtrl === true}
        onChange={onChangeCB}
      />{' '}
      Material{' '}
      <input
        type='checkbox'
        name='cst'
        checked={cst === true}
        onChange={onChangeCB}
      />{' '}
      Cunsumption{' '}
      <input
        type='checkbox'
        name='mp'
        checked={mp === true}
        onChange={onChangeCB}
      />{' '}
      Material Price{' '}
      <input
        type='checkbox'
        name='po'
        checked={po === true}
        onChange={onChangeCB}
      />{' '}


问:
Changing The Size of Twitter's Follow Button?
I'm looking at the new Twitter Follow Button (https://twitter.com/about/resources/followbutton), but unfortunately my sidebar is smaller than the default size, thus throwing my whole site out of whack.  </p>

<p>Is there an easy way to hack the script to resize the button, or at least to put a line break between the actual follow button and the account name?  </p>

答:
I'd wrap the button in a container with a nice class name and use CSS to adjust the styling.

```<code>.twitter-button-container{
  width: 100px;
  height:100px;
}
</code>```

Something like that.

UPDATE

On second thought, it seems that the image is a background image to the anchor tag. I don't think it's possible to resize background images using CSS etc. You'd need to have the image in an img tag.

Body:
I'm looking at the new Twitter Follow Button (https://twitter.com/about/resources/followbutton), but unfortunately my sidebar is smaller than the default size, thus throwing my whole site out of whack.

Is there an easy way to hack the script to resize the button, or at least to put a line break between the actual follow button and the account name?

Body:
I'd wrap the button in a container with a nice class name and use CSS to adjust the styling.

.twitter-button-container{
  width: 100px;
  height:100px;
}

Something like that.

UPDATE

On second thought, it seems that the image is a background image to the anchor tag. I don't think it's possible to resize background images using CSS etc. You'd need to have the image in an img tag.


问:
starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory":
I am trying to build an docker image on centos 7 from SCRATCH. I have performed following steps :

```<code>FROM scratch
RUN rpm -ivh https://address/app.rpm
RUN YUM install tools
...
...
CMD ["rpm","start"]
</code>```

After executing this , I tried to build this dockerfile with command
"docker build -t testsid -f ./dockerfile ."

Now I see following error :

```<code>Sending build context to Docker daemon  3.072kB
Step 1/16 : FROM scratch
 --->
Step 2/16 : RUN rpm -ivh https://address/app.rpm
 ---> Running in d25a0a879d9e
OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown
</code>```

Please let me know whether anyone has suggestion regarding this. ?

Any input will be really helpful.

Thank you.

答:
FROM scratch starts from a totally empty image.  The only things that will be in the container filesystem at all are files in /dev, /proc, and /etc that Docker automatically provides.  When you say rpm, that command doesn't exist.  A string-form RUN command gets wrapped in /bin/sh -c ..., but there is no /bin directory.

FROM scratch is a somewhat advanced use of Docker.  If you're very comfortable with concepts like statically-linked binaries and the differences between bare-string and JSON-array CMD, you can use it to make an extremely small image.  For most typical uses you'll want to at least start from something with some sort of distribution and package manager.

If you need Red Hat's package management tools, the easiest Docker Hub image to start from will be centos:

```<code>FROM centos:8 # includes rpm, yum, /bin directory
RUN rpm -ivh https://address/app.rpm
RUN yum install tools
...
</code>```

Body:
I am trying to build an docker image on centos 7 from SCRATCH. I have performed following steps :

FROM scratch
RUN rpm -ivh https://address/app.rpm
RUN YUM install tools
...
...
CMD ["rpm","start"]

After executing this , I tried to build this dockerfile with command
"docker build -t testsid -f ./dockerfile ."

Now I see following error :

Sending build context to Docker daemon  3.072kB
Step 1/16 : FROM scratch
 --->
Step 2/16 : RUN rpm -ivh https://address/app.rpm
 ---> Running in d25a0a879d9e
OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown

Please let me know whether anyone has suggestion regarding this. ?

Any input will be really helpful.

Thank you.

Body:
FROM scratch starts from a totally empty image.  The only things that will be in the container filesystem at all are files in /dev, /proc, and /etc that Docker automatically provides.  When you say rpm, that command doesn't exist.  A string-form RUN command gets wrapped in /bin/sh -c ..., but there is no /bin directory.

FROM scratch is a somewhat advanced use of Docker.  If you're very comfortable with concepts like statically-linked binaries and the differences between bare-string and JSON-array CMD, you can use it to make an extremely small image.  For most typical uses you'll want to at least start from something with some sort of distribution and package manager.

If you need Red Hat's package management tools, the easiest Docker Hub image to start from will be centos:

FROM centos:8 # includes rpm, yum, /bin directory
RUN rpm -ivh https://address/app.rpm
RUN yum install tools
...


问:
Mapply error after updating R and tidyverse
I have been working on a rejection sampling code using several loops.
After updating R and tidyverse I found that the code no longer works, displaying the following error:

```<code>Error: Assigned data `mapply(...)` must be compatible with existing data.
i Error occurred for column `sampled`.
x Can't convert from <integer> to <logical> due to loss of precision.
* Locations: 1.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In seq.default(x, y, na.rm = TRUE) :
 extra argument ‘na.rm’ will be disregarded
</code>```

The code worked previously, and is related to a previous question, linked [here][1].
I have tried to work through (avoid) the issue by using older versions of R (3.6) and tidyverse (1.3.0), but now I have some additional packages that I need to use which are incompatible with older versions of R. I'm not looking to rework the entire code, and I hoping that it will only take a few tweaks to get it working with the newer versions of R and tidyverse.

Edit I made a mistake regarding the initial df I provided for this question. Columns ID, After_1, and After_2 should have contained a combination of letters and numbers instead of only numbers. The example df has been updated.

Here is a modified code example that is displaying the same errors as my actual code:

```<code>df <- dfsource
temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

  row_list<-as.list(1:nrow(temp_df))
  q<-0

  while(length(row_list)!=0 & q<10){
    q<-q+1 #to make sure that we don't spinning off in an infinite loop
    for(j in row_list){ #this loop replaces the check values
      skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
      for(k in 4:5){ #checking the topoafter columns
        if(is.na(temp_df[j,k])){
          # print("NA break")
          # print(i)
          break
        } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
          # print("integer next")
          next
          # print("integer next")
        } else if(temp_df[j,k]==""){ #check for blank values
          # print("empty string next")
          temp_df[j,k]<-NA #if blank value found, replace with NA
          # print("fixed blank to NA")
          next
        }
        else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
          skip_flag<-TRUE
          # print("skip flag set")
        } else {
          temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
          # print("successful check value grab")
        } #if-else
      } #k for loop
      if(skip_flag==FALSE){
        row_list<-row_list[row_list!=j]
      } else {
        next
      }

      #sampling section
      if(skip_flag==FALSE){
        temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
          sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
        temp_df[j,7]<-i #identifying the run number

        if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
          # print(j)
          while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
            temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
              sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
          } #while
          temp_df[j,7]=i
        }#if
      }
    } #j for loop
  } #while loop wrapper around j loop
  if(i==1){
    df2<-temp_df
  }else{
    df2<-rbind(df2,temp_df)
  }#else

  #blank out temp_df to prepare for another run
  temp_df<-df
  temp_df$sampled <- NA
  temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop
</code>```

And here is the sample data to use which I would read in as dfsource:

```<code>structure(list(ID = c("A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16",
"A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25",
"A26", "A27", "A28", "A29", "A30"), Start = c(1, 1, 1, 1, 1,
50, 50, 50, 50, 50, 100, 100, 100, 100, 100, 200, 200, 300, 250,
350, 300, 300, 400, 500, 400, 400, 450, 500, 550, 500), End = c(1000,
1000, 1000, 1000, 1000, 950, 950, 950, 950, 950, 1000, 1000,
1000, 1000, 900, 800, 900, 750, 650, 650, 600, 850, 700, 600,
600, 700, 550, 550, 600, 550), After_1 = c("A3", "", "", "",
"A3", "", "", "", "", "", "", "A11", "", "A11", "", "", "", "",
"", "", "", "A21", "", "", "", "", "", "", "", "A28"), After_2 = c("",
"", "", "", "A2", "", "", "", "", "", "", "", "", "A12", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    sampled = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -30L), spec = structure(list(cols = list(
    ID = structure(list(), class = c("collector_character", "collector"
    )), Start = structure(list(), class = c("collector_double",
    "collector")), End = structure(list(), class = c("collector_double",
    "collector")), After_1 = structure(list(), class = c("collector_character",
    "collector")), After_2 = structure(list(), class = c("collector_character",
    "collector")), sampled = structure(list(), class = c("collector_logical",
    "collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```

  [1]: https://stackoverflow.com/questions/58653809/sample-using-start-and-end-values-within-a-loop-in-r
```

答:
EDIT: Initialize sampled as NA_integer_:

temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA_integer_ #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

    row_list<-as.list(1:nrow(temp_df))
    q<-0

    while(length(row_list)!=0 & q<10){
        q<-q+1 #to make sure that we don't spinning off in an infinite loop
        for(j in row_list){ #this loop replaces the check values
            skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
            for(k in 4:5){ #checking the topoafter columns
                if(is.na(temp_df[j,k])){
                    break
                } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
                    # print("integer next")
                    next
                    # print("integer next")
                } else if(temp_df[j,k]==""){ #check for blank values
                    # print("empty string next")
                    temp_df[j,k]<-NA #if blank value found, replace with NA
                    # print("fixed blank to NA")
                    next
                }
                else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
                    skip_flag<-TRUE
                    # print("skip flag set")
                } else {
                    temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
                    # print("successful check value grab")
                } #if-else
            } #k for loop
            if(skip_flag==FALSE){
                row_list<-row_list[row_list!=j]
            } else {
                next
            }
            #sampling section
            if(skip_flag==FALSE){
                temp_df[j,6]<-sample(temp_df$Start[j]:temp_df$End[j],1)
                temp_df[j,7]<-i #identifying the run number

                if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
                    # print(j)
                    while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
                        temp_df[j,6]<-sample(temp_df$Start[j]:temp_df$End[j],1)
                    } #while
                    temp_df[j,7]=i
                }#if
            }
        } #j for loop
    } #while loop wrapper around j loop
    if(i==1){
        df2<-temp_df
    }else{
        df2<-rbind(df2,temp_df)
    }#else

    #blank out temp_df to prepare for another run
    temp_df<-df
    temp_df$sampled <- NA_integer_
    temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop

```

<p>Looking at the first question you had (Sample using start and end values within a loop in R), I am not quite sure why you need <code>mapply</code> if you are already looping row by row. Why not just something like in this example:</p>

<pre class="lang-r prettyprint-override"><code>set.seed(1)
df <- structure(list(ID = structure(1:14, .Label = c("a", "b", "c",
                                                                                "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"), class = "factor"),
                                         start = c(25L, 36L, 23L, 15L, 21L, 43L, 39L, 27L, 11L, 21L,
                                                            28L, 44L, 16L, 25L), end = c(67L, 97L, 85L, 67L, 52L, 72L,
                                                                                55L, 62L, 99L, 89L, 65L, 58L, 77L, 88L)), class = "data.frame", row.names = c(NA, -14L))

df$sample <- NA

for (row in 1:nrow(df)) {
    df$sample[row] <- sample(df$start[row]:df$end[row], 1)
}

df
#>    ID start end sample
#> 1   a    25  67     28
#> 2   b    36  97     74
#> 3   c    23  85     23
#> 4   d    15  67     48
#> 5   e    21  52     49
#> 6   f    43  72     65
#> 7   g    39  55     49
#> 8   h    27  62     40
#> 9   i    11  99     92
#> 10  j    21  89     79
#> 11  k    28  65     60
#> 12  l    44  58     48
#> 13  m    16  77     36
#> 14  n    25  88     66
</code>```

Created on 2020-06-02 by the reprex package (v0.3.0)

If that works, then hopefully you won't have the error associated with mapply anymore.

Body:
I have been working on a rejection sampling code using several loops.
After updating R and tidyverse I found that the code no longer works, displaying the following error:

Error: Assigned data `mapply(...)` must be compatible with existing data.
i Error occurred for column `sampled`.
x Can't convert from <integer> to <logical> due to loss of precision.
* Locations: 1.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In seq.default(x, y, na.rm = TRUE) :
 extra argument ‘na.rm’ will be disregarded

The code worked previously, and is related to a previous question, linked [here][1].
I have tried to work through (avoid) the issue by using older versions of R (3.6) and tidyverse (1.3.0), but now I have some additional packages that I need to use which are incompatible with older versions of R. I'm not looking to rework the entire code, and I hoping that it will only take a few tweaks to get it working with the newer versions of R and tidyverse.

Edit I made a mistake regarding the initial df I provided for this question. Columns ID, After_1, and After_2 should have contained a combination of letters and numbers instead of only numbers. The example df has been updated.

Here is a modified code example that is displaying the same errors as my actual code:

df <- dfsource
temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

  row_list<-as.list(1:nrow(temp_df))
  q<-0

  while(length(row_list)!=0 & q<10){
    q<-q+1 #to make sure that we don't spinning off in an infinite loop
    for(j in row_list){ #this loop replaces the check values
      skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
      for(k in 4:5){ #checking the topoafter columns
        if(is.na(temp_df[j,k])){
          # print("NA break")
          # print(i)
          break
        } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
          # print("integer next")
          next
          # print("integer next")
        } else if(temp_df[j,k]==""){ #check for blank values
          # print("empty string next")
          temp_df[j,k]<-NA #if blank value found, replace with NA
          # print("fixed blank to NA")
          next
        }
        else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
          skip_flag<-TRUE
          # print("skip flag set")
        } else {
          temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
          # print("successful check value grab")
        } #if-else
      } #k for loop
      if(skip_flag==FALSE){
        row_list<-row_list[row_list!=j]
      } else {
        next
      }

      #sampling section
      if(skip_flag==FALSE){
        temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
          sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
        temp_df[j,7]<-i #identifying the run number

        if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
          # print(j)
          while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
            temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
              sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
          } #while
          temp_df[j,7]=i
        }#if
      }
    } #j for loop
  } #while loop wrapper around j loop
  if(i==1){
    df2<-temp_df
  }else{
    df2<-rbind(df2,temp_df)
  }#else

  #blank out temp_df to prepare for another run
  temp_df<-df
  temp_df$sampled <- NA
  temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop

And here is the sample data to use which I would read in as dfsource:

structure(list(ID = c("A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16",
"A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25",
"A26", "A27", "A28", "A29", "A30"), Start = c(1, 1, 1, 1, 1,
50, 50, 50, 50, 50, 100, 100, 100, 100, 100, 200, 200, 300, 250,
350, 300, 300, 400, 500, 400, 400, 450, 500, 550, 500), End = c(1000,
1000, 1000, 1000, 1000, 950, 950, 950, 950, 950, 1000, 1000,
1000, 1000, 900, 800, 900, 750, 650, 650, 600, 850, 700, 600,
600, 700, 550, 550, 600, 550), After_1 = c("A3", "", "", "",
"A3", "", "", "", "", "", "", "A11", "", "A11", "", "", "", "",
"", "", "", "A21", "", "", "", "", "", "", "", "A28"), After_2 = c("",
"", "", "", "A2", "", "", "", "", "", "", "", "", "A12", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    sampled = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -30L), spec = structure(list(cols = list(
    ID = structure(list(), class = c("collector_character", "collector"
    )), Start = structure(list(), class = c("collector_double",
    "collector")), End = structure(list(), class = c("collector_double",
    "collector")), After_1 = structure(list(), class = c("collector_character",
    "collector")), After_2 = structure(list(), class = c("collector_character",
    "collector")), sampled = structure(list(), class = c("collector_logical",
    "collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```

  [1]: https://stackoverflow.com/questions/58653809/sample-using-start-and-end-values-within-a-loop-in-r

Body:
EDIT: Initialize sampled as NA_integer_:

temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA_integer_ #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

    row_list<-as.list(1:nrow(temp_df))
    q<-0

    while(length(row_list)!=0 & q<10){
        q<-q+1 #to make sure that we don't spinning off in an infinite loop
        for(j in row_list){ #this loop replaces the check values
            skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
            for(k in 4:5){ #checking the topoafter columns
                if(is.na(temp_df[j,k])){
                    break
                } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
                    # print("integer next")
                    next
                    # print("integer next")
                } else if(temp_df[j,k]==""){ #check for blank values
                    # print("empty string next")
                    temp_df[j,k]<-NA #if blank value found, replace with NA
                    # print("fixed blank to NA")
                    next
                }
                else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
                    skip_flag<-TRUE
                    # print("skip flag set")
                } else {
                    temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
                    # print("successful check value grab")
                } #if-else
            } #k for loop
            if(skip_flag==FALSE){
                row_list<-row_list[row_list!=j]
            } else {
                next
            }
            #sampling section
            if(skip_flag==FALSE){
                temp_df[j,6]<-sample(temp_df$Start[j]:temp_df$End[j],1)
                temp_df[j,7]<-i #identifying the run number

                if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
                    # print(j)
                    while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
                        temp_df[j,6]<-sample(temp_df$Start[j]:temp_df$End[j],1)
                    } #while
                    temp_df[j,7]=i
                }#if
            }
        } #j for loop
    } #while loop wrapper around j loop
    if(i==1){
        df2<-temp_df
    }else{
        df2<-rbind(df2,temp_df)
    }#else

    #blank out temp_df to prepare for another run
    temp_df<-df
    temp_df$sampled <- NA_integer_
    temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop

Looking at the first question you had (Sample using start and end values within a loop in R), I am not quite sure why you need mapply if you are already looping row by row. Why not just something like in this example:

set.seed(1)
df <- structure(list(ID = structure(1:14, .Label = c("a", "b", "c",
                                                                                "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"), class = "factor"),
                                         start = c(25L, 36L, 23L, 15L, 21L, 43L, 39L, 27L, 11L, 21L,
                                                            28L, 44L, 16L, 25L), end = c(67L, 97L, 85L, 67L, 52L, 72L,
                                                                                55L, 62L, 99L, 89L, 65L, 58L, 77L, 88L)), class = "data.frame", row.names = c(NA, -14L))

df$sample <- NA

for (row in 1:nrow(df)) {
    df$sample[row] <- sample(df$start[row]:df$end[row], 1)
}

df
#>    ID start end sample
#> 1   a    25  67     28
#> 2   b    36  97     74
#> 3   c    23  85     23
#> 4   d    15  67     48
#> 5   e    21  52     49
#> 6   f    43  72     65
#> 7   g    39  55     49
#> 8   h    27  62     40
#> 9   i    11  99     92
#> 10  j    21  89     79
#> 11  k    28  65     60
#> 12  l    44  58     48
#> 13  m    16  77     36
#> 14  n    25  88     66

Created on 2020-06-02 by the reprex package (v0.3.0)

If that works, then hopefully you won't have the error associated with mapply anymore.