问:
Insert the timestamp column in the scandate column?
I want to insert the timestamp column in the values of ScanDate column with Null values.

I need to use this in tableau and if I keep the values separetade, I got wrong results

```<code>select distinct A.RootDocId, A.LastEventAppId, A.LastEventStatus,
        case when B.Value = '' then A.Timestamp else
        PARSE_TIMESTAMP('%d/%m/%Y %H:%M:%S',
replace(regexp_replace(B.Value, '[/-]1([7-9]) ', '/201\\1 '), '-', '/'))
        end ScanDate, C.Value Federation, A.timestamp
from `serv.dam.documentroot` A
left join unnest(Metadata) B ON B.Key like 'ScanDate'
left join unnest(Metadata) C ON C.Key like '%ederation'
        limit 100
</code>```

I expected this :

Where Scandate is null, it should be replaced with the timestamp.

答:
Its usually better when using Tableau to model your relationships (joins) in your Tableau data source, and let the tool generate optimized SQL for your specific visualization. If you hand write your own SQL, Tableau will respect it of course, but not try to optimize it.

Almost anything you would do in mainstream SQL is available in Tableau without resorting to hand written SQL if you decide to explore that route. The Tableau calculation equivalent for SQL's Coalesce() is called IF_NULL().

Body:
I want to insert the timestamp column in the values of ScanDate column with Null values.

I need to use this in tableau and if I keep the values separetade, I got wrong results

select distinct A.RootDocId, A.LastEventAppId, A.LastEventStatus,
        case when B.Value = '' then A.Timestamp else
        PARSE_TIMESTAMP('%d/%m/%Y %H:%M:%S',
replace(regexp_replace(B.Value, '[/-]1([7-9]) ', '/201\\1 '), '-', '/'))
        end ScanDate, C.Value Federation, A.timestamp
from `serv.dam.documentroot` A
left join unnest(Metadata) B ON B.Key like 'ScanDate'
left join unnest(Metadata) C ON C.Key like '%ederation'
        limit 100

I expected this :

Where Scandate is null, it should be replaced with the timestamp.


来源: stackexchange

问:
Python dev_appserver cant import `.so` file (Pillow)
Inside my GAE application I try this:

```<code>from PIL import Image
</code>```

And get this:

```<code>Traceback (most recent call last):
  ...
  File "/home/sheena/Workspace/Waxed/code/waxed_backend/src/waxed_backend/concerns/misc/views.py", line 57, in home
    from PIL import Image
  File "libs/PIL/Image.py", line 56, in <module>
    from . import _imaging as core
  File "/home/sheena/Workspace/Waxed/venvs/wxt_comp/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 1024, in load_module
    raise ImportError('No module named %s' % fullname)
ImportError: No module named PIL._imaging
</code>```

/path/to/libs/PIL/imaging.so exists. And I have no problem importing anything else from that libs file from within dev_appserver.

And this works fine:

```<code>cd /path/to/libs/
python
>>> from PIL import Image
</code>```

I can only conclude that either dev_appserver somehow breaks impotrt functionality so that .so files aren't recognised.

Has anyone else seen this before? Any idea how to fix it?

答:
_imaging is a PIL dependency written in C. Because it's C and not Python, including the library in your lib folder won't work. You need to define that library in your app.yaml file:</p>

```<code>libraries:
   - name: PIL
     version: latest
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Inside my GAE application I try this:

from PIL import Image

And get this:

Traceback (most recent call last):
  ...
  File "/home/sheena/Workspace/Waxed/code/waxed_backend/src/waxed_backend/concerns/misc/views.py", line 57, in home
    from PIL import Image
  File "libs/PIL/Image.py", line 56, in <module>
    from . import _imaging as core
  File "/home/sheena/Workspace/Waxed/venvs/wxt_comp/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 1024, in load_module
    raise ImportError('No module named %s' % fullname)
ImportError: No module named PIL._imaging

/path/to/libs/PIL/imaging.so exists. And I have no problem importing anything else from that libs file from within dev_appserver.

And this works fine:

cd /path/to/libs/
python
>>> from PIL import Image

I can only conclude that either dev_appserver somehow breaks impotrt functionality so that .so files aren't recognised.

Has anyone else seen this before? Any idea how to fix it?

Body:
_imaging is a PIL dependency written in C. Because it's C and not Python, including the library in your lib folder won't work. You need to define that library in your app.yaml file:

libraries:
   - name: PIL
     version: latest

ContentLicense: CC BY-SA 4.0


问:
MySQL, PHP: echo IDs from smalest to largest
I have simple code in PHP and actual code throws all items from MySQL table with even ID and under it all items with odd ID.

And I need to all IDs with content will be listed from smallest to largest under themselves.

```<code>if( $db-> connect_error ) {
    die( "Not connected" . $db-> connect_error );
}

$sqlEven = "SELECT * FROM documents WHERE MOD (id,2)=0";
$resultEven = $db-> query($sqlEven);

if( $resultEven-> num_rows ) {
    while( $rowEven = $resultEven-> fetch_assoc() ) {
        echo $rowEven["id"] . "<li class=\"dark\"><a href=\"" . $rowEven["url"] . "\">" . $rowEven["name"] . "</a></li>";
    }
}

if( $db-> connect_error ) {
    die( "Not connected" . $db-> connect_error );
}

$sqlOdd = "SELECT * FROM documents WHERE MOD (id,2)<>0";
$resultOdd = $db-> query($sqlOdd);

if( $resultOdd-> num_rows ) {
    while( $rowOdd = $resultOdd-> fetch_assoc() ) {
        echo $rowOdd["id"] . "<li class=\"light\"><a href=\"" . $rowOdd["url"] . "\">" . $rowOdd["name"] . "</a></li>";
    }
}
</code>```

答:
You can reduce this to one query and check in PHP if the number is even or odd. Using a ternary operator, it can be done inline. Using ORDER BY MOD(id, 2), id (sort by even first, then ascending order), you get the data sorted by even and odd (see live fiddle: http://sqlfiddle.com/#!9/af25e5/2).

This way, you only need one query and one loop.

if ($db->connect_error) {
    die("Not connected: " . $db->connect_error);
}

$sql = "SELECT * FROM documents ORDER BY MOD(id, 2), id";
$result = $db->query($sql);

if ($result->num_rows) {
    while ($row = $result->fetch_assoc()) {
        echo $row["id"] . '
'.$row["name"]."
";
    }
}
```

Body:
I have simple code in PHP and actual code throws all items from MySQL table with even ID and under it all items with odd ID.

And I need to all IDs with content will be listed from smallest to largest under themselves.

if( $db-> connect_error ) {
    die( "Not connected" . $db-> connect_error );
}

$sqlEven = "SELECT * FROM documents WHERE MOD (id,2)=0";
$resultEven = $db-> query($sqlEven);

if( $resultEven-> num_rows ) {
    while( $rowEven = $resultEven-> fetch_assoc() ) {
        echo $rowEven["id"] . "
" . $rowEven["name"] . "
";
    }
}

if( $db-> connect_error ) {
    die( "Not connected" . $db-> connect_error );
}

$sqlOdd = "SELECT * FROM documents WHERE MOD (id,2)<>0";
$resultOdd = $db-> query($sqlOdd);

if( $resultOdd-> num_rows ) {
    while( $rowOdd = $resultOdd-> fetch_assoc() ) {
        echo $rowOdd["id"] . "
" . $rowOdd["name"] . "
";
    }
}

Body:
You can reduce this to one query and check in PHP if the number is even or odd. Using a ternary operator, it can be done inline. Using ORDER BY MOD(id, 2), id (sort by even first, then ascending order), you get the data sorted by even and odd (see live fiddle: http://sqlfiddle.com/#!9/af25e5/2).

This way, you only need one query and one loop.

if ($db->connect_error) {
    die("Not connected: " . $db->connect_error);
}

$sql = "SELECT * FROM documents ORDER BY MOD(id, 2), id";
$result = $db->query($sql);

if ($result->num_rows) {
    while ($row = $result->fetch_assoc()) {
        echo $row["id"] . '<li class="'.($row['id'] % 2 == 0 ? 'dark' : 'light').'"><a href="'.$row["url"].'">'.$row["name"]."</a></li>";
    }
}


问:
Error:android-apt plugin is incompatible with the Android Gradle plugin. Please use 'annotationProcessor'
```<code>apply plugin: 'com.android.application'
</code>```

apply plugin: 'realm-android'

android {
    compileSdkVersion 24
    buildToolsVersion '26.0.2'

```<code>defaultConfig {
    applicationId "com.kolhapur.news"
    minSdkVersion 14
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code>```

}

/* IMPORTANT :
 * Be careful when update dependencies, different version library may caused error /
dependencies {
    compile fileTree(dir: 'libs', include: ['.jar'])
    testCompile 'junit:junit:4.12'
    // google library
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:cardview-v7:24.1.1'
    compile 'com.android.support:recyclerview-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'
    compile 'com.google.android.gms:play-services-ads:9.2.1'
    compile 'com.google.android.gms:play-services-analytics:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'

```<code>// library for api
compile('com.squareup.retrofit2:retrofit:2.0.0-beta4') {
    exclude module: 'okhttp'
}**strong text**
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'

// ripple effect library
compile 'com.balysv:material-ripple:1.0.2'
</code>```

}

apply plugin: 'com.google.gms.google-services'

答:
Remove these lines

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

And

```<code>apply plugin: 'com.neenbedankt.android-apt'
</code>```

This works with me.

Body:
apply plugin: 'com.android.application'

apply plugin: 'realm-android'

android {
    compileSdkVersion 24
    buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "com.kolhapur.news"
    minSdkVersion 14
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

/* IMPORTANT :
 * Be careful when update dependencies, different version library may caused error /
dependencies {
    compile fileTree(dir: 'libs', include: ['.jar'])
    testCompile 'junit:junit:4.12'
    // google library
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:cardview-v7:24.1.1'
    compile 'com.android.support:recyclerview-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'
    compile 'com.google.android.gms:play-services-ads:9.2.1'
    compile 'com.google.android.gms:play-services-analytics:9.2.1'
    compile 'com.google.firebase:firebase-messaging:9.2.1'

// library for api
compile('com.squareup.retrofit2:retrofit:2.0.0-beta4') {
    exclude module: 'okhttp'
}**strong text**
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.picasso:picasso:2.5.2'

// ripple effect library
compile 'com.balysv:material-ripple:1.0.2'

}

apply plugin: 'com.google.gms.google-services'

Body:
Remove these lines

apply plugin: 'com.google.gms.google-services'

And

apply plugin: 'com.neenbedankt.android-apt'

This works with me.


问:
Create flag indicating if year variable is in the range of start:end variables in data.table
I have a data.table with 3 date variables: year, start, end.

```<code>test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))
</code>```

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

```<code>test[,x:=(year %in% start:end)]
</code>```

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

答:
Another approach

```<code>#first, create a x-column with all FALSE
DT[, x := FALSE ]
#update the x-column subset where year is between start and end to TRUE
DT[ year %between% list(start,end), x := TRUE]
</code>```

Should run fast... Benchmarks will follow soon

update: benchmarks on a data.table of 1M rows

```<code>n = 1000000
set.seed(123)
dt <- data.table(year =sample( 2001:2003, n, replace = TRUE),
                 start=sample( c(2003,2002,2000), n, replace = TRUE),
                 end  =sample( c(2003,2004,2002), n, replace = TRUE) )

microbenchmark::microbenchmark(
  wimpel = {
    DT <- copy(dt)
    DT[, x := FALSE ]
    DT[ year %between% list(start,end), x := TRUE]
    },
  akrun_nrow = {
    DT <- copy(dt)
    DT[, x := between(year, start, end), 1:nrow(DT)]
    },
  akrun_map = {
    DT <- copy(dt)
    DT[, x := unlist(do.call(Map, c(f = between, unname(.SD)))), .SDcols = year:end]
    },
  akrun_pmap = {
    DT <- copy(dt)
    DT[, x := purrr::pmap_lgl(.SD[, .(x = year, left = start, right = end)], between)]
    },
  markus = {
    DT <- copy(dt)
    DT[, col := mapply(between, year, start, end)]
  },
  times = 3
  )
</code>```

results

```<code>Unit: milliseconds
       expr        min         lq       mean     median         uq        max neval
     wimpel   29.98388   30.41861   48.98399   30.85333   58.48404   86.11475     3
 akrun_nrow 2741.35268 2755.01860 2944.58975 2768.68453 3046.20829 3323.73206     3
  akrun_map 3673.21253 3683.22849 3711.51209 3693.24446 3730.66188 3768.07929     3
 akrun_pmap 3281.13335 3291.04689 3406.46131 3300.96043 3469.12528 3637.29013     3
     markus 3408.07869 3569.33044 3670.68141 3730.58219 3801.98277 3873.38334     3
</code>```

There seems to be a clear winner.. but perhaps I'm missing something here?

Body:
I have a data.table with 3 date variables: year, start, end.

test <- data.table(year=2001:2003,start=c(2003,2002,2000),end=c(2003,2004,2002),x_desired=c(F,T,F))

O want to create a new variable x, indicating, for each row, if year is in the range defined by start and end. The correct desired result is in the variable x_desired.

I imagined this could be done with:

test[,x:=(year %in% start:end)]

but the result is clearly not correct. I wanted the ranges to be defined row-by-row, but don't know how to express that.

Body:
Another approach

#first, create a x-column with all FALSE
DT[, x := FALSE ]
#update the x-column subset where year is between start and end to TRUE
DT[ year %between% list(start,end), x := TRUE]

Should run fast... Benchmarks will follow soon

update: benchmarks on a data.table of 1M rows

n = 1000000
set.seed(123)
dt <- data.table(year =sample( 2001:2003, n, replace = TRUE),
                 start=sample( c(2003,2002,2000), n, replace = TRUE),
                 end  =sample( c(2003,2004,2002), n, replace = TRUE) )

microbenchmark::microbenchmark(
  wimpel = {
    DT <- copy(dt)
    DT[, x := FALSE ]
    DT[ year %between% list(start,end), x := TRUE]
    },
  akrun_nrow = {
    DT <- copy(dt)
    DT[, x := between(year, start, end), 1:nrow(DT)]
    },
  akrun_map = {
    DT <- copy(dt)
    DT[, x := unlist(do.call(Map, c(f = between, unname(.SD)))), .SDcols = year:end]
    },
  akrun_pmap = {
    DT <- copy(dt)
    DT[, x := purrr::pmap_lgl(.SD[, .(x = year, left = start, right = end)], between)]
    },
  markus = {
    DT <- copy(dt)
    DT[, col := mapply(between, year, start, end)]
  },
  times = 3
  )

results

Unit: milliseconds
       expr        min         lq       mean     median         uq        max neval
     wimpel   29.98388   30.41861   48.98399   30.85333   58.48404   86.11475     3
 akrun_nrow 2741.35268 2755.01860 2944.58975 2768.68453 3046.20829 3323.73206     3
  akrun_map 3673.21253 3683.22849 3711.51209 3693.24446 3730.66188 3768.07929     3
 akrun_pmap 3281.13335 3291.04689 3406.46131 3300.96043 3469.12528 3637.29013     3
     markus 3408.07869 3569.33044 3670.68141 3730.58219 3801.98277 3873.38334     3

There seems to be a clear winner.. but perhaps I'm missing something here?


问:
How to duplicate elements in a js array without creating "dependent elements"?
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4
```

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

答:
The problem is that you're passing the reference to the original object in Array(times).fill(current) .

In this case the two copies of the first {a:2} are the same copy of the original (They reference to the same space in memory) so if you change one, the two of them will change as they reference the same object in memory.

You have to make a deepcloning function or maybe spread the object inside a new one. You can change your original function to work with objects and primitives like this:

```<code>function duplicateElements(elementsArray, times) {
  //Make a new placeholder array
  var newArray = [];
  //Loop the array of elements you want to duplicate
  for (let index = 0; index < elementsArray.length; index++) {
    //Current element of the array of element
    var currentElement = elementsArray[index];
    //Current type of the element to check if it is an object or not
    var currentType = typeof currentElement
    //Loop over the times you want to copy the element
    for (let index = 0; index < times; index++) {
      //If the new element is not an object
      if (currentType !== "object" && currentType){
        //append the element
        newArray.push(currentElement)
        //if it is an Object
      } else if (currentType === "object" && currentType){
        //append an spreaded new Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
        newArray.push({...currentElement})
      }
    }
  }
  return newArray;
}
</code>```

This is not the optimal way to do this, but I think that maybe you're new to javascript and is better to learn the old way of looping before using more Array functionalities (as the answer from Jonas Wilms, that is also a good answer).

I would recommend javascript.info and eloquent javascript to learn more about the language

Body:
I am trying to modify a single element from an array whose elements were previously duplicated n times. To perform the array duplication I just relied on a custom function duplicateElements(array, times)from this post (see @Bamieh answer). As shown in the exemple below, the problem is I can't modify a single element from the array without modifying other elements:

function duplicateElements(array, times) {
  return array.reduce((res, current) => {
    return res.concat(Array(times).fill(current));
  }, []);
}

var myvar = duplicateElements([{ a: 1 }, { a: 2 }], 2);
myvar[0].a = 3;

console.log(myvar);
// (4) [{…}, {…}, {…}, {…}]
// 0: {a: 3}
// 1: {a: 3}
// 2: {a: 2}
// 3: {a: 2}
// length: 4

As you can see myvar[1].a was also modified although this wasn't intended. How can I avoid this issue?

Body:
The problem is that you're passing the reference to the original object in Array(times).fill(current) .

In this case the two copies of the first {a:2} are the same copy of the original (They reference to the same space in memory) so if you change one, the two of them will change as they reference the same object in memory.

You have to make a deepcloning function or maybe spread the object inside a new one. You can change your original function to work with objects and primitives like this:

function duplicateElements(elementsArray, times) {
  //Make a new placeholder array
  var newArray = [];
  //Loop the array of elements you want to duplicate
  for (let index = 0; index < elementsArray.length; index++) {
    //Current element of the array of element
    var currentElement = elementsArray[index];
    //Current type of the element to check if it is an object or not
    var currentType = typeof currentElement
    //Loop over the times you want to copy the element
    for (let index = 0; index < times; index++) {
      //If the new element is not an object
      if (currentType !== "object" && currentType){
        //append the element
        newArray.push(currentElement)
        //if it is an Object
      } else if (currentType === "object" && currentType){
        //append an spreaded new Object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
        newArray.push({...currentElement})
      }
    }
  }
  return newArray;
}

This is not the optimal way to do this, but I think that maybe you're new to javascript and is better to learn the old way of looping before using more Array functionalities (as the answer from Jonas Wilms, that is also a good answer).

I would recommend javascript.info and eloquent javascript to learn more about the language


问:
Why is was my code not performing with negative values inputted?
Sorry im just learning java and im new to coding!
The task of my code is to evaluate input in terms of odd and even numbers.
Without the math.abs line the code would not recognize the odd/even values of negative numbers correctly.

i made a fix using the math.abs command to convert the negative value and get the desired result. But, i just wanted to know why this step is necessary and how java  scanner interprets the negative value/symbol and provides the wrong answer without my fix.

```<code>import java.util.Scanner;

public class EvenOrOdd {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type a number: ");
        int x = Integer.parseInt(reader.nextLine());
        int f = Math.abs(x);

        if ( f % 2 == 1){
            System.out.println("The number is odd.");
        }
        else {
            System.out.println("The number is even.");
        }
    }
}
</code>```

答:
The remainder of a negative number divided by a positive number will be negative.

```<code>-1 % 2
</code>```

is

```<code>-1
</code>```

but since that is not 1, you will declare it to be even.

Body:
Sorry im just learning java and im new to coding!
The task of my code is to evaluate input in terms of odd and even numbers.
Without the math.abs line the code would not recognize the odd/even values of negative numbers correctly.

i made a fix using the math.abs command to convert the negative value and get the desired result. But, i just wanted to know why this step is necessary and how java  scanner interprets the negative value/symbol and provides the wrong answer without my fix.

import java.util.Scanner;

public class EvenOrOdd {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type a number: ");
        int x = Integer.parseInt(reader.nextLine());
        int f = Math.abs(x);

        if ( f % 2 == 1){
            System.out.println("The number is odd.");
        }
        else {
            System.out.println("The number is even.");
        }
    }
}

Body:
The remainder of a negative number divided by a positive number will be negative.

-1 % 2

is

-1

but since that is not 1, you will declare it to be even.


问:
Heroku - bash: node: command not found. Process error code 127
I am struggling with the problem that I am not able to deploy my node application to the Heroku. Previously I have done it several times and everything was working like a charm. Now I encounter bash: node: command not found. I have no idea what to do to get rid of this problem.

My Procfile:

```<code>web: node ./src/index.js
</code>```

My package.json:

```<code>{
  "name": "scheduler_be",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.js",
  "scripts": {
    "test": "jest --forceExit",
    "start": "nodemon ./src/index.js --development"

  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jablonskipj/scheduler-be.git"
  },
  "author": "Patryk Jablonski",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jablonskipj/scheduler-be/issues"
  },
  "homepage": "https://github.com/jablonskipj/scheduler-be#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.16.4",
    "jest": "^24.1.0",
    "knex": "^0.16.5",
    "node": "^12.2.0",
    "node-cron": "^2.0.3",
    "nodemon": "^1.18.9",
    "npm": "^6.9.0",
    "pg": "^7.8.0",
    "pg-hstore": "^2.3.2",
    "smsapi": "^1.5.7"
  },
  "engines": {
    "node": "12.2.0"
  }
}
</code>```

and my index.js:

```<code>const express = require('express')
const reminderRoutes = require('./routes/Routes')
const bodyParser = require('body-parser')

const PORT = process.env.PORT || 8006

console.log(PORT)

const app = express()

app.use(bodyParser.json())
app.use('/reminder', reminderRoutes)

app.listen(PORT, () => {
  console.log(`app listening on port ${PORT}`)
})
</code>```

I have tried to log out anything valuable by using heroku logs -t but this does not give me anything more than Process error code 127.

Can anyone help me with this problem?

I have tried things suggested in the heroku node.js bash: node: command not found but nothing helped. That question was asked 7 years ago and never answered, so I am pretty sure that my problem is different here.

Is there anyone from the Heroku team that could help me with the problem? Recently I have tried to force the use of the npm in version 6.5.0 and this has no effect. I have read the whole https://devcenter.heroku.com/articles/troubleshooting-node-deploys and applied all of the suggestions. How can I force Heroku to give me more info about what is exactly the problem?

EDIT:

I have also tried without the Procfile and app still does not work. Now I receive bash: npm: command not found so I am getting pretty frustrated, because of that I have another Nodejs app deployed on the Heroku and it is deploying without a problem.

EDIT:

I have checked for multiple times and the buildset is heroku/nodejs. Is there anything else that I can do to deploy this app to the heroku somehow?

Additionally here is a screen of the logs that I can see in the Heroku console

The log file - text version:

```<code>2019-05-21T06:59:52.401049+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T06:59:53.969667+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T06:59:53.952550+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T06:59:53.901105+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:01:13.046896+00:00 app[api]: Starting process with command `node src/schedule.js` by user scheduler@addons.heroku.com
2019-05-21T08:01:18.939306+00:00 heroku[scheduler.8582]: Starting process with command `node src/schedule.js`
2019-05-21T08:01:19.672108+00:00 heroku[scheduler.8582]: State changed from starting to up
2019-05-21T08:01:20.475107+00:00 heroku[scheduler.8582]: State changed from up to complete
2019-05-21T08:01:20.454340+00:00 heroku[scheduler.8582]: Process exited with status 127
2019-05-21T08:01:20.379550+00:00 app[scheduler.8582]: bash: node: command not found
2019-05-21T08:21:17.000000+00:00 app[api]: Build started by user manilandiasalon@gmail.com
2019-05-21T08:22:22.166110+00:00 heroku[web.1]: State changed from crashed to starting
2019-05-21T08:22:27.607552+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T08:22:29.106294+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T08:22:29.182031+00:00 heroku[web.1]: State changed from crashed to starting
2019-05-21T08:22:29.086883+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T08:22:28.981729+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:22:20.927103+00:00 app[api]: Deploy d783e9a4 by user manilandiasalon@gmail.com
2019-05-21T08:22:20.927103+00:00 app[api]: Release v30 created by user manilandiasalon@gmail.com
2019-05-21T08:22:36.960377+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T08:22:39.080765+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T08:22:39.061234+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T08:22:38.981195+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:22:27.000000+00:00 app[api]: Build succeeded
</code>```

After raising a ticket in the Heroku support page I received info that my application acts like a containerized app. In this case, I am not able to do anything about that and I have to wait till support team fix my issue

答:
I am not familiar with heroku, but I can say that whenever you have a "bash: BLANK not found" error it usually means you are using the command from somewhere that does not know about the command. </p>

<p>So, in this case, node is not installed in a location that the current working directory knows about. Maybe you are telling heroku an incorrect location to look for node or something, or node is just not properly installed. Check where node is installed and if you need to tell heroku where it is installed then make sure the search paths are correct? </p>

Body:
I am struggling with the problem that I am not able to deploy my node application to the Heroku. Previously I have done it several times and everything was working like a charm. Now I encounter bash: node: command not found. I have no idea what to do to get rid of this problem.

My Procfile:

web: node ./src/index.js

My package.json:

{
  "name": "scheduler_be",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.js",
  "scripts": {
    "test": "jest --forceExit",
    "start": "nodemon ./src/index.js --development"

  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jablonskipj/scheduler-be.git"
  },
  "author": "Patryk Jablonski",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jablonskipj/scheduler-be/issues"
  },
  "homepage": "https://github.com/jablonskipj/scheduler-be#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.16.4",
    "jest": "^24.1.0",
    "knex": "^0.16.5",
    "node": "^12.2.0",
    "node-cron": "^2.0.3",
    "nodemon": "^1.18.9",
    "npm": "^6.9.0",
    "pg": "^7.8.0",
    "pg-hstore": "^2.3.2",
    "smsapi": "^1.5.7"
  },
  "engines": {
    "node": "12.2.0"
  }
}

and my index.js:

const express = require('express')
const reminderRoutes = require('./routes/Routes')
const bodyParser = require('body-parser')

const PORT = process.env.PORT || 8006

console.log(PORT)

const app = express()

app.use(bodyParser.json())
app.use('/reminder', reminderRoutes)

app.listen(PORT, () => {
  console.log(`app listening on port ${PORT}`)
})

I have tried to log out anything valuable by using heroku logs -t but this does not give me anything more than Process error code 127.

Can anyone help me with this problem?

I have tried things suggested in the heroku node.js bash: node: command not found but nothing helped. That question was asked 7 years ago and never answered, so I am pretty sure that my problem is different here.

Is there anyone from the Heroku team that could help me with the problem? Recently I have tried to force the use of the npm in version 6.5.0 and this has no effect. I have read the whole https://devcenter.heroku.com/articles/troubleshooting-node-deploys and applied all of the suggestions. How can I force Heroku to give me more info about what is exactly the problem?

EDIT:

I have also tried without the Procfile and app still does not work. Now I receive bash: npm: command not found so I am getting pretty frustrated, because of that I have another Nodejs app deployed on the Heroku and it is deploying without a problem.

EDIT:

I have checked for multiple times and the buildset is heroku/nodejs. Is there anything else that I can do to deploy this app to the heroku somehow?

Additionally here is a screen of the logs that I can see in the Heroku console

The log file - text version:

2019-05-21T06:59:52.401049+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T06:59:53.969667+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T06:59:53.952550+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T06:59:53.901105+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:01:13.046896+00:00 app[api]: Starting process with command `node src/schedule.js` by user scheduler@addons.heroku.com
2019-05-21T08:01:18.939306+00:00 heroku[scheduler.8582]: Starting process with command `node src/schedule.js`
2019-05-21T08:01:19.672108+00:00 heroku[scheduler.8582]: State changed from starting to up
2019-05-21T08:01:20.475107+00:00 heroku[scheduler.8582]: State changed from up to complete
2019-05-21T08:01:20.454340+00:00 heroku[scheduler.8582]: Process exited with status 127
2019-05-21T08:01:20.379550+00:00 app[scheduler.8582]: bash: node: command not found
2019-05-21T08:21:17.000000+00:00 app[api]: Build started by user manilandiasalon@gmail.com
2019-05-21T08:22:22.166110+00:00 heroku[web.1]: State changed from crashed to starting
2019-05-21T08:22:27.607552+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T08:22:29.106294+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T08:22:29.182031+00:00 heroku[web.1]: State changed from crashed to starting
2019-05-21T08:22:29.086883+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T08:22:28.981729+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:22:20.927103+00:00 app[api]: Deploy d783e9a4 by user manilandiasalon@gmail.com
2019-05-21T08:22:20.927103+00:00 app[api]: Release v30 created by user manilandiasalon@gmail.com
2019-05-21T08:22:36.960377+00:00 heroku[web.1]: Starting process with command `node index.js`
2019-05-21T08:22:39.080765+00:00 heroku[web.1]: State changed from starting to crashed
2019-05-21T08:22:39.061234+00:00 heroku[web.1]: Process exited with status 127
2019-05-21T08:22:38.981195+00:00 app[web.1]: bash: node: command not found
2019-05-21T08:22:27.000000+00:00 app[api]: Build succeeded

After raising a ticket in the Heroku support page I received info that my application acts like a containerized app. In this case, I am not able to do anything about that and I have to wait till support team fix my issue

Body:
I am not familiar with heroku, but I can say that whenever you have a "bash: BLANK not found" error it usually means you are using the command from somewhere that does not know about the command.

So, in this case, node is not installed in a location that the current working directory knows about. Maybe you are telling heroku an incorrect location to look for node or something, or node is just not properly installed. Check where node is installed and if you need to tell heroku where it is installed then make sure the search paths are correct?


问:
Showing an already existing "Fortune" when going back to the page
"Once a fortune has been generated, if they return to the site they should be shown their existing fortune for the next year from the date it was generated.

If the user wants to generate a new fortune, give them a link to do so."

My problem is I can't figure out how to make it stay on the generated fortune page when going back to the website, I tried searching it up but I did not find anything. I think i already made a reset link but I am unsure.
What kind of code do I need to make it stay on the fortune page?

I searched it up online, I've tried somehow making it check that cookies were applied but we were not taught that.

Main PHP Page (index.php)

```<code><html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>
    <form method="post" action="fortune.php">
        <label for="fname">First Name</label>
        <input type="text" id="fname" name="fname" />
        <br />
        <label for="colour">Favourite Colour</label>
        <input type="text" id="colour" name="colour" />
        <br />
        <label for="birthmonth">Birth Month</label>
        <select id="birthmonth" name="birthmonth">
            <option value="1">January</option>
            <option value="2">February</option>
            <option value="3">March</option>
            <option value="4">April</option>
            <option value="5">May</option>
            <option value="6">June</option>
            <option value="7">July</option>
            <option value="8">August</option>
            <option value="9">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>
        <br />
        <input type="submit" id="submit" name="submit" value="Tell my fortune" />
    </form>
</body>
</html>
</code>```

Page after you complete the form

```<code><?php
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>
</head>

<body>
    <img src="fortune-teller.jpg" alt="The Fortune Teller" style="float:right;" />
    <h1>Fortune Teller</h1>
    <p>The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.</p>
    <p>What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...</p>

    <h2>Fortune for <?php echo $_POST['fname']; ?></h2>
    <p>
    <?php
        if($_POST['fname']=="Tony"){
                echo "You like to control everyone within your influence, to shape things to your own liking. ";
        }
        else if($_POST['fname']=="Ebonie"){
            echo "You're' fine when in harmony but changeable when in discord, because many of your best qualities are then reversed. ";
        }
        else if($_POST['fname']=="Eric"){
            echo "You have a vivid imagination who can bring inspired messages to the world. ";
        }
        else if($_POST['fname']=="Kristina"){
            echo "EXTREMES in fortune, health and spirituality. You are very versatile, idealistic and intuitive. ";
        }
        else if($_POST['fname']=="Jamie"){
            echo "You're' honest, benevolent, brilliant and often inventive, full of high inspirations. ";
        }else{
            echo "You're a decent person at best. ";
        }

        //Birthmonth - something to do with the season they were born in
        if($_POST['birthmonth']<4){
            //January, February, March - Q1 (Winter)
            echo "You are independent, analytic, and a born leader. ";
        }
        else if($_POST['birthmonth']<6){
            //April, May, June - Q2 (Spring)
            echo "You may be perceived as being stubborn, bossy, and impulsive. ";
        }
        else if($_POST['birthmonth']<9){
            //July, August, September - Q3 (Summer)
            echo "You are a sincere, candid, and sympathetic individual.. ";
        }
        else if($_POST['birthmonth']<12){
            //October, November, December - Q4 (Fall)
            echo "You are a practical philosopher who values a stable lifestyle. ";
        }

        //favourite colour - something about your job
        if($_POST['colour']=="red"){
            echo "You will find success in your career this month.";
        }
        else if($_POST['colour']=="blue"){
            echo "You need to be careful as you're on the verge of your employment being termenated.";
        }
        else if($_POST['colour']=="green"){
            echo "Show up to work early, keep your nose clean and your head down and you'll get a raise next month.";
        }
        else if($_POST['colour']=="yellow"){
            echo "A management position is in your future.";
        }
        else if($_POST['colour']=="black"){
            echo "Your difficulty working with others will cause tensions in the workplace in the near future.";
        }
        else{
            echo "Keep doing your job as well as you do now, good things will happen.";
        }
    ?>
    </p>
    <?php
      $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
      echo "<a href='$url'>Reset</a>";
    ?>
</body>
</html>
</code>```

The expected outcome is when you complete the form it will save the last time you got to the page, displaying the date of your last fortune which I got it to do, but it also needs to have you remain on that page the next time you enter the page and with a reset button which takes you back to the form.

答:
I think the problem you are having is that you have the concept of when to check the cookie incorrectly. Seeing as this sounds like a homework problem I will try and give you an answer that guides you in the right direction.

What you would need to do is upon submitting the form this would do a post to the page which causes the cookie to be set. However the PHP logic that checks the cookie should be on any page a visitor can land on (generally this is the main index page). It should check the cookie and display the HTML content appropriate for that user's detected cookie. If no cookie is detected then it can display your base index page. (This can be done by displaying dynamic html elements or simply by redirecting the user to another page)

Body:
"Once a fortune has been generated, if they return to the site they should be shown their existing fortune for the next year from the date it was generated.

If the user wants to generate a new fortune, give them a link to do so."

My problem is I can't figure out how to make it stay on the generated fortune page when going back to the website, I tried searching it up but I did not find anything. I think i already made a reset link but I am unsure.
What kind of code do I need to make it stay on the fortune page?

I searched it up online, I've tried somehow making it check that cookies were applied but we were not taught that.

Main PHP Page (index.php)

    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>

Fortune Teller

The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.

What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...

    <form method="post" action="fortune.php">
        First Name
        <input type="text" id="fname" name="fname" />

        Favourite Colour
        <input type="text" id="colour" name="colour" />

        Birth Month
        <select id="birthmonth" name="birthmonth">
            <option value="1">January</option>
            <option value="2">February</option>
            <option value="3">March</option>
            <option value="4">April</option>
            <option value="5">May</option>
            <option value="6">June</option>
            <option value="7">July</option>
            <option value="8">August</option>
            <option value="9">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>

        <input type="submit" id="submit" name="submit" value="Tell my fortune" />
    </form>

Page after you complete the form

<?php
if(isset($_COOKIE['lastVisit']))
{
$visit = $_COOKIE['lastVisit'];
echo "Your last fortune was told at ". $visit;
}
//set to expire in a year
$year = +31556926 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $year);
?>

<!doctype html>

    <meta charset="utf-8">
    <title>Week 4 Tutorial - Fortune Teller</title>

Fortune Teller

The fortune teller has looked deep in your soul, and has a sense of who you are and what will come in your life.

What is your fate? How long will you live? Will you be successful or struggle in life? Find out below...

Fortune for <?php echo $_POST['fname']; ?>

    <?php
        if($_POST['fname']=="Tony"){
                echo "You like to control everyone within your influence, to shape things to your own liking. ";
        }
        else if($_POST['fname']=="Ebonie"){
            echo "You're' fine when in harmony but changeable when in discord, because many of your best qualities are then reversed. ";
        }
        else if($_POST['fname']=="Eric"){
            echo "You have a vivid imagination who can bring inspired messages to the world. ";
        }
        else if($_POST['fname']=="Kristina"){
            echo "EXTREMES in fortune, health and spirituality. You are very versatile, idealistic and intuitive. ";
        }
        else if($_POST['fname']=="Jamie"){
            echo "You're' honest, benevolent, brilliant and often inventive, full of high inspirations. ";
        }else{
            echo "You're a decent person at best. ";
        }

        //Birthmonth - something to do with the season they were born in
        if($_POST['birthmonth']<4){
            //January, February, March - Q1 (Winter)
            echo "You are independent, analytic, and a born leader. ";
        }
        else if($_POST['birthmonth']<6){
            //April, May, June - Q2 (Spring)
            echo "You may be perceived as being stubborn, bossy, and impulsive. ";
        }
        else if($_POST['birthmonth']<9){
            //July, August, September - Q3 (Summer)
            echo "You are a sincere, candid, and sympathetic individual.. ";
        }
        else if($_POST['birthmonth']<12){
            //October, November, December - Q4 (Fall)
            echo "You are a practical philosopher who values a stable lifestyle. ";
        }

        //favourite colour - something about your job
        if($_POST['colour']=="red"){
            echo "You will find success in your career this month.";
        }
        else if($_POST['colour']=="blue"){
            echo "You need to be careful as you're on the verge of your employment being termenated.";
        }
        else if($_POST['colour']=="green"){
            echo "Show up to work early, keep your nose clean and your head down and you'll get a raise next month.";
        }
        else if($_POST['colour']=="yellow"){
            echo "A management position is in your future.";
        }
        else if($_POST['colour']=="black"){
            echo "Your difficulty working with others will cause tensions in the workplace in the near future.";
        }
        else{
            echo "Keep doing your job as well as you do now, good things will happen.";
        }
    ?>

    <?php
      $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
      echo "Reset";
    ?>

The expected outcome is when you complete the form it will save the last time you got to the page, displaying the date of your last fortune which I got it to do, but it also needs to have you remain on that page the next time you enter the page and with a reset button which takes you back to the form.


Title: How can I melt the dataframe getting all dates between a range?

Body:
I have a dataset like this:

    import pandas as pd
    pd.DataFrame({'col1': [1, 2], 'start date': ['1/3/2019', '1/10/2019'],
                                  'end date':['1/5/2019','1/12/2019']} )

I want to get a row for each of the values between Start Date and End Date.

    pd.DataFrame({'col1': [1,1,1,2,2,2],
                  'date': ['1/3/2019','1/4/2019','1/5/2019',
                           '1/10/2019', '1/11/2019', '1/12/2019'],

                  'start date': ['1/3/2019', '1/3/2019', '1/3/2019',
                           '1/10/2019', '1/10/2019', '1/10/2019'],

                  'end date':['1/5/2019','1/5/2019','1/5/2019',
                           '1/12/2019','1/12/2019','1/12/2019']} )

Edit: Range overlap is allowed.

I am trying to use melt but I can't get what I want.

Body:
Here is something to consider which uses pd.date_range and a groupby.apply:

df = pd.DataFrame({'col1': [1, 2], 'start date': ['1/3/2019', '1/10/2019'], 'end date':['1/5/2019','1/12/2019']} )
df.set_index(['col1', 'start date', 'end date'], inplace=True)
df_result = df.groupby(['col1', 'start date', 'end date']).apply(lambda df_: pd.date_range(*df_.index[0][1:], freq='D').to_frame(index=True, name='date'))
df_result.reset_index(inplace=True)
df_result.reindex(['col1', 'date', 'start date', 'end date'], axis=1)

# produces the following:

   col1       date start date   end date
0     1 2019-01-03   1/3/2019   1/5/2019
1     1 2019-01-04   1/3/2019   1/5/2019
2     1 2019-01-05   1/3/2019   1/5/2019
3     2 2019-01-10  1/10/2019  1/12/2019
4     2 2019-01-11  1/10/2019  1/12/2019
5     2 2019-01-12  1/10/2019  1/12/2019


问:
Team System get-latest-version on checkout
We used to use SourceSafe, and one thing I liked about it was that when you checked out a file, it automatically got you its latest version.

Now we work with Team System 2005, and it doesn't work that way - you have to "get latest version" before you start working on a file that you've checked out.

Is there a way to configure Team System (2005) to automatically get the latest version when checking out a file?

答:
There's a Visual Studio Add-in for this that someone wrote:

http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/03/24/TFS-GetLatest-version-on-check_2D00_out-Add_2D00_In.aspx

OwnerDisplayName: Leac

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Vaibhav


问:
Program not working as well - C
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

Thanks !

答: Replace == with != in string[i] == '\0'

Title: Program not working as well - C

Body:
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

Thanks !

Body: Replace == with != in string[i] == '\0'


问:
Container shrinks to the size of his child
Why is my Container shrinks to the size of his child?
By the way, the container doesn't shrink if he is in slivers</p>

```<code>Container(
                height: 100,
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                      blurRadius: 10.0,
                      offset: Offset(3.0, 10.0),
                      // spreadRadius: 2.0,
                    )
                  ],
                ),
                child: Icon(Icons.location_on,
                    color: Color(0XFF0D47A1), size: 60.0),
              ),
</code>```

答:
The way that widgets size themselves is actually quite complicated, and I don't think I can do a better job explaining than flutter's documentation: Layouts in Flutter. Different widget types size themselves differently depending on their children and their parents. So when a container is in a SliverList it might size itself differently than if it isn't.

However, the alignment property of the Container defines how the container sizes itself:

If non-null, the container will expand to fill its parent and position its child within itself according to the given value. If the incoming constraints are unbounded, then the child will be shrink-wrapped instead.

You could alternatively wrap the child in a Center or Alignment widget.

Body:
Why is my Container shrinks to the size of his child?
By the way, the container doesn't shrink if he is in slivers

Container(
                height: 100,
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black,
                      blurRadius: 10.0,
                      offset: Offset(3.0, 10.0),
                      // spreadRadius: 2.0,
                    )
                  ],
                ),
                child: Icon(Icons.location_on,
                    color: Color(0XFF0D47A1), size: 60.0),
              ),


问:
stop deployment of people outside company email address - Firebase
Currently anyone with email address can deploy a code by firebase-tools
i generally use firebase deploy

the challenge i have here is , i want to restrict people outside company email address to deploy code using the command firebase deploy .

Eg: company mail address : one@abc.com -> Allow
outside company : one@xyz  -> Denie Deployemnt

Is this possible in firebase , i have read lot of document but nothing really helps me here !

I tried to do it with rules. file in firebase , but didnt find great solution

COMPANY EMAIL ADDRESS : one@abc.com

ACTUAL : one@xyz.com -> allowed

Expected : one@xyz.com - > Dont Allow since its not company mail addresss

答:
To be able to run firebase deploy, one must be signed in with an account that is a collaborator on that project.

If you don't want certain users to be able to deploy, don't add them as collaborators to the project.

If you want them to be collaborators, but not be able to deploy to Firebase Hosting, revoke their edit permission for Firebase Hosting.


问:
Find conditions syntax in Rails 5.2.3
I am upgrading an old RoR app to Rails 5.2.3 and would like know the right syntax for below line in 5.2.3:

```<code>    default :to => User.find(:all, :conditions => ["admin=?", true]).map(&:email_addr), :from => "foo@grbx.com"
</code>```

Error I am getting is:

```<code>    Error: The application encountered the following error: Couldn't find all Users with 'id': (all, {:conditions=>["admin=?", true]}) (found 0 results, but was looking for 2). (ActiveRecord::RecordNotFound)
</code>```

答:
```<code>`
User.find(:all, :conditions => ["admin=?", true]).map(&:email_addr)
`

The above command is deprecated in rails 4,5.
You can use

`
User.where(admin: true).map(&:email_addr)
User.where(admin: true).collect(&:email_addr)
User.where(admin: true).pluck(:email_addr)
`
</code>```

Title: Find conditions syntax in Rails 5.2.3

Body:
I am upgrading an old RoR app to Rails 5.2.3 and would like know the right syntax for below line in 5.2.3:

    default :to => User.find(:all, :conditions => ["admin=?", true]).map(&:email_addr), :from => "foo@grbx.com"

Error I am getting is:

    Error: The application encountered the following error: Couldn't find all Users with 'id': (all, {:conditions=>["admin=?", true]}) (found 0 results, but was looking for 2). (ActiveRecord::RecordNotFound)


问:
Error: name "Socketkind is not defind" with Flask-socketio?
I'm using flask-socketio to build a web-telnet. It's work well until I've added an object of class for telnet to another device in my local network. Anyone know how to resolve this problem?

Here my code:

```<code>import telnetlib
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@socketio.on('check_device')
 def check(ip_add):
 device =  telnet_device(ip_add)
 device.connect()

class telnet_device():
  def __init__(self,ip_add):
        self.username  = 'user'
        self.password  = 'pass'
        self.host      = ip_add
        self.connection= False
        self.ketnoi    = ''

  def connect(self):
    try:
        self.ketnoi   = telnetlib.Telnet(self.host, timeout=15)
        self.ketnoi.write(self.username.encode()+b'\r')
        self.ketnoi.write(self.password.encode()+b'\r')
        self.ketnoi.expect([b'>',b']'],5)
        self.connection = True
        return True
   except Exception as error:
       print(error)
       return False
</code>```

And the error messages:

```<code>Traceback (most recent call last):
  File "src\gevent\greenlet.py", line 766, in gevent._greenlet.Greenlet.run
  File "C:\Python34\lib\site-packages\socketio\server.py", line 599, in _handle_event_internal
    r = server._trigger_event(data[0], namespace, sid, *data[1:])
  File "C:\Python34\lib\site-packages\socketio\server.py", line 628, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "C:\Python34\lib\site-packages\flask_socketio\__init__.py", line 277, in _handler
    *args)
  File "C:\Python34\lib\site-packages\flask_socketio\__init__.py", line 680, in _handle_event
    ret = handler(*args)
  File "D:\web_app\app.py", line 301, in kiemtra_olt
    device.connect()
  File "D:\web_app\telnettb.py", line 15, in connect
    self.ketnoi   = telnetlib.Telnet(self.host, timeout=15)
  File "C:\Python34\lib\telnetlib.py", line 221, in __init__
    self.open(host, port, timeout)
  File "C:\Python34\lib\telnetlib.py", line 237, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python34\lib\site-packages\gevent\socket.py", line 83, in create_connection
    addrs = list(getaddrinfo(host, port, 0, SOCK_STREAM))
  File "C:\Python34\lib\site-packages\gevent\_socketcommon.py", line 218, in getaddrinfo
    in addrlist
  File "C:\Python34\lib\site-packages\gevent\_socketcommon.py", line 217, in <listcomp>
    for af, socktype, proto, canonname, sa
NameError: name 'SocketKind' is not defined
2019-05-27T08:41:52Z <Thread at 0x4e3c470: <bound method Server._handle_event_internal of <socketio.server.Server object at 0x044CEA70>>(<socketio.server.Server object at 0x044CEA70>, '626fb5231dba41c5be8a226f8f8240b9', ['check_device', 'ip_add'], '/', None)> failed with NameError
</code>```

答: I believe you are using a version of Python that is too old. The SocketKind type was introduced in 3.4.3 according to this issue. Are you using a 3.4.2 or older release? An upgrade to a newer Python should address your problem.

Body:
I'm using flask-socketio to build a web-telnet. It's work well until I've added an object of class for telnet to another device in my local network. Anyone know how to resolve this problem?

Here my code:

import telnetlib
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@socketio.on('check_device')
 def check(ip_add):
 device =  telnet_device(ip_add)
 device.connect()

class telnet_device():
  def __init__(self,ip_add):
        self.username  = 'user'
        self.password  = 'pass'
        self.host      = ip_add
        self.connection= False
        self.ketnoi    = ''

  def connect(self):
    try:
        self.ketnoi   = telnetlib.Telnet(self.host, timeout=15)
        self.ketnoi.write(self.username.encode()+b'\r')
        self.ketnoi.write(self.password.encode()+b'\r')
        self.ketnoi.expect([b'>',b']'],5)
        self.connection = True
        return True
   except Exception as error:
       print(error)
       return False

And the error messages:

Traceback (most recent call last):
  File "src\gevent\greenlet.py", line 766, in gevent._greenlet.Greenlet.run
  File "C:\Python34\lib\site-packages\socketio\server.py", line 599, in _handle_event_internal
    r = server._trigger_event(data[0], namespace, sid, *data[1:])
  File "C:\Python34\lib\site-packages\socketio\server.py", line 628, in _trigger_event
    return self.handlers[namespace][event](*args)
  File "C:\Python34\lib\site-packages\flask_socketio\__init__.py", line 277, in _handler
    *args)
  File "C:\Python34\lib\site-packages\flask_socketio\__init__.py", line 680, in _handle_event
    ret = handler(*args)
  File "D:\web_app\app.py", line 301, in kiemtra_olt
    device.connect()
  File "D:\web_app\telnettb.py", line 15, in connect
    self.ketnoi   = telnetlib.Telnet(self.host, timeout=15)
  File "C:\Python34\lib\telnetlib.py", line 221, in __init__
    self.open(host, port, timeout)
  File "C:\Python34\lib\telnetlib.py", line 237, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python34\lib\site-packages\gevent\socket.py", line 83, in create_connection
    addrs = list(getaddrinfo(host, port, 0, SOCK_STREAM))
  File "C:\Python34\lib\site-packages\gevent\_socketcommon.py", line 218, in getaddrinfo
    in addrlist
  File "C:\Python34\lib\site-packages\gevent\_socketcommon.py", line 217, in <listcomp>
    for af, socktype, proto, canonname, sa
NameError: name 'SocketKind' is not defined
2019-05-27T08:41:52Z <Thread at 0x4e3c470: <bound method Server._handle_event_internal of <socketio.server.Server object at 0x044CEA70>>(<socketio.server.Server object at 0x044CEA70>, '626fb5231dba41c5be8a226f8f8240b9', ['check_device', 'ip_add'], '/', None)> failed with NameError


答:
I would use range_index to build the list of dates between start date and end date, build a partial dataframe from each row and then concat them all:

```<code>pd.concat(
    [pd.DataFrame(row.to_dict(), index = pd.date_range(
        start = pd.to_datetime(df.loc[i, 'start date']),
        end = pd.to_datetime(df.loc[i, 'end date']),
        freq = 'D')).rename_axis('date').reset_index()
     for i, row in df.iterrows()], ignore_index=True)
</code>```

Body:
I would use range_index to build the list of dates between start date and end date, build a partial dataframe from each row and then concat them all:

pd.concat(
    [pd.DataFrame(row.to_dict(), index = pd.date_range(
        start = pd.to_datetime(df.loc[i, 'start date']),
        end = pd.to_datetime(df.loc[i, 'end date']),
        freq = 'D')).rename_axis('date').reset_index()
     for i, row in df.iterrows()], ignore_index=True)


问:
Menu control in silverlight 4 similar to WPF Menu
I want a menu control for my silverlight 4.0 application.
The functionality should be similar to a WPF menu control,
Can you suggest me the solution.
Thanks.

答:
Try

http://silverlightpopupmenu.codeplex.com/

http://slmenu.codeplex.com/

http://www.vectorlight.net/silverlight/controls/menu_(popup).aspx

You could also try paid components such as

http://www.devexpress.com/products/net/controls/silverlight/menu/

http://www.telerik.com/products/silverlight/menu.aspx


问:
How to create a Jandex index for RESTeasy Multipart Provider
I'm trying to use RESTeasy Multipart with Quarkus, but when I do

mvn clean compile quarkus:dev

I get this warning:

Unable to properly register the hierarchy of the following classes for reflection as they are not in the Jandex index:
- org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput

I tried all of these solutions: How to create a Jandex index in Quarkus for classes in a external module but none of them work, I still get the same warning.

Quarkus Version: 0.15

The goal is to upload a file.

This is the part of the Code which uses

import org.jboss.resteasy.plugins.providers.multipart.InputPart;

import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

    @POST
    @Path("/fileupload")
    @Consumes("multipart/form-data")
    //@Consumes(MediaType.APPLICATION_XML)
    public Response uploadFile(MultipartFormDataInput input) {
        System.out.println("TEST TEST TEST");
        final String UPLOADED_FILE_PATH = "/tmp";

        String fileName = "";

        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("uploadedFile");

        for (InputPart inputPart : inputParts) {

            try {

                MultivaluedMap<String, String> header = inputPart.getHeaders();
                fileName = getFileName(header);

                //convert the uploaded file to inputstream
                InputStream inputStream = inputPart.getBody(InputStream.class,null);

                byte [] bytes = IOUtils.toByteArray(inputStream);

                //constructs upload file path
                fileName = UPLOADED_FILE_PATH + fileName;

                writeFile(bytes,fileName);

                System.out.println("Done");

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return Response.status(201)
                .entity("uploadFile is called, Uploaded file name : " + fileName).build();

    }

    /**
     * header sample
     * {
     *  Content-Type=[image/png],
     *  Content-Disposition=[form-data; name="file"; filename="filename.extension"]
     * }
     **/
    //get uploaded filename, is there a easy way in RESTEasy?
    private String getFileName(MultivaluedMap<String, String> header) {

        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");

        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {

                String[] name = filename.split("=");

                String finalFileName = name[1].trim().replaceAll("\"", "");
                return finalFileName;
            }
        }
        return "unknown";
    }

    //save to somewhere
    private void writeFile(byte[] content, String filename) throws IOException {

        File file = new File(filename);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fop = new FileOutputStream(file);

        fop.write(content);
        fop.flush();
        fop.close();

    }
```

<p>This is the pom.xml file:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example.comcord.asset</groupId>
  <artifactId>assetProject</artifactId>
  <version>1.0-SNAPSHOT</version>
  <properties>
    <surefire-plugin.version>2.22.0</surefire-plugin.version>
    <quarkus.version>0.15.0</quarkus.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-bom</artifactId>
        <version>${quarkus.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>27.1-jre</version>
    </dependency>

    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy-jsonb</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-hibernate-orm-panache</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-jdbc-postgresql</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
    <dependency>
      <groupId>org.apache.tika</groupId>
      <artifactId>tika-core</artifactId>
      <version>1.21</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-multipart-provider -->
    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-multipart-provider</artifactId>
      <version>4.0.0.Final</version>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>build</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <systemProperties>
            <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>native</id>
      <activation>
        <property>
          <name>native</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-maven-plugin</artifactId>
            <version>${quarkus.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>native-image</goal>
                </goals>
                <configuration>
                  <enableHttpUrlHandler>true</enableHttpUrlHandler>
                </configuration>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${surefire-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <systemProperties>
                    <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                  </systemProperties>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>
</code>```

答:
Don’t worry, it’s not an issue and you can safely ignore the message.

We have an ignore list in Quarkus and I will add this one to the list as it’s not something that is either serialized or deserialized. The message is specifically for classes that will be used by a JSON/XML... serializer.

It should be fixed in the next release planned for Wednesday. I’ll open a PR tomorrow.

Body:
I'm trying to use RESTeasy Multipart with Quarkus, but when I do

mvn clean compile quarkus:dev

I get this warning:

Unable to properly register the hierarchy of the following classes for reflection as they are not in the Jandex index:
- org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput

I tried all of these solutions: How to create a Jandex index in Quarkus for classes in a external module but none of them work, I still get the same warning.

Quarkus Version: 0.15

The goal is to upload a file.

This is the part of the Code which uses

import org.jboss.resteasy.plugins.providers.multipart.InputPart;

import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

    @POST
    @Path("/fileupload")
    @Consumes("multipart/form-data")
    //@Consumes(MediaType.APPLICATION_XML)
    public Response uploadFile(MultipartFormDataInput input) {
        System.out.println("TEST TEST TEST");
        final String UPLOADED_FILE_PATH = "/tmp";

        String fileName = "";

        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("uploadedFile");

        for (InputPart inputPart : inputParts) {

            try {

                MultivaluedMap<String, String> header = inputPart.getHeaders();
                fileName = getFileName(header);

                //convert the uploaded file to inputstream
                InputStream inputStream = inputPart.getBody(InputStream.class,null);

                byte [] bytes = IOUtils.toByteArray(inputStream);

                //constructs upload file path
                fileName = UPLOADED_FILE_PATH + fileName;

                writeFile(bytes,fileName);

                System.out.println("Done");

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return Response.status(201)
                .entity("uploadFile is called, Uploaded file name : " + fileName).build();

    }

    /**
     * header sample
     * {
     *  Content-Type=[image/png],
     *  Content-Disposition=[form-data; name="file"; filename="filename.extension"]
     * }
     **/
    //get uploaded filename, is there a easy way in RESTEasy?
    private String getFileName(MultivaluedMap<String, String> header) {

        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");

        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {

                String[] name = filename.split("=");

                String finalFileName = name[1].trim().replaceAll("\"", "");
                return finalFileName;
            }
        }
        return "unknown";
    }

    //save to somewhere
    private void writeFile(byte[] content, String filename) throws IOException {

        File file = new File(filename);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fop = new FileOutputStream(file);

        fop.write(content);
        fop.flush();
        fop.close();

    }

This is the pom.xml file:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example.comcord.asset</groupId>
  <artifactId>assetProject</artifactId>
  <version>1.0-SNAPSHOT</version>
  <properties>
    <surefire-plugin.version>2.22.0</surefire-plugin.version>
    <quarkus.version>0.15.0</quarkus.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-bom</artifactId>
        <version>${quarkus.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>27.1-jre</version>
    </dependency>

    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-junit5</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy-jsonb</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-hibernate-orm-panache</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-jdbc-postgresql</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.tika</groupId>
      <artifactId>tika-core</artifactId>
      <version>1.21</version>
    </dependency>

    <dependency>
      <groupId>org.jboss.resteasy</groupId>
      <artifactId>resteasy-multipart-provider</artifactId>
      <version>4.0.0.Final</version>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>build</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
          <systemProperties>
            <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <profiles>
    <profile>
      <id>native</id>
      <activation>
        <property>
          <name>native</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>io.quarkus</groupId>
            <artifactId>quarkus-maven-plugin</artifactId>
            <version>${quarkus.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>native-image</goal>
                </goals>
                <configuration>
                  <enableHttpUrlHandler>true</enableHttpUrlHandler>
                </configuration>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>${surefire-plugin.version}</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                  <goal>verify</goal>
                </goals>
                <configuration>
                  <systemProperties>
                    <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
                  </systemProperties>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
</project>


问:
How can I add a date stamp to a file i am copying?
I am able to copy a file using the below line of code, it works great.  I would love it if the destination file name would include the system date when copied.  I have tried many things, but am unable to achieve the goal.  Cab somebody help me out here?

File.Copy("\Computer1\mall\Files\Computer1.cfg", "c:\ComputerFiles\Computer1.cfg", True)

答:
You can use the FileInfo class to set the files CreationTime, LastAccesstime, LastWriteTime.</p>

```<code>Dim fileLocation As String = "c:\ComputerFiles\Computer1.cfg"

Dim fi As New FileInfo(fileLocation)
fi.CreationTime = DateTime.Now
fi.LastAccessTime = DateTime.Now
fi.LastWriteTime = DateTime.Now
</code>```

Body:
You can use the FileInfo class to set the files CreationTime, LastAccesstime, LastWriteTime.

Dim fileLocation As String = "c:\ComputerFiles\Computer1.cfg"

Dim fi As New FileInfo(fileLocation)
fi.CreationTime = DateTime.Now
fi.LastAccessTime = DateTime.Now
fi.LastWriteTime = DateTime.Now


问:
Why does Java report a mismatch when trying to print big random numbers?
Java reports a Type mismatch exception when trying to print big numbers and stored an array.

I'm currently learning some Java. One of the excercises of the course I'm doing, asks me to generate some random numbers and storing them inside an array. Everything works fine as long as I generate integers, I can print them without trouble using out.print.

But, when I generate big numbers and try to print them, Java informs a type mismatch in the line where I have the for each loop.

```<code>package clases;

public class Arrays_3 {
    public static void main (String [] args) {
        long [] array_random=new long[150];
        for (int i=0;i<array_random.length;i++) {
            array_random[i]=(long)Math.round(Math.random()*100000) ;
        }

        for (long elemento:array_random) {
            System.out.println(array_random[elemento]);
        }
    }
}
</code>```

This is the error I get on Eclipse console after running the code above:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from long to int

    at clases.Arrays_3.main(Arrays_3.java:17)
```

Line 17 is where the System.out.print method is.

答:
Elemento is a long, while arrays are indexed by integers.

Besides, with for(long elemento: array) you are creating an iterator that return one value of the array on each iteration of the loop. Thus, you can directly print it.

```<code>for (long elemento : array) {
    System.out.println(elemento);
}
</code>```

If you want to lookup for an element of the array, you should iterate over an index variable

```<code>for (int idx=0;idx<array.length;idx++) {
    System.out.println(array[idx]);
}
</code>```

Body:
Java reports a Type mismatch exception when trying to print big numbers and stored an array.

I'm currently learning some Java. One of the excercises of the course I'm doing, asks me to generate some random numbers and storing them inside an array. Everything works fine as long as I generate integers, I can print them without trouble using out.print.

But, when I generate big numbers and try to print them, Java informs a type mismatch in the line where I have the for each loop.

package clases;

public class Arrays_3 {
    public static void main (String [] args) {
        long [] array_random=new long[150];
        for (int i=0;i<array_random.length;i++) {
            array_random[i]=(long)Math.round(Math.random()*100000) ;
        }

        for (long elemento:array_random) {
            System.out.println(array_random[elemento]);
        }
    }
}

This is the error I get on Eclipse console after running the code above:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Type mismatch: cannot convert from long to int

    at clases.Arrays_3.main(Arrays_3.java:17)

Line 17 is where the System.out.print method is.

Body:
Elemento is a long, while arrays are indexed by integers.

Besides, with for(long elemento: array) you are creating an iterator that return one value of the array on each iteration of the loop. Thus, you can directly print it.

for (long elemento : array) {
    System.out.println(elemento);
}

If you want to lookup for an element of the array, you should iterate over an index variable

for (int idx=0;idx<array.length;idx++) {
    System.out.println(array[idx]);
}


问:
How to write if statement in arrow function expression?
i am not getting expected result in below code just wanted to know if its correct way to add condition in arrow function syntax using expression.

const drugPriceErrors = [99, 85];

Case#1
const messages = [{
  settlementCode: "99",
  settlementDesc: "test:test"
}]

Case#2
const messages = [{
  settlementCode: "77",
  settlementDesc: "test"
}
];

Case#3

const messages = [{
  settlementCode: "66",
  settlementDesc: "test:test"
}]

function validateEntries(messages) {
  if (!messages) {
    return []
  };

  let filteredMsg = messages.filter((item) => {
    if (!drugPriceErrors.includes(item.settlementCode)) {
      item.settlementDesc.includes(":")
    } else {
      return;
    }
  });

  return filteredMsg;
};

console.log(validateEntries(messages));```
</div>
</div>
</p>

<p>expected output </p>

```Case#1 output should be
    [{
      settlementCode: "99",
      settlementDesc: "test:test"
    }]

Case#2 output should be

[]

Case#3 output

[{
      settlementCode: "66",
      settlementDesc: "test:test"
    }]
```

答:
As per my understanding, you want to filter in those objects that meet following criteria

SettlementCode should not exist in drugPriceErrors array OR

SettlementDesc should contain :

You can correct your code as following

Firstly, as drugPriceErrors is an array of numbers, convert settlementCode to number using +settlementCode

If condition is evaluated to true i.e. settlementCode exist in drugPriceErrors, return true

Else, return whether settlementDesc contains :

const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];

function validateEntries(messages) {
  if (!messages) {
    return []
  };

  let filteredMsg = messages.filter((item) => {
    if (drugPriceErrors.includes(+item.settlementCode)) return true;
    else return item.settlementDesc.includes(":");
  });

  return filteredMsg;
};

console.log(validateEntries(messages));```
</div>
</div>
</p>

<p>Additionally, you can also simplify your code as following</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];

 const result = messages.filter(v => drugPriceErrors.includes(+v.settlementCode) || v.settlementDesc.includes(":"));
 console.log(result);</code>```

Body:
i am not getting expected result in below code just wanted to know if its correct way to add condition in arrow function syntax using expression.

const drugPriceErrors = [99, 85];

Case#1
const messages = [{
  settlementCode: "99",
  settlementDesc: "test:test"
}]

Case#2
const messages = [{
  settlementCode: "77",
  settlementDesc: "test"
}
];

Case#3

const messages = [{
  settlementCode: "66",
  settlementDesc: "test:test"
}]

function validateEntries(messages) {
  if (!messages) {
    return []
  };

  let filteredMsg = messages.filter((item) => {
    if (!drugPriceErrors.includes(item.settlementCode)) {
      item.settlementDesc.includes(":")
    } else {
      return;
    }
  });

  return filteredMsg;
};

console.log(validateEntries(messages));

expected output

Case#1 output should be
    [{
      settlementCode: "99",
      settlementDesc: "test:test"
    }]

Case#2 output should be

[]

Case#3 output

[{
      settlementCode: "66",
      settlementDesc: "test:test"
    }]

Body:
As per my understanding, you want to filter in those objects that meet following criteria

SettlementCode should not exist in drugPriceErrors array OR

SettlementDesc should contain :

You can correct your code as following

Firstly, as drugPriceErrors is an array of numbers, convert settlementCode to number using +settlementCode

If condition is evaluated to true i.e. settlementCode exist in drugPriceErrors, return true

Else, return whether settlementDesc contains :

const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];

function validateEntries(messages) {
  if (!messages) {
    return []
  };

  let filteredMsg = messages.filter((item) => {
    if (drugPriceErrors.includes(+item.settlementCode)) return true;
    else return item.settlementDesc.includes(":");
  });

  return filteredMsg;
};

console.log(validateEntries(messages));

Additionally, you can also simplify your code as following

const drugPriceErrors = [99,85];
const messages = [ {settlementCode:"99", settlementDesc: "test:test" }, {settlementCode:"66", settlementDesc: "test:test" },{settlementCode: "77",settlementDesc: "test"}];

 const result = messages.filter(v => drugPriceErrors.includes(+v.settlementCode) || v.settlementDesc.includes(":"));
 console.log(result);


问:
How to design the objects' relationship with ORM
I have been confused about ORM since I see the following sample code:

```<code>public class Article
{
    public List<Comment> Comments;

    public void AddComment(Comment comment)
    {
        Comments.Add(comment);
    }

    // I'm surprised by this kind of operation
    // how much performance hit it should be
    public void Save()
    {
        //update the article and all its comments
    }
}
</code>```

According to what I think, the responsiblity of saving comment should be assigned to the comment itself:

```<code>public class Comment
{
    public Article BelongArticle;

    //I think this is better/direct than use object Article,
    //But it's based on the consideration of database structure,
    //I was told one should "forget" the database, but it's really hard
    public int ArticleId;

    public void Save()
    {
        //save the comment directly
    }
}
</code>```

答:
You are reaching conclusions without any real basis because you are just looking at some sample code and not considering what actually might be happening.

The whole point of using an ORM is so you can allow it to handle the database transactions while you work in an object oriented rather than a relational fashion in your application.  You really cannot say anything about how the ORM performs when you do an update on Article by just looking at Article.Save.  Article.Save is an OO construct, and what the ORM actually executes on the database is a relational action.  What about Article.Save makes you think it is inefficient?  Looking at that does not give you any information.  You would have to look at what the ORM of choice is doing on the database.

Suppose the Article is a new object.  In this case you have to save the Article, set the foreign key in the Comment, and then save the comment.  Your "preferred" code does not show the full operation but it still must occur.  The difference is the ORM gives you an object oriented way to do this - just call save on the article.  Under the hood the same operations must occur either way.  Maybe the ORM takes more steps than you could do it in manually, but maybe not.

Suppose Article is not a new object.  You add a new Comment.  Depending on the platform, when you call Save this time potentially what happens with an ORM could be no different than what you might think as better depending on how your code is written.  If there is nothing that needs to be updated in the Article, the ORM may simply save the Comment.

ORMs use various methods, but in general they maintain some kind of running account of objects that need to be updated.

You cannot just say that the first approach is somehow inefficient just on face because you called a method on Article instead of Comment - what is actually happening will depend on the specific ORM platform you use as well as the state of the objects.

Body:
I have been confused about ORM since I see the following sample code:

public class Article
{
    public List<Comment> Comments;

    public void AddComment(Comment comment)
    {
        Comments.Add(comment);
    }

    // I'm surprised by this kind of operation
    // how much performance hit it should be
    public void Save()
    {
        //update the article and all its comments
    }
}

According to what I think, the responsiblity of saving comment should be assigned to the comment itself:

public class Comment
{
    public Article BelongArticle;

    //I think this is better/direct than use object Article,
    //But it's based on the consideration of database structure,
    //I was told one should "forget" the database, but it's really hard
    public int ArticleId;

    public void Save()
    {
        //save the comment directly
    }
}


问:
Xamarin FirebaseStorage upload image
I can't figure out how to upload an image to FirebaseStorge.

```<code> var storageRef = FirebaseStorage.Instance.Reference.Child(FilePaths.FIREBASE_IMAGE_DIR + "/" + auth.CurrentUser.Uid + "/photo" + (count + 1));`
</code>```

There are 3 options:

```<code>storageRef.PutStream(); storageRef.PutFile(); storageRef.PutBytes();

FilePath = "/storage/emulator/0/Pictures/...."
</code>```

How can I convert this file to be able to upload it in firebase.
I'm new in Xamarin and I can't understand how it works.

答: Try to read this post, I used his explanation to do the same thing, and it works real good: https://www.c-sharpcorner.com/article/xamarin-android-image-uploading-to-firebase/</p>

Title: Xamarin FirebaseStorage upload image

Body:
I can't figure out how to upload an image to FirebaseStorge.

 var storageRef = FirebaseStorage.Instance.Reference.Child(FilePaths.FIREBASE_IMAGE_DIR + "/" + auth.CurrentUser.Uid + "/photo" + (count + 1));`

There are 3 options:

storageRef.PutStream(); storageRef.PutFile(); storageRef.PutBytes();

FilePath = "/storage/emulator/0/Pictures/...."

How can I convert this file to be able to upload it in firebase.
I'm new in Xamarin and I can't understand how it works.