问:
Convert in reverse ascii to whole decimal in Java
Hi all and thank you for the help in advance.

I have scoured the webs and have not really turned up with anything concrete as to my initial question.

I have a program I am developing in JAVA thats primary purpose is to read a .DAT file and extract certain values from it and then calculate an output based on the extracted values which it then writes back to the file.

The file is made up of records that are all the same length and format and thus it should be fairly straightforward to access, currently I am using a loop and and an if statement to find the first occurrence of a record and then through user input determine the length of each record to then loop through each record.

HOWEVER! The first record of this file is a blank (Or so I thought). As it turns out this first record is the key to the rest of the file in that the first few chars are ascii and reference the record length and the number of records contained within the file respectively.

below are a list of the ascii values themselves as found in the files (Disregard the " " the ascii is contained within them)

"#¼ ä "

"#g â "

"ÇG @ "

"Ç‰ ‰ "

"Çò È "

"=¼ "

A friend of mine who many years ago use to code in Basic recons the first 3 chars refer to the record length and the following 9 refer to the number of records.

Basically what I am needing to do is convert this initial string of ascii chars to two decimals in order to work out the length of each record and the number of records.

Any assistance will be greatly appreciated.

Edit...

Please find below the Basic code used to access the file in the past, perhaps this will help?

```<code>    CLS
    INPUT "Survey System Data File? : ", survey$
    survey$ = "f:\apps\survey\" + survey$
    reclen = 3004
    OPEN survey$ + ".dat" FOR RANDOM AS 1 LEN = reclen
    FIELD #1, 3 AS RL$, 9 AS n$
    GET #1, 1
    RL = CVI(RL$): n = CVI(n$)
    PRINT "Record Length     = "; RL
    reclen = RL
    PRINT "Number of Records = "; n
    CLOSE #1
</code>```

Basically what I am looking for is something similar but in java.

答:
ASCII is a special way to translate a bit pattern in a byte to a character, and that gives each character a numerical value; for the letter 'A' is this 65.

In Java, you can get that numerical value by converting the char to an int (ok, this gives you the Unicode value, but as for the ASCII characters the Unicode value is the same as for ASCII, this does not matter).

But now you need to know how the length is calculated: do you have to add the values? Or multiply them? Or append them? Or multiply them with 128^p where p is the position, and add the result? And, in the latter case, is the first byte on position 0 or position 3?

Same for the number of records, of course.

Another possible interpretation of the data is that the bytes are BCD encoded numbers. In that case, each nibble (4bit set) represents a number from 0 to 9. In that case, you have to do some bit manipulation to extract the numbers and concatenate them, from left (highest) to right (lowest). At least you do not have to struggle with the sequence and further interpretation here …

But as BCD would require 8-bit, this would be not the right interpretation if the file really contains ASCII, as ASCII is 7-bit.

Body:
Hi all and thank you for the help in advance.

I have scoured the webs and have not really turned up with anything concrete as to my initial question.

I have a program I am developing in JAVA thats primary purpose is to read a .DAT file and extract certain values from it and then calculate an output based on the extracted values which it then writes back to the file.

The file is made up of records that are all the same length and format and thus it should be fairly straightforward to access, currently I am using a loop and and an if statement to find the first occurrence of a record and then through user input determine the length of each record to then loop through each record.

HOWEVER! The first record of this file is a blank (Or so I thought). As it turns out this first record is the key to the rest of the file in that the first few chars are ascii and reference the record length and the number of records contained within the file respectively.

below are a list of the ascii values themselves as found in the files (Disregard the " " the ascii is contained within them)

"#¼ ä "

"#g â "

"ÇG @ "

"Ç‰ ‰ "

"Çò È "

"=¼ "

A friend of mine who many years ago use to code in Basic recons the first 3 chars refer to the record length and the following 9 refer to the number of records.

Basically what I am needing to do is convert this initial string of ascii chars to two decimals in order to work out the length of each record and the number of records.

Any assistance will be greatly appreciated.

Edit...

Please find below the Basic code used to access the file in the past, perhaps this will help?

    CLS
    INPUT "Survey System Data File? : ", survey$
    survey$ = "f:\apps\survey\" + survey$
    reclen = 3004
    OPEN survey$ + ".dat" FOR RANDOM AS 1 LEN = reclen
    FIELD #1, 3 AS RL$, 9 AS n$
    GET #1, 1
    RL = CVI(RL$): n = CVI(n$)
    PRINT "Record Length     = "; RL
    reclen = RL
    PRINT "Number of Records = "; n
    CLOSE #1

Basically what I am looking for is something similar but in java.


来源: stackexchange

问:
C: find the longest line
This is an example program from the book The C Programming Language by Dennis Ritchie and Brian Kernighan (Second Edition). My question is if we are passing the value(variable line) but not the reference to the function length, then how does the change reflect in the main function?</p>

```<code>#include <stdio.h>
#define MAXLINE 1000

int length(char s[], int lim);
void copy(char to[], char from[]);

int main() {
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while ((len = length(line, MAXLINE)) > 0) {
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }

    if (max > 0) {
        printf("%s", longest);
    }

    return 0;
}

int length(char s[], int lim) {
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
    }

    if (c == '\n') {
        s[i] = c;
        ++i;
    }

    s[i] = '\0';
    return i;
}

void copy(char to[], char from []) {
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0') {
        ++i;
    }
}
</code>```

答:
```<code>len = length(line, MAXLINE)
</code>```

in C all arrays are passed by pointer. so the function length receives the pointer to first char oh the array line and it modifies this array

ContentLicense: CC BY-SA 4.0

Title: C: find the longest line

Body:
This is an example program from the book The C Programming Language by Dennis Ritchie and Brian Kernighan (Second Edition). My question is if we are passing the value(variable line) but not the reference to the function length, then how does the change reflect in the main function?

#include <stdio.h>
#define MAXLINE 1000

int length(char s[], int lim);
void copy(char to[], char from[]);

int main() {
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];

    max = 0;
    while ((len = length(line, MAXLINE)) > 0) {
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    }

    if (max > 0) {
        printf("%s", longest);
    }

    return 0;
}

int length(char s[], int lim) {
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
        s[i] = c;
    }

    if (c == '\n') {
        s[i] = c;
        ++i;
    }

    s[i] = '\0';
    return i;
}

void copy(char to[], char from []) {
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0') {
        ++i;
    }
}

Body:
len = length(line, MAXLINE)

in C all arrays are passed by pointer. so the function length receives the pointer to first char oh the array line and it modifies this array


问:
style react component on click
so i have this simple divs of names:

i just want to press on one of them and get a background color of green and when pressing on another one the first one will be canceled so just one will be colored at a time. what i simply need is inline style or i don't know i'm stuck.

first.js:

import React from 'react';

```<code>function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    const classes = {
        selected: {
          backgroundColor: '#00ff00'
        }
      }

    return (
        <div
            name={name}
            title = {title}
            style={style}
        >
           {name}
        </div>
    )

}
export default SidebarComponents;
</code>```

second.js:

```<code>import React, { useEffect, useState } from "react";
import SidebarComponents from "../SidebarComponents/SidebarComponents";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Sidebar1/Sidebar.css';

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: "John Smith", title: "John Smith" },
      { name: "Male, 26 years old", title: "Gender and age" },
      { name: "john", title: "Alerts" },
      { name: "claude", title: "Recent" },
      { name: "edward", title: "Blood pressure" },
      { name: "mira", title: "Body weight" },
      { name: "alex", title: "Glucose" },
      { name: "zac", title: "SPO2" }
    ]
  });

  return (
    <div>
      {selectedComponent.componentsName.map(component => {
        return (
            <div className="row align-items-start sidebar-components">
                <div className="col">
                    <SidebarComponents
                    name={component.name}
                    title={component.title}
                    />
                </div>
          </div>
        );
      })}
    </div>
  );
}

export default Sidebar;
</code>```

答:
on Sidebar:

```<code>const [selectedName, setSelectedName] = useState(null);
//...
<SidebarComponents
  name={component.name}
  title={component.title}
  selected={component.name === selectedName}
  onSelect={setSelectedName}
/>
</code>```

on SidebarComponents:

```<code>const selectedClassName = selected ? 'selected' : '';

//...

<div
  name={name}
  title={title}
  style={style}
  className={`sidebar ${selectedClassName}`} //you must add sidebar and selected classes to your styles
  onClick={() => onSelect(name)}
>
  {name}
</div>
</code>```

Title: style react component on click

Body:
so i have this simple divs of names:

i just want to press on one of them and get a background color of green and when pressing on another one the first one will be canceled so just one will be colored at a time. what i simply need is inline style or i don't know i'm stuck.

first.js:

import React from 'react';

function SidebarComponents({name,title,selected,onSelect}) {

    const style={
        cursor: "pointer"
    };

    const classes = {
        selected: {
          backgroundColor: '#00ff00'
        }
      }

    return (

           {name}

    )

}
export default SidebarComponents;

second.js:

import React, { useEffect, useState } from "react";
import SidebarComponents from "../SidebarComponents/SidebarComponents";
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Sidebar1/Sidebar.css';

function Sidebar({ onChange }) {
  const [selectedComponent, setSelectedComponent] = useState({
    componentsName: [
      { name: "John Smith", title: "John Smith" },
      { name: "Male, 26 years old", title: "Gender and age" },
      { name: "john", title: "Alerts" },
      { name: "claude", title: "Recent" },
      { name: "edward", title: "Blood pressure" },
      { name: "mira", title: "Body weight" },
      { name: "alex", title: "Glucose" },
      { name: "zac", title: "SPO2" }
    ]
  });

  return (

      {selectedComponent.componentsName.map(component => {
        return (

                    <SidebarComponents
                    name={component.name}
                    title={component.title}
                    />

        );
      })}

  );
}

export default Sidebar;

Body:
on Sidebar:

const [selectedName, setSelectedName] = useState(null);
//...
<SidebarComponents
  name={component.name}
  title={component.title}
  selected={component.name === selectedName}
  onSelect={setSelectedName}
/>

on SidebarComponents:

const selectedClassName = selected ? 'selected' : '';

//...

<div
  name={name}
  title={title}
  style={style}
  className={`sidebar ${selectedClassName}`} //you must add sidebar and selected classes to your styles
  onClick={() => onSelect(name)}
>
  {name}
</div>


问:
mapViewWillStartLoadingMap not called
Hey guys Im trying to show the activity indicator when the map is loading.

```<code>- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
    NSLog(@"map started loading);
}
</code>```

I tried using above method, but it never gets called.
Whenever i zoom in or out the map tiles will start loading, however this method is not called.

答:
Just declaring that your class implements the protocol is not enough.  That just helps the compiler generate warnings or errors about missing or incorrect method implementations.

You have to actually set the delegate property of the map view to that class instance.

If the map view has been created in IB then right-click on the map view and connect the delegate property to File's Owner.

If the map view is created in code, then in viewDidLoad, add a line like:

```<code>mapView.delegate = self;
</code>```

If you've done all this and the method still isn't getting called, it's also possible that the regions your are viewing are already cached locally and don't need re-loading.  Try moving to a region or zooming in deep somewhere you've never been.

ContentLicense: CC BY-SA 3.0

Title: mapViewWillStartLoadingMap not called

Body:
Hey guys Im trying to show the activity indicator when the map is loading.

- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
    NSLog(@"map started loading);
}

I tried using above method, but it never gets called.
Whenever i zoom in or out the map tiles will start loading, however this method is not called.

Body:
Just declaring that your class implements the protocol is not enough.  That just helps the compiler generate warnings or errors about missing or incorrect method implementations.

You have to actually set the delegate property of the map view to that class instance.

If the map view has been created in IB then right-click on the map view and connect the delegate property to File's Owner.

If the map view is created in code, then in viewDidLoad, add a line like:

mapView.delegate = self;

If you've done all this and the method still isn't getting called, it's also possible that the regions your are viewing are already cached locally and don't need re-loading.  Try moving to a region or zooming in deep somewhere you've never been.


问:
Opening a .exe file from configurable path
I would like to know how do I open up a program in C#, in any computer, I only get it to start with

```<code>Process.Start("C:\Users\\*name*\Desktop\MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe");
</code>```

But I would like to share the program with my friends, and they don't have the same file directory as me. So how can I do that?

答:
You are free not to hardcode the desktop path.

```<code>string desktoppath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
String path = @"MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe";
Process.Start(desktoppath + @"\" + path);
</code>```

Is this something you want?

Body:
I would like to know how do I open up a program in C#, in any computer, I only get it to start with

Process.Start("C:\Users\\*name*\Desktop\MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe");

But I would like to share the program with my friends, and they don't have the same file directory as me. So how can I do that?

Body:
You are free not to hardcode the desktop path.

string desktoppath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
String path = @"MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe";
Process.Start(desktoppath + @"\" + path);

Is this something you want?


问:
Passing arguments containing spaces from one script to another in Perl
I am trying to pass arguments from one Perl script to another. Some of the arguments contain spaces.

I am reading in a comma-delimited text file and splitting each line on the comma.

```<code>my ($jockey, $racecourse, $racenum, $hnamenum, $trainer, $TDRating, $PRO) = split(/,/, $line);
</code>```

The data in the comma-delimited text file look as follows:

```<code>AARON LYNCH,WARRNAMBOOL,RACE 1,DAREBIN (8),ERIC MUSGROVE,B,1
</code>```

When I print out each variable, from the parent script, they look fine (as above).

```<code>print "$jockey\n";
print "$racecourse\n";
print "$racenum\n";
print "$hnamenum\n";
print "$trainer\n";
print "$TDRating\n";
print "$PRO\n";

AARON LYNCH
WARRNAMBOOL
RACE 1
DAREBIN (8)
ERIC MUSGROVE
B
1
</code>```

When I pass the arguments to the child script (as follows), the arguments are passed incorrectly.

```<code>system("perl \"$bindir\\narrative4.pl\" $jockey $racecourse $racenum $hnamenum $trainer $TDRating $PRO");

AARON
LYNCH
WARRNAMBOOL
RACE
1
DAREBIN
(8)
</code>```

As you can see, $ARGV[0] becomes AARON, $ARGV[1] becomes LYNCH, $ARGV[2] becomes WARRNAMBOOL, and so on.

I have investigated adding quotes to the arguments using qq, quotemeta and Win32::ShellQuote, unfortunately, even if I pass qq{"$jockey"}, the quotes are still stripped before they reach the child script, so they must be protected in some way.

I not sure if either of the aforementioned solutions is the correct but I'm happy to be corrected.

I'd appreciate any suggestions. Thanks in advance.

Note: I am running this using Strawberry Perl on a Windows 10 PC.
Note2: I purposely left out use strict; & use warnings; in these examples.

Parent Script

```<code>use Cwd;
$dir = getcwd;
$bin = "bin"; $bindir = "$dir/$bin";

$infile = "FINAL-SORTED-JOCKEY-RIDES-FILE.list";

open (INFILE, "<$infile") or die "Could not open $infile $!\n";

while (<INFILE>)
{
   $line = $_;

   chomp($line);

   my ($jockey, $racecourse, $racenum, $hnamenum, $trainer, $TDRating, $PRO) = split(/,/, $line);

   print "$jockey\n";
   print "$racecourse\n";
   print "$racenum\n";
   print "$hnamenum\n";
   print "$trainer\n";
   print "$TDRating\n";
   print "$PRO\n";

   system("perl \"$bindir\\narrative4.pl\" $jockey $racecourse $racenum $hnamenum $trainer $TDRating $PRO");

   sleep (1);
}
close INFILE;

exit;
</code>```

Child Script

```<code>$passedjockey = $ARGV[0];
$passedracecourse = $ARGV[1];
$passedracenum = $ARGV[2];
$passedhnamenum = $ARGV[3];
$passedtrainer = $ARGV[4];
$passedTDRating = $ARGV[5];
$passedPRO = $ARGV[6];

print "$passedjockey\n";
print "$passedracecourse\n";
print "$passedracenum\n";
print "$passedhnamenum\n";
print "$passedtrainer\n";
print "$passedTDRating\n";
print "$passedPRO\n\n";
</code>```

答:
That whole double-quoted string that is passed to system is first evaluated and thus all variables are interpolated -- so the intended multi-word arguments become merely words in a list. So in the end the string has a command to run with individual words as arguments.

Then, even if you figure out how to stick which quotes in there just right, so to keep those multi-word arguments "together," there's still a chance of a shell being invoked, in which case those arguments again get broken up into words before being passed to the program.

Instead of all this use the LIST form of system.  The first argument is then the name of the program that will be directly executed without a shell (see docs for some details on that), and the remaining arguments are passed as they are to that program.

parent

```<code>use warnings;
use strict;
use feature 'say';

my @args = ('first words', 'another', 'two more', 'final');

my $prog = 'print_args.pl';

system($prog, @args) == 0
    or die "Error w/ system($prog, @args): $!";
</code>```

and the invoked print_args.pl

```<code>use warnings;
use strict;
use feature 'say';

say for @ARGV;
</code>```

The @ARGV contains arguments passed to the program at invocation. There's more that can be done to inspect the error, see docs and links in them.†

By what you show you indeed don't need a shell and the LIST form is generally easy to recommend as a basic way to use system, when the shell isn't needed.  If you were to need shell's capabilities for something in that command then you'd have to figure out how to protect those spaces.

† And then there are modules for running external programs that are far better than system & Co.  From ease-of-use to features and power:
IPC::System::Simple, Capture::Tiny, IPC::Run3, IPC::Run.

Body:
I am trying to pass arguments from one Perl script to another. Some of the arguments contain spaces.

I am reading in a comma-delimited text file and splitting each line on the comma.

my ($jockey, $racecourse, $racenum, $hnamenum, $trainer, $TDRating, $PRO) = split(/,/, $line);

The data in the comma-delimited text file look as follows:

AARON LYNCH,WARRNAMBOOL,RACE 1,DAREBIN (8),ERIC MUSGROVE,B,1

When I print out each variable, from the parent script, they look fine (as above).

print "$jockey\n";
print "$racecourse\n";
print "$racenum\n";
print "$hnamenum\n";
print "$trainer\n";
print "$TDRating\n";
print "$PRO\n";

AARON LYNCH
WARRNAMBOOL
RACE 1
DAREBIN (8)
ERIC MUSGROVE
B
1

When I pass the arguments to the child script (as follows), the arguments are passed incorrectly.

system("perl \"$bindir\\narrative4.pl\" $jockey $racecourse $racenum $hnamenum $trainer $TDRating $PRO");

AARON
LYNCH
WARRNAMBOOL
RACE
1
DAREBIN
(8)

As you can see, $ARGV[0] becomes AARON, $ARGV[1] becomes LYNCH, $ARGV[2] becomes WARRNAMBOOL, and so on.

I have investigated adding quotes to the arguments using qq, quotemeta and Win32::ShellQuote, unfortunately, even if I pass qq{"$jockey"}, the quotes are still stripped before they reach the child script, so they must be protected in some way.

I not sure if either of the aforementioned solutions is the correct but I'm happy to be corrected.

I'd appreciate any suggestions. Thanks in advance.

Note: I am running this using Strawberry Perl on a Windows 10 PC.
Note2: I purposely left out use strict; & use warnings; in these examples.

Parent Script

use Cwd;
$dir = getcwd;
$bin = "bin"; $bindir = "$dir/$bin";

$infile = "FINAL-SORTED-JOCKEY-RIDES-FILE.list";

open (INFILE, "<$infile") or die "Could not open $infile $!\n";

while (<INFILE>)
{
   $line = $_;

   chomp($line);

   my ($jockey, $racecourse, $racenum, $hnamenum, $trainer, $TDRating, $PRO) = split(/,/, $line);

   print "$jockey\n";
   print "$racecourse\n";
   print "$racenum\n";
   print "$hnamenum\n";
   print "$trainer\n";
   print "$TDRating\n";
   print "$PRO\n";

   system("perl \"$bindir\\narrative4.pl\" $jockey $racecourse $racenum $hnamenum $trainer $TDRating $PRO");

   sleep (1);
}
close INFILE;

exit;

Child Script

$passedjockey = $ARGV[0];
$passedracecourse = $ARGV[1];
$passedracenum = $ARGV[2];
$passedhnamenum = $ARGV[3];
$passedtrainer = $ARGV[4];
$passedTDRating = $ARGV[5];
$passedPRO = $ARGV[6];

print "$passedjockey\n";
print "$passedracecourse\n";
print "$passedracenum\n";
print "$passedhnamenum\n";
print "$passedtrainer\n";
print "$passedTDRating\n";
print "$passedPRO\n\n";

Body:
That whole double-quoted string that is passed to system is first evaluated and thus all variables are interpolated -- so the intended multi-word arguments become merely words in a list. So in the end the string has a command to run with individual words as arguments.

Then, even if you figure out how to stick which quotes in there just right, so to keep those multi-word arguments "together," there's still a chance of a shell being invoked, in which case those arguments again get broken up into words before being passed to the program.

Instead of all this use the LIST form of system.  The first argument is then the name of the program that will be directly executed without a shell (see docs for some details on that), and the remaining arguments are passed as they are to that program.

parent

use warnings;
use strict;
use feature 'say';

my @args = ('first words', 'another', 'two more', 'final');

my $prog = 'print_args.pl';

system($prog, @args) == 0
    or die "Error w/ system($prog, @args): $!";

and the invoked print_args.pl

use warnings;
use strict;
use feature 'say';

say for @ARGV;

The @ARGV contains arguments passed to the program at invocation. There's more that can be done to inspect the error, see docs and links in them.†

By what you show you indeed don't need a shell and the LIST form is generally easy to recommend as a basic way to use system, when the shell isn't needed.  If you were to need shell's capabilities for something in that command then you'd have to figure out how to protect those spaces.

† And then there are modules for running external programs that are far better than system & Co.  From ease-of-use to features and power:
IPC::System::Simple, Capture::Tiny, IPC::Run3, IPC::Run.


答:
GROUP_CONCAT() skips NULL values.

You can use IFNULL to convert the null values to an explicit string 'null'.

```<code>SELECT entity_id,
SUBSTRING_INDEX(GROUP_CONCAT(`start` ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `start`,
SUBSTRING_INDEX(GROUP_CONCAT(IFNULL(`end`, 'null') ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `end`
FROM my_table
WHERE `start` <= '2020-05-23 23:59:59'
AND ( `end` IS NULL OR `end` BETWEEN '2020-05-23 00:00:00' AND '2020-05-23 23:59:59' )
GROUP BY entity_id ;
</code>```

Title: Missing null values in a GroupConcat

Body:
I have a table where I registry when an event start and when ends. I want a list of the events that ends between my date range or are in progress yet, but those that hasn't ended yet are wrong because the null value is missed in the group concat.

How can I get the null values with grouping by entity_id?

| id | entity_id | start                | end                  |
|----|-----------|----------------------|----------------------|
| 1  | 10        | 2020-05-22T23:50:00Z | 2020-05-23T00:15:00Z |
| 2  | 20        | 2020-05-22T23:30:00Z | 2020-05-23T00:50:00Z |
| 3  | 10        | 2020-05-23T01:00:00Z | 2020-05-23T01:10:00Z |
| 4  | 20        | 2020-05-23T01:30:00Z | 2020-05-23T01:50:00Z |
| 5  | 20        | 2020-05-23T02:00:00Z | null                 |
| 6  | 10        | 2020-05-23T05:00:00Z | null                 |

My query:

SELECT entity_id,
SUBSTRING_INDEX(GROUP_CONCAT(`start` ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `start`,
SUBSTRING_INDEX(GROUP_CONCAT(`end` ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `end`
FROM my_table
WHERE `start` <= '2020-05-23 23:59:59'
AND ( `end` IS NULL OR `end` BETWEEN '2020-05-23 00:00:00' AND '2020-05-23 23:59:59' )
GROUP BY entity_id ;

This is the query result

| entity_id | start               | end                 |
|-----------|---------------------|---------------------|
| 10        | 2020-05-23 05:00:00 | 2020-05-23 01:10:00 |
| 20        | 2020-05-23 02:00:00 | 2020-05-23 01:50:00 |

But this is what should be

| entity_id | start               | end                 |
|-----------|---------------------|---------------------|
| 10        | 2020-05-23 05:00:00 | null                |
| 20        | 2020-05-23 02:00:00 | null                |

I created an example: http://sqlfiddle.com/#!9/e04be2/1/0

Body:
GROUP_CONCAT() skips NULL values.

You can use IFNULL to convert the null values to an explicit string 'null'.

SELECT entity_id,
SUBSTRING_INDEX(GROUP_CONCAT(`start` ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `start`,
SUBSTRING_INDEX(GROUP_CONCAT(IFNULL(`end`, 'null') ORDER BY `start` DESC SEPARATOR '||'), '||', 1) AS `end`
FROM my_table
WHERE `start` <= '2020-05-23 23:59:59'
AND ( `end` IS NULL OR `end` BETWEEN '2020-05-23 00:00:00' AND '2020-05-23 23:59:59' )
GROUP BY entity_id ;


问:
Creating a df starting from a timestamp value and ending on a timestamp value increment by one hour in Spark scala
Can anyone help me to create a data frame were starting and ending timestamp value is given and we need to print all the hour increment by one?

Example
Starting timestamp: 02-05-2020 01:00

Ending timestamp: 03-05-2020 02:00

So the df should have all those values:

```<code>
02-05-2020 01:00
02-05-2020 02:00
02-05-2020 03:00
02-05-2020 04:00
02-05-2020 05:00
.
.
.
03-05-2020 02:00

</code>```

Body:
Can anyone help me to create a data frame were starting and ending timestamp value is given and we need to print all the hour increment by one?

Example
Starting timestamp: 02-05-2020 01:00

Ending timestamp: 03-05-2020 02:00

So the df should have all those values:

02-05-2020 01:00
02-05-2020 02:00
02-05-2020 03:00
02-05-2020 04:00
02-05-2020 05:00
.
.
.
03-05-2020 02:00

Body:
Check below code.

scala> val df = Seq(("02-05-2020 01:00","03-05-2020 02:00")).toDF("start","end")
df: org.apache.spark.sql.DataFrame = [start: string, end: string]

scala> df.show(false)
+----------------+----------------+
|start           |end             |
+----------------+----------------+
|02-05-2020 01:00|03-05-2020 02:00|
+----------------+----------------+

scala> :paste
// Entering paste mode (ctrl-D to finish)

// Creating UDF to get List of dates.
val dateList = udf((start:String,end: String) => {
      import org.joda.time._
      import org.joda.time.format.DateTimeFormat
      val st = DateTime.parse(start,DateTimeFormat.forPattern("dd-MM-yyyy HH:mm"))
      val et = DateTime.parse(end,DateTimeFormat.forPattern("dd-MM-yyyy HH:mm"))
      (0 to Hours.hoursBetween(st,et).getHours)
         .map(hour => st.plusHours(hour).toString(DateTimeFormat.forPattern("dd-MM-yyyy HH:mm")))
        .toList
})

// Exiting paste mode, now interpreting.

dateList: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function2>,ArrayType(StringType,true),Some(List(StringType, StringType)))

scala> df.select(explode(dateList($"start",$"end")).as("dates")).show(30,false)
+----------------+
|dates           |
+----------------+
|02-05-2020 01:00|
|02-05-2020 02:00|
|02-05-2020 03:00|
|02-05-2020 04:00|
|02-05-2020 05:00|
|02-05-2020 06:00|
|02-05-2020 07:00|
|02-05-2020 08:00|
|02-05-2020 09:00|
|02-05-2020 10:00|
|02-05-2020 11:00|
|02-05-2020 12:00|
|02-05-2020 13:00|
|02-05-2020 14:00|
|02-05-2020 15:00|
|02-05-2020 16:00|
|02-05-2020 17:00|
|02-05-2020 18:00|
|02-05-2020 19:00|
|02-05-2020 20:00|
|02-05-2020 21:00|
|02-05-2020 22:00|
|02-05-2020 23:00|
|03-05-2020 00:00|
|03-05-2020 01:00|
|03-05-2020 02:00|
+----------------+

scala>

Execution Time : Solution - 1

scala> spark.time { spark.sql("SELECT explode(sequence(1588381200, 1588471200, 3600)) as date_col").withColumn("date_col", from_unixtime($"date_col")).show(5,false)}
+-------------------+
|date_col           |
+-------------------+
|2020-05-02 06:30:00|
|2020-05-02 07:30:00|
|2020-05-02 08:30:00|
|2020-05-02 09:30:00|
|2020-05-02 10:30:00|
+-------------------+
only showing top 5 rows

Time taken: 2122 ms

Execution Time : Solution - 2

scala> :paste
// Entering paste mode (ctrl-D to finish)

spark.time {
val df = Seq(("02-05-2020 01:00","03-05-2020 02:00")).toDF("start","end")
// Creating UDF to get List of dates.
val dateList = udf((start:String,end: String) => {
      import org.joda.time._
      import org.joda.time.format.DateTimeFormat
      val st = DateTime.parse(start,DateTimeFormat.forPattern("dd-MM-yyyy HH:mm"))
      val et = DateTime.parse(end,DateTimeFormat.forPattern("dd-MM-yyyy HH:mm"))
      (0 to Hours.hoursBetween(st,et).getHours)
         .map(hour => st.plusHours(hour).toString(DateTimeFormat.forPattern("dd-MM-yyyy HH:mm")))
        .toList
})

df.select(explode(dateList($"start",$"end")).as("dates")).show(5,false)
}

// Exiting paste mode, now interpreting.

+----------------+
|dates           |
+----------------+
|02-05-2020 01:00|
|02-05-2020 02:00|
|02-05-2020 03:00|
|02-05-2020 04:00|
|02-05-2020 05:00|
+----------------+
only showing top 5 rows

Time taken: 548 ms

scala>


问:
When to use Azure blob storage versus Azure file share?
Azure newbie here.
I have an architecture requirement to move the data from on-premise to cloud database. This is done in two steps due to security restrictions and timelines.

Move the file to azure blob storage

Read from the blob and Import to the sql database .

Azure blob is suggested for unstructured data. However, the data we want to export to cloud is a simple export of data from sql tables to csv  files.

For such requirements what is recommended? Azure blob or Azure file share? When to use blob versus azure file share ?

答:
Actually, if you want to migrate database from local/on-premise SQL Server to Azure SQL, there are many ways can help do that directly without Blob or File Storage.

Such as:

Using Data Migration Assistant(DMA) to help you migrate the data/database to Azure.

Ref: Migrate on-premises SQL Server or SQL Server on Azure VMs to Azure SQL Database using the Data Migration Assistant

SQL Server Management Studio(SSMS) task: Deploy Database to Microsoft Azure SQL Database.

Ref: Using the Deploy Database to SQL Azure Wizard in SQL Server Management Studio to move to the Cloud

Of course you could export the sql server data as CSV files to Blob or File storage, then import the csv file to Azure SQL. In usually, we often use Blob Storage work with Azure SQL database. It's up to you, reference the document @Gaurav Mantri-AIS mentioned.

Hope this helps.


问:
Check if password contains easy sequences with php
I want to have an php check for easy passwords patterns like

```<code>123456
123456789
abcde
98764321
101010
202020
</code>```

Is it possible to have a check like this that doesn't rely in maintaining an array of pre-defined strings ?

答:
Just iterate to each letter and check if the next one is same, one less or one more as current. So you can create a score of uniqueness.

For last case you can check if there are duplicate characters and remove from score, too.

$passwords = ['123456', '123456789', 'abcde', '98764321', '101010', '202020', 'xhdgszu'];

foreach ($passwords as $password) {
    $score = $length = strlen($password);
    $chars = str_split($password);

    for ($i = 0; $i < $length - 1; $i++) {
        $currentChar = $chars[$i];
        $nextChar = $chars[$i + 1];
        if ($currentChar === $nextChar
            || ord($currentChar) - 1 === ord($nextChar)
            || ord($currentChar) + 1 === ord($nextChar)
        ) {
            $score--;
            continue;
        }
    }

    $unique = array_unique($chars);
    $score -= $length - count($unique);

    echo "{$password}: {$score} / {$length} ", ($score < $length) ? 'Bad' : 'Good', PHP_EOL;
}
```

```123456: 1 / 6 Bad
123456789: 1 / 9 Bad
abcde: 1 / 5 Bad
98764321: 2 / 8 Bad
101010: -3 / 6 Bad
202020: 2 / 6 Bad
xhdgszu: 7 / 7 Good

```

Body:
I want to have an php check for easy passwords patterns like

123456
123456789
abcde
98764321
101010
202020

Is it possible to have a check like this that doesn't rely in maintaining an array of pre-defined strings ?

Body:
Just iterate to each letter and check if the next one is same, one less or one more as current. So you can create a score of uniqueness.

For last case you can check if there are duplicate characters and remove from score, too.

$passwords = ['123456', '123456789', 'abcde', '98764321', '101010', '202020', 'xhdgszu'];

foreach ($passwords as $password) {
    $score = $length = strlen($password);
    $chars = str_split($password);

    for ($i = 0; $i < $length - 1; $i++) {
        $currentChar = $chars[$i];
        $nextChar = $chars[$i + 1];
        if ($currentChar === $nextChar
            || ord($currentChar) - 1 === ord($nextChar)
            || ord($currentChar) + 1 === ord($nextChar)
        ) {
            $score--;
            continue;
        }
    }

    $unique = array_unique($chars);
    $score -= $length - count($unique);

    echo "{$password}: {$score} / {$length} ", ($score < $length) ? 'Bad' : 'Good', PHP_EOL;
}

123456: 1 / 6 Bad
123456789: 1 / 9 Bad
abcde: 1 / 5 Bad
98764321: 2 / 8 Bad
101010: -3 / 6 Bad
202020: 2 / 6 Bad
xhdgszu: 7 / 7 Good


答:
This definition:

```<code>int length(char s[], int lim)
</code>```

can be rewritten as:

```<code>int length(char *s, int lim)
</code>```

which might make it easier to understand. We don't pass the variable by value, we pass the pointer, so the function can access the data and modify it if necessary.

Title: C: find the longest line

Body:
This definition:

int length(char s[], int lim)

can be rewritten as:

int length(char *s, int lim)

which might make it easier to understand. We don't pass the variable by value, we pass the pointer, so the function can access the data and modify it if necessary.


问:
How to render children within react functional components using react and typescript?
i want to render the component that is passed to the react functional component using react and typescript.

below is my code,

```<code>function MainComponent () {
    return (
        <Wrapper>
            <SomeOtheComponent/>
            <DragAndDrop>
                <ListContent> //this is the children for the DragAndDrop component and want this to
                    //render within DragAndDrop component
                    {condition_true && (
                        <FirstList/>
                    )}
                    {condition_true && (
                        <SecondList/>
                    )}
                </ListContent>
            </Wrapper>
        );
    }

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }

     };

     const handleDragOut = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragCounter((prev: number) => prev - 1);
         if (dragCounter === 0) {
             setDragging(false);
         }
     };

     const handleDrop = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragging(false);
         if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
             e.dataTransfer.clearData();
             setDragCounter(0);
         }
     };

     return (
         <DropZone
             ref={dropRef}
             onDragEnter={handleDragIn}
             onDragLeave={handleDragOut}
             onDragOver={handleDrag}
             onDrop={handleDrop}
         >
             {dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}
         </DropZone>
     );
 };
</code>```

Now the question is why doesnt ListContent within DragAndDrop Component render....I am not sure if there is something wrong with the way i pass children to DragAndDrop component in MainComponent. could someone help me with this. thanks.

答:
The dragging value is set to false from the useState call in DragAndDrop, so on first render, the DropZoneOverlay won't get rendered.

```<code>{dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}
</code>```

Body:
i want to render the component that is passed to the react functional component using react and typescript.

below is my code,

function MainComponent () {
    return (
        <Wrapper>
            <SomeOtheComponent/>
            <DragAndDrop>
                <ListContent> //this is the children for the DragAndDrop component and want this to
                    //render within DragAndDrop component
                    {condition_true && (
                        <FirstList/>
                    )}
                    {condition_true && (
                        <SecondList/>
                    )}
                </ListContent>
            </Wrapper>
        );
    }

const DragAndDrop: React.FC = ({ children }) => { //here i am passing children
    const [dragging, setDragging] = useState(false);
    const [dragCounter, setDragCounter] = useState(0);

    React.useEffect(() => {
        // componentDidMount()
        setDragCounter(0);
    }, []);

    const handleDrag = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
    };

    const handleDragIn = (e: any) => {
        e.preventDefault();
        e.stopPropagation();
        setDragCounter((prev: number) => prev + 1);
        if (e.dataTransfer.files) {
            setDragging(true);
        }

     };

     const handleDragOut = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragCounter((prev: number) => prev - 1);
         if (dragCounter === 0) {
             setDragging(false);
         }
     };

     const handleDrop = (e: any) => {
         e.preventDefault();
         e.stopPropagation();
         setDragging(false);
         if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
             e.dataTransfer.clearData();
             setDragCounter(0);
         }
     };

     return (
         <DropZone
             ref={dropRef}
             onDragEnter={handleDragIn}
             onDragLeave={handleDragOut}
             onDragOver={handleDrag}
             onDrop={handleDrop}
         >
             {dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}
         </DropZone>
     );
 };

Now the question is why doesnt ListContent within DragAndDrop Component render....I am not sure if there is something wrong with the way i pass children to DragAndDrop component in MainComponent. could someone help me with this. thanks.

Body:
The dragging value is set to false from the useState call in DragAndDrop, so on first render, the DropZoneOverlay won't get rendered.

{dragging && <DropZoneOverlay>{children}</DropZoneOverlay>}


问:
Move text cursor to particular screen coordinate?
How can I set the cursor at the desired location on the console in C or C++?

I remember a function called gotoxy(x,y), but I think its deprecated. Is there any alternative?

答:
You can use this to set the cursor to specific coordinates on the screen, and then simply use cout<< or printf statement to print anything on the console:</p>

```<code>#include <iostream>
#include <windows.h>

using namespace std;

void set_cursor(int,int);

int main()
{
     int x=0 , y=0;
     set_cursor(x,y);
     cout<<"Mohammad Usman Sajid";

     return 0;
}

void set_cursor(int x = 0 , int y = 0)
{
    HANDLE handle;
    COORD coordinates;
    handle = GetStdHandle(STD_OUTPUT_HANDLE);
    coordinates.X = x;
    coordinates.Y = y;
    SetConsoleCursorPosition ( handle , coordinates );
}
</code>```

Body:
You can use this to set the cursor to specific coordinates on the screen, and then simply use cout<< or printf statement to print anything on the console:

#include <iostream>
#include <windows.h>

using namespace std;

void set_cursor(int,int);

int main()
{
     int x=0 , y=0;
     set_cursor(x,y);
     cout<<"Mohammad Usman Sajid";

     return 0;
}

void set_cursor(int x = 0 , int y = 0)
{
    HANDLE handle;
    COORD coordinates;
    handle = GetStdHandle(STD_OUTPUT_HANDLE);
    coordinates.X = x;
    coordinates.Y = y;
    SetConsoleCursorPosition ( handle , coordinates );
}


问:
Solr search query for dynamic fields indexed
I am implementing the solr search in my project .
I have one question regarding how do i search a dynamic fields that is created in a solr index
Eg:-  this is the tag that is formed in the index

And I am  trying to search from solr using this query Employee_* = 172

Please help me in this if the way of searching is incorrect.

答: In your queries, you need to define exactly what concrete fields you want to search, e.g. Employee_a, Employee_b (or whatever dynamic fields you've used). You can't search in all dynamic fields by using wildcards in a field name in queries.


问:
Autodesk Forge Create Activity
I am using Autodesk Forge DesignAutomatin V3 in C# and am getting an error when creating an Activity.

this is the error i receive: System.IO.InvalidDataException: 'CommandLine is a required property for Activity and cannot be null'

Here is how i am setting up the activity.

```<code>var activity = new Activity()
{
    CommandLine = new List<string>() { $"$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{_bundleId}].path) /s $(settings[script].path)" },
    Parameters = new Dictionary<string, ModelParameter>()
    {
        { "HostDwg", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "$(HostDwg)", Required = true } },
        { "InputModel", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "3DBuild.dxf", Required = true, } },
        { "Result", new ModelParameter() { Verb = ModelParameter.VerbEnum.Put, Zip = true, LocalName = _outPutFileName, Required = true } }
    },
    Engine = _engineVersion,
    Appbundles = new List<string>() { myApp },
    Settings = new Dictionary<string, dynamic>()
    {
        { "script", new StringSetting() { Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", _outPutFileName) } }
    },
    Description = "DXF processor",
    Version = 1,
    Id = _activityName
};
</code>```

答:
Please use exclusive Design Automation .NET core SDK for v3, it appears that you are referring Design Automation namespace from autodesk.forge.
When you add new SDK, make sure you remove this -     using Autodesk.Forge.Model.DesignAutomation.v3; from your code.

var activity = new Activity() {
 CommandLine = new List < string > () {
  $ "$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{PackageName}].path) /s $(settings[script].path)"
 }, Parameters = new Dictionary < string, Parameter > () {
  {
   "HostDwg",
   new Parameter() {
    Verb = Verb.Get, LocalName = "$(HostDwg)", Required = true
   }
  }, {
   "InputModel",
   new Parameter() {
    Verb = Verb.Get, LocalName = "3DBuild.dxf", Required = true,
   }
  }, {
   "Result",
   new Parameter() {
    Verb = Verb.Put, Zip = true, LocalName = outputFile, Required = true
   }
  }
 }, Engine = TargetEngine, Appbundles = new List < string > () {
  myApp
 }, Settings = new Dictionary < string, ISetting > () {
  {
   "script",
   new StringSetting() {
    Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", outputFile)
   }
  }
 }, Description = "DXF processor", Version = 1, Id = ActivityName
};
```

Title: Autodesk Forge Create Activity

Body:
I am using Autodesk Forge DesignAutomatin V3 in C# and am getting an error when creating an Activity.

this is the error i receive: System.IO.InvalidDataException: 'CommandLine is a required property for Activity and cannot be null'

Here is how i am setting up the activity.

var activity = new Activity()
{
    CommandLine = new List<string>() { $"$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{_bundleId}].path) /s $(settings[script].path)" },
    Parameters = new Dictionary<string, ModelParameter>()
    {
        { "HostDwg", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "$(HostDwg)", Required = true } },
        { "InputModel", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "3DBuild.dxf", Required = true, } },
        { "Result", new ModelParameter() { Verb = ModelParameter.VerbEnum.Put, Zip = true, LocalName = _outPutFileName, Required = true } }
    },
    Engine = _engineVersion,
    Appbundles = new List<string>() { myApp },
    Settings = new Dictionary<string, dynamic>()
    {
        { "script", new StringSetting() { Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", _outPutFileName) } }
    },
    Description = "DXF processor",
    Version = 1,
    Id = _activityName
};


问:
How to set a Key Vault secret from Azure Function app in the same resource group?
I would like to set up an Azure Function, which would run every 4h, retrieve a JWK from an URL (it is not the one I show below) and save it into a Key Vault as a secret.

When I try the Powershell code at the command line, it just works:

```<code>PS C:\> $x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) |
>> Select-Object -expand x5c
PS C:\> $secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
PS C:\> $secret = Set-AzKeyVaultSecret -VaultName my-keyvault -Name 'MyLittleSecret' -SecretValue $secretvalue
</code>```

and I can see the secret in the Key Vault:

However when I try to set up a timed Azure Function, then nothing happens, when I click "Run":

I suppose that being a Function newbie I am looking in the wrong place for the logs... But even if I find them, is that the correct way to do my task?

Does Azure PowerShell work in a Function?

Does it require a Login-AzAccount first?

答:
Does Azure PowerShell work in a Function?

Yes, it will work.

Does it require a Login-AzAccount first?

No, you don't need to do that.

For more details, please follow the steps below.

1.Make sure you created the function app with the settings like below.

2.After creating the function app, navigate to the Identity of the app in the portal, enable the System assigned MSI like below.

3.Navigate to your keyvault in the portal -> Access policies -> Add Access Policy -> search for your function name(the MSI has the same name as your function) and add it with correct secret permissions.

4.In the function, no need to login manually, it will login with the MSI automatically, just use the command below, it works fine on my side.

```<code>param($Timer)

$x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys | ConvertFrom-Json |Select-Object -expand keys |Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) | Select-Object -expand x5c
$secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
$secret = Set-AzKeyVaultSecret -VaultName joykeyvault -Name 'MyLittleSecret' -SecretValue $secretvalue
Write-Host $secret.Name
</code>```

Check the keyvault:

Body:
I would like to set up an Azure Function, which would run every 4h, retrieve a JWK from an URL (it is not the one I show below) and save it into a Key Vault as a secret.

When I try the Powershell code at the command line, it just works:

PS C:\> $x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) |
>> Select-Object -expand x5c
PS C:\> $secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
PS C:\> $secret = Set-AzKeyVaultSecret -VaultName my-keyvault -Name 'MyLittleSecret' -SecretValue $secretvalue

and I can see the secret in the Key Vault:

However when I try to set up a timed Azure Function, then nothing happens, when I click "Run":

I suppose that being a Function newbie I am looking in the wrong place for the logs... But even if I find them, is that the correct way to do my task?

Does Azure PowerShell work in a Function?

Does it require a Login-AzAccount first?

Body:
Does Azure PowerShell work in a Function?

Yes, it will work.

Does it require a Login-AzAccount first?

No, you don't need to do that.

For more details, please follow the steps below.

1.Make sure you created the function app with the settings like below.

2.After creating the function app, navigate to the Identity of the app in the portal, enable the System assigned MSI like below.

3.Navigate to your keyvault in the portal -> Access policies -> Add Access Policy -> search for your function name(the MSI has the same name as your function) and add it with correct secret permissions.

4.In the function, no need to login manually, it will login with the MSI automatically, just use the command below, it works fine on my side.

param($Timer)

$x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys | ConvertFrom-Json |Select-Object -expand keys |Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) | Select-Object -expand x5c
$secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
$secret = Set-AzKeyVaultSecret -VaultName joykeyvault -Name 'MyLittleSecret' -SecretValue $secretvalue
Write-Host $secret.Name

Check the keyvault:


问:
How to retrieve elements in foreach loop in Mule4?
I have defined a variable to keep application/json collection.

My original payload contain following json block;

```<code>"amendments": {
    "amendmentId": ["8a9a84b76b5a5a59016b687bae35012e",
                "8a9a84b76b5a5a59016b6888e90e0144"]
                }

<set-variable value="#[payload..amendmentId[1]]" doc:name="AmendmentIds" doc:id="03b6c46a-fc7b-43d4-b23a-502146ef0b13" variableName="amendmentids"/>
<logger level="INFO" doc:name="Logger" doc:id="6a1ad892-65f9-4dd2-9891-bdf3ad64c908" message="#[vars.amendmentids]" />
</code>```

It prints as;

```<code>[
  "8a9a84b76b5a5a59016b687bae35012e",
  "8a9a84b76b5a5a59016b6888e90e0144"
]
</code>```

Then I use ForEach loop to define few process logic for each Id,
Within foreach loop how I can get, each above id?
I used,vars.amendmentids[vars.counter]], but getting following error[1]

```<code><foreach doc:name="For Each" doc:id="7b741315-aa28-4704-82f0-629c21d93853" collection="#[vars.amendmentids]">
            <logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[vars.amendmentids[vars.counter]]"/>

        </foreach>
</code>```

[1]

```<code>Message               : "Internal execution exception while executing the script, this is most probably a bug, file an issue with the script and the input data.
Caused by:
java.lang.RuntimeException: Unable to infer a output media type as more than one is being used: application/json,application/java please specify using: output <your mime-type> --- <expr>
    at org.mule.weave.v2.el.MuleDataWeaveHelper$.inferImplicitOutput(MuleDataWeaveHelper.scala:69)
.............
" evaluating expression: "vars.amendmentids[vars.counter]".
Error type            : MULE:EXPRESSION
</code>```

答:
I fixed it by defining output mime type like;</p>

```<code><logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[output application/java --- vars.amendmentids[vars.counter - 1]]"/>
</code>```

Body:
I have defined a variable to keep application/json collection.

My original payload contain following json block;

"amendments": {
    "amendmentId": ["8a9a84b76b5a5a59016b687bae35012e",
                "8a9a84b76b5a5a59016b6888e90e0144"]
                }

<set-variable value="#[payload..amendmentId[1]]" doc:name="AmendmentIds" doc:id="03b6c46a-fc7b-43d4-b23a-502146ef0b13" variableName="amendmentids"/>
<logger level="INFO" doc:name="Logger" doc:id="6a1ad892-65f9-4dd2-9891-bdf3ad64c908" message="#[vars.amendmentids]" />

It prints as;

[
  "8a9a84b76b5a5a59016b687bae35012e",
  "8a9a84b76b5a5a59016b6888e90e0144"
]

Then I use ForEach loop to define few process logic for each Id,
Within foreach loop how I can get, each above id?
I used,vars.amendmentids[vars.counter]], but getting following error[1]

<foreach doc:name="For Each" doc:id="7b741315-aa28-4704-82f0-629c21d93853" collection="#[vars.amendmentids]">
            <logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[vars.amendmentids[vars.counter]]"/>

        </foreach>

[1]

Message               : "Internal execution exception while executing the script, this is most probably a bug, file an issue with the script and the input data.
Caused by:
java.lang.RuntimeException: Unable to infer a output media type as more than one is being used: application/json,application/java please specify using: output <your mime-type> --- <expr>
    at org.mule.weave.v2.el.MuleDataWeaveHelper$.inferImplicitOutput(MuleDataWeaveHelper.scala:69)
.............
" evaluating expression: "vars.amendmentids[vars.counter]".
Error type            : MULE:EXPRESSION

Body:
I fixed it by defining output mime type like;

<logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[output application/java --- vars.amendmentids[vars.counter - 1]]"/>


问:
If I have a favicon, do I need to link to it?
I have a Favicon and in my page I have something like:

```<code><link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
</code>```

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun

答: As long as your favicon is in the root of your website (ie. /favicon.ico), then yes you can drop this link. The link allows you to change where you want to store your favicon.

Body:
I have a Favicon and in my page I have something like:

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

This works fine. But inspired by the book "Ultra Fast asp" I am trying to remove all the small bits that are not necessary. I read a lot about browsers looking for favicon.ico anyway. (People complaining about 404 errors if they do not have a favicon).

So I was wondering: what is the use of the link if the browser looks for it anyway. It is "dead wood" -> so can I just remove this link completely or am I missing something.

thanks for your ideas,
Pleun


问:
How to merge multiple dummy variables columns which were created from a single categorical variable into single column in python?
I am working on IPL dataset which has many categorical variables one such variable is toss_winner. I have created dummy variable for this and now I have 15 columns with binary values. I want to merge all these column into single column with numbers 0-14 each number representing IPL team.

答:
IIUC, Use:

```<code>df['Team No.'] = dummies.cumsum(axis=1).ne(1).sum(axis=1)
</code>```

Example,

```<code>df = pd.DataFrame({'Toss winner': ['Chennai', 'Mumbai', 'Rajasthan', 'Banglore', 'Hyderabad']})
dummies = pd.get_dummies(df['Toss winner'])
df['Team No.'] = dummies.cumsum(axis=1).ne(1).sum(axis=1)
</code>```

Result:

```<code># print(dummies)
   Banglore  Chennai  Hyderabad  Mumbai  Rajasthan
0         0        1          0       0          0
1         0        0          0       1          0
2         0        0          0       0          1
3         1        0          0       0          0
4         0        0          1       0          0

# print (df)
  Toss winner  Team No.
0     Chennai         1
1      Mumbai         3
2   Rajasthan         4
3    Banglore         0
4   Hyderabad         2
</code>```

Body:
IIUC, Use:

df['Team No.'] = dummies.cumsum(axis=1).ne(1).sum(axis=1)

Example,

df = pd.DataFrame({'Toss winner': ['Chennai', 'Mumbai', 'Rajasthan', 'Banglore', 'Hyderabad']})
dummies = pd.get_dummies(df['Toss winner'])
df['Team No.'] = dummies.cumsum(axis=1).ne(1).sum(axis=1)

Result:

# print(dummies)
   Banglore  Chennai  Hyderabad  Mumbai  Rajasthan
0         0        1          0       0          0
1         0        0          0       1          0
2         0        0          0       0          1
3         1        0          0       0          0
4         0        0          1       0          0

# print (df)
  Toss winner  Team No.
0     Chennai         1
1      Mumbai         3
2   Rajasthan         4
3    Banglore         0
4   Hyderabad         2


问:
How to pass textbox value to java script on button click event

Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

```<code><asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>
</code>```

PassValue is JavaScript method.

Thanks in Advance.

答:
```<code><asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
<asp:Button runat="server" ID="Click" OnClientClick="GetTextBoxValue('<%= rowID.ClientID %>')"/>

function GetTextBoxValue(textBoxID){
   var value = window.document.getElementById(textBoxID).value; }
</code>```

Body:
Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

<asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>

PassValue is JavaScript method.

Thanks in Advance.


问:
How can I tune my neural network to avoid overfitting the mnist data set?

!!!!!!!!!TL;DR at the bottom!!!!!!!!

In an attempt to learn the in's and out's of ML, I have been implementing a neural network optimizer in c++ and wrapped it with swig as a python module. Of course, the first problem I tackled was XOR via the following snip of code: 2 input layers, 2 hidden layers, 1 output layer.

```<code>from MikeLearn import NeuralNetwork
from MikeLearn import ClassificationOptimizer
import time

#=======================================================
# Training Set
#=======================================================

X = [[0,1],[1,0],[1,1],[0,0]]
Y = [[1],[1],[0],[0]]

nIn = len(X[0])
nOut = len(Y[0])

#=======================================================
# Model
#=======================================================
verbosity = 0

#Initualize neural network
# NeuralNetwork([nInputs, nHidden1, nHidden2,..,nOutputs],['Activation1','Activation2'...]
N = NeuralNetwork([nIn,2,nOut],['sigmoid','sigmoid'])
N.setLoggerVerbosity(verbosity)

#Initialize the classification optimizer
#ClassificationOptimizer(NeuralNetwork,Xtrain,Ytrain)
Opt = ClassificationOptimizer(N,X,Y)
Opt.setLoggerVerbosity(verbosity)

start_time = time.time();

#fit data
#fit(nEpoch,LearningRate)
E = Opt.fit(10000,0.1)
print("--- %s seconds ---" % (time.time() - start_time))

#Make a prediction
print(Opt.predict(X))
</code>```

This snippet of code yields the following output (Correct answer would be [1,1,0,0])

```<code>--- 0.10273098945617676 seconds ---
((0.9398755431175232,), (0.9397522211074829,), (0.0612373948097229,), (0.04882470518350601,))
>>>
</code>```

Looks great!
Now for the issue. The following snippet of code tries to learn from the mnist dataset, but suffers very obviously from overfitting. ~750 input (28X28 pixels), 50 hidden, 10 output

```<code>from MikeLearn import NeuralNetwork
from MikeLearn import ClassificationOptimizer
import matplotlib.pyplot as plt
import numpy as np
import pickle
import time

#=======================================================
# Data Set
#=======================================================

#load the data dictionary
modeldata = pickle.load( open( "mnist_data.p", "rb" ) )
X = modeldata['X']
Y = modeldata['Y']

#normalize data
X = np.array(X)
X = X/255
X = X.tolist()

#training set
X1 = X[0:49999]
Y1 = Y[0:49999]

#validation set
X2 = X[50000:59999]
Y2 = Y[50000:59999]

#number of inputs/outputs
nIn = len(X[0]) #~750
nOut = len(Y[0]) #=10

#=======================================================
# Model
#=======================================================
verbosity = 1

#Initualize neural network
# NeuralNetwork([nInputs, nHidden1, nHidden2,..,nOutputs],['Activation1','Activation2'...]
N = NeuralNetwork([nIn,50,nOut],['sigmoid','sigmoid'])
N.setLoggerVerbosity(verbosity)

#Initialize optimizer
#ClassificationOptimizer(NeuralNetwork,Xtrain,Ytrain)
Opt = ClassificationOptimizer(N,X1,Y1)
Opt.setLoggerVerbosity(verbosity)

start_time = time.time();
#fit data
#fit(nEpoch,LearningRate)
E = Opt.fit(10,0.1)
print("--- %s seconds ---" % (time.time() - start_time))

#================================
#Final Accuracy on training set
#================================
XL = Opt.predict(X1)

correct = 0
for i,x in enumerate(XL):
    if XL[i].index(max(XL[i])) == Y[i].index(max(Y1[i])):
        correct = correct + 1

print("Training set Correct = " +  str(correct))
Accuracy = correct/len(XL)*100;
print("Accuracy = " + str(Accuracy) + '%')

#================================
#Final Accuracy on validation set
#================================
XL = Opt.predict(X2)

correct = 0
for i,x in enumerate(XL):
    if XL[i].index(max(XL[i])) == Y[i].index(max(Y2[i])):
        correct = correct + 1

print("Testing set Correct = " +  str(correct))
Accuracy = correct/len(XL)*100;
print("Accuracy = " + str(Accuracy)+'%')
</code>```

That snippet of code yields the following output which shows the training accuracy and validation accuracy.

```<code>-------------------------
Epoch
9
-------------------------
E=
0.00696964
E=
0.350509
E=
3.49568e-05
E=
4.09073e-06
E=
1.38491e-06
E=
0.229873
E=
3.60186e-05
E=
0.000115187
E=
2.29978e-06
E=
2.69165e-06
--- 27.400235176086426 seconds ---
Training set Correct = 48435
Accuracy = 96.87193743874877%
Testing set Correct = 982
Accuracy = 9.820982098209821%
</code>```

The training set accuracy is great, but then the testing set is no better than a random guess. Any idea what could be causing this?

TL;DR

Solved XOR with a model 2 inputs, 2 hidden, 1 output and sigmoid activation functions. Good results.

Tried to solve the Mnist data set with a model of 750 inputs (28X28 pixels), 50 hidden, 10 output and sigmoid activation functions. Severe overfitting issue. 95% accuracy on the training set, 10% accuracy on validation set.

Any Idea what is causing this?

答:
The cause of overfitting is a combination of the data and model (network in this case). During the training is was 'lazy' and found aspects of the data that worked well in training data but not generalize well.

It is difficult/impossible to point out exactly where in the trained network the nodes/weights are located that are responsible for overfitting.

But we can avoid overfitting with several tricks:

Regularisation

Drop-out (easier to implement)

Change Network Architecture (less layers/less nodes/more dimension-reduction)

https://machinelearningmastery.com/dropout-for-regularizing-deep-neural-networks/

To get an idea of regularization, try the playground from tensorflow:

https://playground.tensorflow.org/

A visualisation of dropout

https://yusugomori.com/projects/deep-learning/dropout-relu

Besides try out regularisation techniques, also experiments with different NN architectures.

Body:
!!!!!!!!!TL;DR at the bottom!!!!!!!!

In an attempt to learn the in's and out's of ML, I have been implementing a neural network optimizer in c++ and wrapped it with swig as a python module. Of course, the first problem I tackled was XOR via the following snip of code: 2 input layers, 2 hidden layers, 1 output layer.

from MikeLearn import NeuralNetwork
from MikeLearn import ClassificationOptimizer
import time

#=======================================================
# Training Set
#=======================================================

X = [[0,1],[1,0],[1,1],[0,0]]
Y = [[1],[1],[0],[0]]

nIn = len(X[0])
nOut = len(Y[0])

#=======================================================
# Model
#=======================================================
verbosity = 0

#Initualize neural network
# NeuralNetwork([nInputs, nHidden1, nHidden2,..,nOutputs],['Activation1','Activation2'...]
N = NeuralNetwork([nIn,2,nOut],['sigmoid','sigmoid'])
N.setLoggerVerbosity(verbosity)

#Initialize the classification optimizer
#ClassificationOptimizer(NeuralNetwork,Xtrain,Ytrain)
Opt = ClassificationOptimizer(N,X,Y)
Opt.setLoggerVerbosity(verbosity)

start_time = time.time();

#fit data
#fit(nEpoch,LearningRate)
E = Opt.fit(10000,0.1)
print("--- %s seconds ---" % (time.time() - start_time))

#Make a prediction
print(Opt.predict(X))

This snippet of code yields the following output (Correct answer would be [1,1,0,0])

--- 0.10273098945617676 seconds ---
((0.9398755431175232,), (0.9397522211074829,), (0.0612373948097229,), (0.04882470518350601,))
>>>

Looks great!
Now for the issue. The following snippet of code tries to learn from the mnist dataset, but suffers very obviously from overfitting. ~750 input (28X28 pixels), 50 hidden, 10 output

from MikeLearn import NeuralNetwork
from MikeLearn import ClassificationOptimizer
import matplotlib.pyplot as plt
import numpy as np
import pickle
import time

#=======================================================
# Data Set
#=======================================================

#load the data dictionary
modeldata = pickle.load( open( "mnist_data.p", "rb" ) )
X = modeldata['X']
Y = modeldata['Y']

#normalize data
X = np.array(X)
X = X/255
X = X.tolist()

#training set
X1 = X[0:49999]
Y1 = Y[0:49999]

#validation set
X2 = X[50000:59999]
Y2 = Y[50000:59999]

#number of inputs/outputs
nIn = len(X[0]) #~750
nOut = len(Y[0]) #=10

#=======================================================
# Model
#=======================================================
verbosity = 1

#Initualize neural network
# NeuralNetwork([nInputs, nHidden1, nHidden2,..,nOutputs],['Activation1','Activation2'...]
N = NeuralNetwork([nIn,50,nOut],['sigmoid','sigmoid'])
N.setLoggerVerbosity(verbosity)

#Initialize optimizer
#ClassificationOptimizer(NeuralNetwork,Xtrain,Ytrain)
Opt = ClassificationOptimizer(N,X1,Y1)
Opt.setLoggerVerbosity(verbosity)

start_time = time.time();
#fit data
#fit(nEpoch,LearningRate)
E = Opt.fit(10,0.1)
print("--- %s seconds ---" % (time.time() - start_time))

#================================
#Final Accuracy on training set
#================================
XL = Opt.predict(X1)

correct = 0
for i,x in enumerate(XL):
    if XL[i].index(max(XL[i])) == Y[i].index(max(Y1[i])):
        correct = correct + 1

print("Training set Correct = " +  str(correct))
Accuracy = correct/len(XL)*100;
print("Accuracy = " + str(Accuracy) + '%')

#================================
#Final Accuracy on validation set
#================================
XL = Opt.predict(X2)

correct = 0
for i,x in enumerate(XL):
    if XL[i].index(max(XL[i])) == Y[i].index(max(Y2[i])):
        correct = correct + 1

print("Testing set Correct = " +  str(correct))
Accuracy = correct/len(XL)*100;
print("Accuracy = " + str(Accuracy)+'%')

That snippet of code yields the following output which shows the training accuracy and validation accuracy.

-------------------------
Epoch
9
-------------------------
E=
0.00696964
E=
0.350509
E=
3.49568e-05
E=
4.09073e-06
E=
1.38491e-06
E=
0.229873
E=
3.60186e-05
E=
0.000115187
E=
2.29978e-06
E=
2.69165e-06
--- 27.400235176086426 seconds ---
Training set Correct = 48435
Accuracy = 96.87193743874877%
Testing set Correct = 982
Accuracy = 9.820982098209821%

The training set accuracy is great, but then the testing set is no better than a random guess. Any idea what could be causing this?

TL;DR

Solved XOR with a model 2 inputs, 2 hidden, 1 output and sigmoid activation functions. Good results.

Tried to solve the Mnist data set with a model of 750 inputs (28X28 pixels), 50 hidden, 10 output and sigmoid activation functions. Severe overfitting issue. 95% accuracy on the training set, 10% accuracy on validation set.

Any Idea what is causing this?


问:
Creating instance or local variables in Rails erb file?
I've got some purely UI related computation like determining the html/css class in the following example:

<% class = score < 60 ? "red" : "green" %>
```

If this is done in the erb templates rather than the controller, which is preferred when creating the variable, class or @class?

答:
which is preferred when creating the variable, class or @class?

You can't create a variable called class since is a reserved keyword. In the other hand @class is perfectly valid.

Speaking about creating variables in a view file, that's not good advice. It's often common to encourage people to leave views far from any logic you might have.

If you're in the rush of doing so, then simply use a ternary operator:

```<code>score < 60 ? 'red' : 'green'
</code>```

Body:
I've got some purely UI related computation like determining the html/css class in the following example:

<% class = score < 60 ? "red" : "green" %>

If this is done in the erb templates rather than the controller, which is preferred when creating the variable, class or @class?

Body:
which is preferred when creating the variable, class or @class?

You can't create a variable called class since is a reserved keyword. In the other hand @class is perfectly valid.

Speaking about creating variables in a view file, that's not good advice. It's often common to encourage people to leave views far from any logic you might have.

If you're in the rush of doing so, then simply use a ternary operator:

score < 60 ? 'red' : 'green'


答:
If local variable is enough, use local variable.

But, apart from that, view is virtually never a good place to define any variables. Why don't you use helper instead? Like this, for example:

```<code>def score_class(score)
  score < 60 ? 'red' : 'green'
end
</code>```

Title: Creating instance or local variables in Rails erb file?

Body:
If local variable is enough, use local variable.

But, apart from that, view is virtually never a good place to define any variables. Why don't you use helper instead? Like this, for example:

def score_class(score)
  score < 60 ? 'red' : 'green'
end


答:
You can use SpecialFolder enum for this purpose:</p>

```<code>Process.Start($@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe");
</code>```

Title: Opening a .exe file from configurable path

Body:
I would like to know how do I open up a program in C#, in any computer, I only get it to start with

Process.Start("C:\Users\\*name*\Desktop\MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe");

But I would like to share the program with my friends, and they don't have the same file directory as me. So how can I do that?

Body:
You can use SpecialFolder enum for this purpose:

Process.Start($@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\MxMV2\MxMV2 EA\EA\bin\Debug\EA.exe");


问:
Flutter how to read only bank transaction sms
I want to read and maintain all bank transaction message and to maintain a bank balance

I am able to read all the bank debited and credited message

my question is that how to find only bank balance string for example

```<code>BOI -  Rs.5900.00 Credited to your Ac XX1552 on 15-12-19 by UPI ref No.934940203877.Avl Bal 6054.43
</code>```

I want to store just Credited  5900.00 and Avl balance 6054.43

答:
Maybe a bit naive, but for your given example, you could use

```<code>\b\d+\.\d+\b
</code>```

See a demo on regex101.com. Otherwise, you'd need to specify more input strings.

Body:
I want to read and maintain all bank transaction message and to maintain a bank balance

I am able to read all the bank debited and credited message

my question is that how to find only bank balance string for example

BOI -  Rs.5900.00 Credited to your Ac XX1552 on 15-12-19 by UPI ref No.934940203877.Avl Bal 6054.43

I want to store just Credited  5900.00 and Avl balance 6054.43

Body:
Maybe a bit naive, but for your given example, you could use

\b\d+\.\d+\b

See a demo on regex101.com. Otherwise, you'd need to specify more input strings.


问:
Leaflet plugin inside react-leaflet
I would like to use Leaflet.VectorGrid plugin and I have a question. Is there an example how to create custom component in react-leaflet?</p>

答:
React-Leaflet aims to provide all the controls and layers provided by Leaflet, but it does not support any Leaflet plugin.

To create a custom components requires the following steps,

1.) Extend an Abstract class provided by React-Leaflet

2.) Implement createLeafletElement (props: Object): Object method to create Leaflet-element. For example,

```<code>createLeafletElement(opts) {
const MapInfo = L.Control.extend({
  onAdd: (map) => {
    this.panelDiv = L.DomUtil.create('div', 'info');
    return this.panelDiv;
  }
});
return new MapInfo({ position: 'bottomleft' });
}
</code>```

3.) Using withLeaflet - Wrap your component. For example,

```<code>export default withLeaflet(MapInfo);
</code>```

This Example will help you - https://codesandbox.io/s/p5zzmnlk8j

Also Please refer to this documentation https://react-leaflet.js.org/docs/en/custom-components.html

Title: Leaflet plugin inside react-leaflet

Body:
React-Leaflet aims to provide all the controls and layers provided by Leaflet, but it does not support any Leaflet plugin.

To create a custom components requires the following steps,

1.) Extend an Abstract class provided by React-Leaflet

2.) Implement createLeafletElement (props: Object): Object method to create Leaflet-element. For example,

createLeafletElement(opts) {
const MapInfo = L.Control.extend({
  onAdd: (map) => {
    this.panelDiv = L.DomUtil.create('div', 'info');
    return this.panelDiv;
  }
});
return new MapInfo({ position: 'bottomleft' });
}

3.) Using withLeaflet - Wrap your component. For example,

export default withLeaflet(MapInfo);

This Example will help you - https://codesandbox.io/s/p5zzmnlk8j

Also Please refer to this documentation https://react-leaflet.js.org/docs/en/custom-components.html


问:
Syntax error help
I seem to have a syntax error and can't see it myself, could someone run over it for me please?

Thanks.

```<code><script>
    var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>
</code>```

答:
David, on the bright side, you don't have a syntax error.

If you're developing PHP, I would recommend two things:

Get a better IDE.  Dreamweaver is TERRIBLE for working with PHP.  I recommend NetBeans (it's awesome and free).

Start breaking up your code into chunks.  The big ball of html and PHP is hard to debug.

Check this out:

```<code><?php
    // prepare output
    $segment  = '?friendship_id=' . $request_data['friendship_id'];
    $segment .= '&friend_id=' . $fromuser['id'] . '";' . "\n";

    $acurl  = 'var acurl_' . $request_data['friendship_id'];
    $acurl .= ' = "sn-include/create_bond_accept.php';
    $acurl .= $segment;

    $dnurl  = 'var dnurl_' . $request_data['friendship_id'];
    $dnurl .= ' = "sn-include/create_bond_deny.php';
    $dnurl .= $segment;
?>
<script type="text/javascript">
    <?php
        echo $acurl;
        echo $dnurl;
    ?>
</script>
</code>```

Title: Syntax error help

Body:
David, on the bright side, you don't have a syntax error.

If you're developing PHP, I would recommend two things:

Get a better IDE.  Dreamweaver is TERRIBLE for working with PHP.  I recommend NetBeans (it's awesome and free).

Start breaking up your code into chunks.  The big ball of html and PHP is hard to debug.

Check this out:

<?php
    // prepare output
    $segment  = '?friendship_id=' . $request_data['friendship_id'];
    $segment .= '&friend_id=' . $fromuser['id'] . '";' . "\n";

    $acurl  = 'var acurl_' . $request_data['friendship_id'];
    $acurl .= ' = "sn-include/create_bond_accept.php';
    $acurl .= $segment;

    $dnurl  = 'var dnurl_' . $request_data['friendship_id'];
    $dnurl .= ' = "sn-include/create_bond_deny.php';
    $dnurl .= $segment;
?>
<script type="text/javascript">
    <?php
        echo $acurl;
        echo $dnurl;
    ?>
</script>


问:
Error when import shapefile on postgis with shp2pgsql (unable to open shapefile)?
I use postgresql 9.1, postgis 2.0.1. For importing the shapefiles to my database, I use shp2pgsql. I have tried many ways for importing theses shapefiles (shp2pgsql -I roads.shp public.roads | psql -d map), but the result is always:

Unable to open roads.shp or roads.SHP.

roads: dbf file (.dbf) can not be opened.

How do I solve this problem?

答: I got the same error, but my case might be different from you. My shp file is located in a folder with the filename consists of symbolic character like Korean, japanese, chinese, etc. After I changed the filename to alphabet my shp file got imported successfully. </p>


问:
How to get client ip from Google Network Load Balancer with kubernetes service
I created a kubernetes service in GKE with type:LoadBalancer.

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: LoadBalancer
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: nginx
```

<p>It's a nginx service and try to get origin client IP. like</p>

```        location / {
            echo $remote_addr;
            echo $http_x_forwarded_for;
        }
```

<p>But the result will get:</p>

```10.140.0.97

```

$remote_addr is like inside kubernetes IP.

$http_x_forwarded_for is empty.

I don't know why this is not like document said.

What I read

https://cloud.google.com/load-balancing/docs/network

Network Load Balancing is a pass-through load balancer, which means that your firewall rules must allow traffic from the client source IP addresses.

https://cloud.google.com/kubernetes-engine/docs/concepts/network-overview#ext-lb

If your Service needs to be reachable from outside the cluster and outside your VPC network, you can configure your Service as a LoadBalancer, by setting the Service's type field to LoadBalancer when defining the Service. GKE then provisions a Network Load Balancer in front of the Service. The Network Load Balancer is aware of all nodes in your cluster and configures your VPC network's firewall rules to allow connections to the Service from outside the VPC network, using the Service's external IP address. You can assign a static external IP address to the Service. Visit Configuring Domain Names with Static IP Addresses for more information.

答:
Because Network Load Balancer handles all incoming traffics and redirect to your GKE cluster. Inside k8s cluster, everything is running under virtual IP network, so you get 10.140.0.97.

The 1st document says you need to setup firewall to accept traffics from client source IP, otherwise by GCP default you are not gonna get any incoming traffic. But 2nd document indicates that GKE will automatically setup for you. All you need to do is find out your external IP and give it a try. You should be able to see your nginx welcome page.

P.S. The default external IP is dynamic, if you want a static IP you can get one via console or gcloud CLI.

Body:
I created a kubernetes service in GKE with type:LoadBalancer.

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  type: LoadBalancer
  ports:
  - name: http
    port: 80
    targetPort: http
  selector:
    app: nginx

It's a nginx service and try to get origin client IP. like

        location / {
            echo $remote_addr;
            echo $http_x_forwarded_for;
        }

But the result will get:

10.140.0.97

$remote_addr is like inside kubernetes IP.

$http_x_forwarded_for is empty.

I don't know why this is not like document said.

What I read

https://cloud.google.com/load-balancing/docs/network

Network Load Balancing is a pass-through load balancer, which means that your firewall rules must allow traffic from the client source IP addresses.

https://cloud.google.com/kubernetes-engine/docs/concepts/network-overview#ext-lb

If your Service needs to be reachable from outside the cluster and outside your VPC network, you can configure your Service as a LoadBalancer, by setting the Service's type field to LoadBalancer when defining the Service. GKE then provisions a Network Load Balancer in front of the Service. The Network Load Balancer is aware of all nodes in your cluster and configures your VPC network's firewall rules to allow connections to the Service from outside the VPC network, using the Service's external IP address. You can assign a static external IP address to the Service. Visit Configuring Domain Names with Static IP Addresses for more information.


问:
Powershell - Continue a script after exiting an application
I'm quite new to Powershell.
To be able to run a certain program I need to disable a device.
This was not to hard, I created the following:

```<code>$DeviceID = (Get-PnpDevice -FriendlyName "*Devicename*").InstanceId
Disable-PnpDevice "$DeviceID" -Confirm:$false
& 'path\file.exe'
</code>```

So far so good. But now I want to Enable the device after I exit the program.
How do I make the script see that I end the program?

答:
Try trapping the result:

```<code>& 'path\file.exe' 2>&1
</code>```

Then test for the exit code which should be held in the environment variable

```<code>$LASTEXITCODE
</code>```

Body:
I'm quite new to Powershell.
To be able to run a certain program I need to disable a device.
This was not to hard, I created the following:

$DeviceID = (Get-PnpDevice -FriendlyName "*Devicename*").InstanceId
Disable-PnpDevice "$DeviceID" -Confirm:$false
& 'path\file.exe'

So far so good. But now I want to Enable the device after I exit the program.
How do I make the script see that I end the program?

Body:
Try trapping the result:

& 'path\file.exe' 2>&1

Then test for the exit code which should be held in the environment variable

$LASTEXITCODE


问:
Is it possible to do a dynamic message translation in angular ngx-translate
I have a dynamic validation message from form controls and the message is from backend configuration.
Is it possible to translate with angular ngx-translate?

```<code><span> {{products.errors?.error | tanslate }} </span>- not works. This error is dynamic erros not able to define in json.
</code>```

likewise for

there is a list of dropdown based on category dynamically from the server. is it possible to translate?

else

is it possible to update the translation en.json,es.json,fr.json files based on server values
eg)
consider usernames,roles ,permissions of logged user needs to be translate

答:
How I see the problem, try to find an api as google translate and send your message and language in which you need to be translated. (fantastic resolution)

https://www.npmjs.com/package/google-translate-api. I never used it, but from examples looks pretty friendly.

```<code>translate('I spea Dutch!', {from: 'en', to: 'nl'}).then(res => {
    console.log(res.text);
    //=> Ik spreek Nederlands!
    console.log(res.from.text.autoCorrected);
    //=> true
    console.log(res.from.text.value);
    //=> I [speak] Dutch!
    console.log(res.from.text.didYouMean);
    //=> false
}).catch(err => {
    console.error(err);
});
</code>```

Realistic, you can map your server errors with numerotations: ERROR_1, ERROR_2, ERROR_3

and in your translate file (which I think is a json):

```<code>{
   ERROR_1: "mesage translated",
   ERROR_2: "another translated message",
   ERROR_3: "etc"
}
</code>```

In client, save your errors in an errors list (string[]) and your html will become:

```<code><span *ngFor="let error of errors">
 {{error | translate}}
</span>
</code>```

Body:
I have a dynamic validation message from form controls and the message is from backend configuration.
Is it possible to translate with angular ngx-translate?

 {{products.errors?.error | tanslate }} - not works. This error is dynamic erros not able to define in json.

likewise for

there is a list of dropdown based on category dynamically from the server. is it possible to translate?

else

is it possible to update the translation en.json,es.json,fr.json files based on server values
eg)
consider usernames,roles ,permissions of logged user needs to be translate

Body:
How I see the problem, try to find an api as google translate and send your message and language in which you need to be translated. (fantastic resolution)

https://www.npmjs.com/package/google-translate-api. I never used it, but from examples looks pretty friendly.

translate('I spea Dutch!', {from: 'en', to: 'nl'}).then(res => {
    console.log(res.text);
    //=> Ik spreek Nederlands!
    console.log(res.from.text.autoCorrected);
    //=> true
    console.log(res.from.text.value);
    //=> I [speak] Dutch!
    console.log(res.from.text.didYouMean);
    //=> false
}).catch(err => {
    console.error(err);
});

Realistic, you can map your server errors with numerotations: ERROR_1, ERROR_2, ERROR_3

and in your translate file (which I think is a json):

{
   ERROR_1: "mesage translated",
   ERROR_2: "another translated message",
   ERROR_3: "etc"
}

In client, save your errors in an errors list (string[]) and your html will become:

<span *ngFor="let error of errors">
 {{error | translate}}
</span>


问:
how does android calculate the res directories
I have read http://developer.android.com/guide/practices/screens_support.html and http://developer.android.com/reference/android/util/DisplayMetrics.html and I somehow left with a gap here.

How is the transition from DisplayMetrics.densityDpi to for example String ("ldpi") done?

And more importantly from DisplayMetrics.widthPixels and DisplayMetrics.widthPixels to for example String ("large")

For the first I can whip up a switch statement easy enough. But the 2nd one is quite more complex. Does anybody know any details? Is there a function which does it?

I even searched the source and did not find anything. But maybe i looked for the wrong thing.

答:
I figured it out, here the correct code (you need a valid android.content.Context instance in attribute context):

```<code>     final android.view.WindowManager windowManager =
        (android.view.WindowManager) this.context
           .getSystemService (android.content.Context.WINDOW_SERVICE);
     final android.util.DisplayMetrics metrics = new android.util.DisplayMetrics ();
     final android.content.res.Resources resources = this.context.getResources ();
     final android.content.res.Configuration config = resources.getConfiguration ();

     windowManager.getDefaultDisplay ().getMetrics (metrics);

     final int density = metrics.densityDpi;
     final int size =
        config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_SIZE_MASK;
     final String densityText;
     final String sizeText;

     switch (density)
     {
        case android.util.DisplayMetrics.DENSITY_LOW:
        {
           densityText = "ldpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_MEDIUM:
        {
           densityText = "mdpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_HIGH:
        {
           densityText = "hdpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_XHIGH:
        {
           densityText = "xhdpi";
           break;
        }
        default:
        {
           densityText = "unknown";
           break;
        }
     } // switch

     switch (size)
     {
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_SMALL:
        {
           sizeText = "small";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_NORMAL:
        {
           sizeText = "normal";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_LARGE:
        {
           sizeText = "large";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_XLARGE:
        {
           sizeText = "xlarge";
           break;
        }
        default:
        {
           sizeText = "unknown";
           break;
        }
     } // switch
</code>```

Body:
I figured it out, here the correct code (you need a valid android.content.Context instance in attribute context):

     final android.view.WindowManager windowManager =
        (android.view.WindowManager) this.context
           .getSystemService (android.content.Context.WINDOW_SERVICE);
     final android.util.DisplayMetrics metrics = new android.util.DisplayMetrics ();
     final android.content.res.Resources resources = this.context.getResources ();
     final android.content.res.Configuration config = resources.getConfiguration ();

     windowManager.getDefaultDisplay ().getMetrics (metrics);

     final int density = metrics.densityDpi;
     final int size =
        config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_SIZE_MASK;
     final String densityText;
     final String sizeText;

     switch (density)
     {
        case android.util.DisplayMetrics.DENSITY_LOW:
        {
           densityText = "ldpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_MEDIUM:
        {
           densityText = "mdpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_HIGH:
        {
           densityText = "hdpi";
           break;
        }
        case android.util.DisplayMetrics.DENSITY_XHIGH:
        {
           densityText = "xhdpi";
           break;
        }
        default:
        {
           densityText = "unknown";
           break;
        }
     } // switch

     switch (size)
     {
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_SMALL:
        {
           sizeText = "small";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_NORMAL:
        {
           sizeText = "normal";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_LARGE:
        {
           sizeText = "large";
           break;
        }
        case android.content.res.Configuration.SCREENLAYOUT_SIZE_XLARGE:
        {
           sizeText = "xlarge";
           break;
        }
        default:
        {
           sizeText = "unknown";
           break;
        }
     } // switch


问:
React input field onKeyPress problem of calling other function
```<code>class A extends React.Component{
   constructor(props){
      this.sendMsg = this.sendMsg.bind(this)
   }

   sendMsg(){
     console.log("Message is send!!!")
   }

keyPressed(event){
    if (event.key === "Enter") {
        this.sendMsg()
    }
}

render(){
   return(
      <input
          type="text"
          className="form-control input-chat border-0"
          id="inputMessage"
          placeholder="Type a new message"
          onKeyPress={this.keyPressed}
      />
   )
}
</code>```

}

Error: this.sendMsg() is undefined.

The above code show a component of input box, if the user click enter, I would like to display a console message. But there have a problem occur as above.
What need to be added to the code to run it properly?

答:
You are not calling the parent contructor in your component, which means you can't use this until after you’ve called the parent constructor.

Add super(props)to your constructor to call the parent constructor.

```<code>constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
}
</code>```

You also need to bind the keyPressed function as this inside keyPressed points to a different thing or use arrow functions instead.

```<code>constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
  this.keyPressed = this.keyPressed.bind(this);
}
</code>```

Using arrow functions

```<code>export default class A extends React.Component {

  sendMsg = () => {
    console.log("Message is send!!!");
  }

  keyPressed = event => {
    if (event.key === "Enter") {
      this.sendMsg();
    }
  };

  render() {
    return (
      <input
        type="text"
        className="form-control input-chat border-0"
        id="inputMessage"
        placeholder="Type a new message"
        onKeyPress={this.keyPressed}
      />
    );
  }
}
</code>```

Body:
class A extends React.Component{
   constructor(props){
      this.sendMsg = this.sendMsg.bind(this)
   }

   sendMsg(){
     console.log("Message is send!!!")
   }

keyPressed(event){
    if (event.key === "Enter") {
        this.sendMsg()
    }
}

render(){
   return(
      <input
          type="text"
          className="form-control input-chat border-0"
          id="inputMessage"
          placeholder="Type a new message"
          onKeyPress={this.keyPressed}
      />
   )
}

}

Error: this.sendMsg() is undefined.

The above code show a component of input box, if the user click enter, I would like to display a console message. But there have a problem occur as above.
What need to be added to the code to run it properly?

Body:
You are not calling the parent contructor in your component, which means you can't use this until after you’ve called the parent constructor.

Add super(props)to your constructor to call the parent constructor.

constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
}

You also need to bind the keyPressed function as this inside keyPressed points to a different thing or use arrow functions instead.

constructor(props) {
  super(props);
  this.sendMsg = this.sendMsg.bind(this);
  this.keyPressed = this.keyPressed.bind(this);
}

Using arrow functions

export default class A extends React.Component {

  sendMsg = () => {
    console.log("Message is send!!!");
  }

  keyPressed = event => {
    if (event.key === "Enter") {
      this.sendMsg();
    }
  };

  render() {
    return (
      <input
        type="text"
        className="form-control input-chat border-0"
        id="inputMessage"
        placeholder="Type a new message"
        onKeyPress={this.keyPressed}
      />
    );
  }
}


问:
How to implement session recording similar to Hotjar, but for mobile apps
For web apps you would simply use MutationObserver to log all DOM changes and then replay them. What are the options for mobile apps?</p>

答:
Well the easiest would be to use some 3rd party tool which is already doing some screen recording & replay.
For example Appsee or smartlook.

Of course you can try to develop your own solution but is quite a long path.

Also pay attention to user consent. There was some issue on Apple store with app removed because they were recording screen. I recommend to use this sdk to manage user consent.