问:
core file memory analysis verification
An application is generating a core file.

Here is the core info.

The error stack was obtained and the objective is to check the data content within the myStruct variable as this is what gets passed into myFunction when the core occurs.

```<code>(gdb) where
#0  0x000000000041bba1 in myFunction (myStruct=0x7ffff9dd0c20) at myTest.c:344
        :
        :
        :
</code>```

From the above I obtained the address of myStruct at 0x7ffff9dd0c20 and dumped out 200 words.

```<code>(gdb) x/200x 0x7ffff9dd0c20
0x7ffff9dd0c20: 0x01938640      0x00000000      0x00001c34      0x000002c8
0x7ffff9dd0c30: 0x00000400      0x00000000      0x01939760      0x00000000
0x7ffff9dd0c40: 0x00000014      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c50: 0x00000000      0x0005000c      0x00000000      0x000d0000
0x7ffff9dd0c60: 0x00000004      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c70: 0x00000000      0x00000000      0x00040000      0x00000000
0x7ffff9dd0c80: 0x0001000c      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c90: 0x00000000      0x00000000      0x00000009      0x00000000
0x7ffff9dd0ca0: 0x00000000      0x00000000      0x410d999a      0x418d999a
0x7ffff9dd0cb0: 0x40b80000      0x41380000      0x000010cc      0x00000000
0x7ffff9dd0cc0: 0x0192edd0      0x00000000      0x00000a30      0x00000158
   :
   :
   :
</code>```

Now I want to verify I am reading the output of the data correctly.

Here is the structure information .

```<code>typedef struct
    {
    char *a;
    unsigned int b;
    unsigned int c;
    int d;
    } structA;

typedef struct
    {
    structA e;
    char *f;
    } myStruct;  <----------This is what gets passed in and what I am trying to examine.
</code>```

Working on Linux, a program was run to verify datatype size.

```<code>Size of char* : 8
Size of int : 4
</code>```

Knowing the address is  0x7ffff9dd0c20 and the structure is myStruct, I assume
I start with analyzing structA since it is first.

Since char *a is the first part of structA and a char * is 2 words do I look at this :

```<code>  0x01938640      0x00000000
</code>```

Next there are essentially 3 ints (2 unsigned int and 1 int) which I viewed as these from the output :

```<code>0x00001c34
0x000002c8
0x00000400
</code>```

This takes me back into structB and to the char *f attribute which should be 2 words.

Does that meaan this this the proper address :

```<code>0x00000000      0x01939760
</code>```

I copied the memory info here again to make it easier to reference.

```<code>(gdb) x/200x 0x7ffff9dd0c20
0x7ffff9dd0c20: 0x01938640      0x00000000      0x00001c34      0x000002c8
0x7ffff9dd0c30: 0x00000400      0x00000000      0x01939760      0x00000000
0x7ffff9dd0c40: 0x00000014      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c50: 0x00000000      0x0005000c      0x00000000      0x000d0000
0x7ffff9dd0c60: 0x00000004      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c70: 0x00000000      0x00000000      0x00040000      0x00000000
0x7ffff9dd0c80: 0x0001000c      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c90: 0x00000000      0x00000000      0x00000009      0x00000000
0x7ffff9dd0ca0: 0x00000000      0x00000000      0x410d999a      0x418d999a
0x7ffff9dd0cb0: 0x40b80000      0x41380000      0x000010cc      0x00000000
0x7ffff9dd0cc0: 0x0192edd0      0x00000000      0x00000a30      0x00000158
</code>```

Is that the proper way to examine and parse out the data?

Here is the definition of one more structure.

```<code>typedef struct
    {
    short w;
    unsigned long x;
    short y;
    short z;
    } otherStruct;
</code>```

This is what is expected to be stored in f.

```<code>    char *f;
</code>```

Within gdb, I tried the following :

```<code> p (otherStruct *)0x1939760
</code>```

and it prints out :

```<code> $12 = (otherStruct *) 0x1939760
</code>```

The strange part is when I originally printed out the data, it showed *f as the following which doesn't look anything like the structure :

```<code>  f = 0x1939760 "\315\314\274@"
</code>```

答:
You're reading the data the hard way.  gdb knows the struct definitions, so you can tell it to print the structure directly using the p command.

For example, given this code using your structs:

```<code>int main()
{
    myStruct s = { { "aaa", 4, 5, 6 }, "bbb" };
    printf("hello\n");
}
</code>```

Running the code under gdb:

(gdb) start
Temporary breakpoint 1 at 0x400535: file x1.c, line 19.
Starting program: /home/dbush/./x1

Temporary breakpoint 1, main () at x1.c:19
19      myStruct s = { { "aaa", 4, 5, 6 }, "bbb" };
Missing separate debuginfos, use: debuginfo-install glibc-2.17-292.el7.x86_64
(gdb) step
20      printf("hello\n");
(gdb) p s
$1 = {e = {a = 0x400600 "aaa", b = 4, c = 5, d = 6}, f = 0x400604 "bbb"}
(gdb)
```

<p>With regard to the field <code>f</code> actually containing a <code>otherStruct *</code>, you can print what this contains by casting <code>f</code> and dereferencing the result:</p>

```p *(otherStruct *)myStruct->f
```

<hr>

<p>That being said, you failed to take into account padding within the structures.    Because <code>structA</code> contains a <code>char *</code> which is 8 bytes in size, the stuct must be aligned on an 8 byte boundary.  Looking at the layout, this means 4 bytes of padding are at the end of the struct.</p>

<p>So the 6th 32-bit word in your dump (0x00000000) is actually that padding.  So the bytes making up <code>f</code> are actually <code>0x01939760      0x00000000</code>.</p>

<p>Looking at the dump of the sample code above:</p>

<pre class="lang-none prettyprint-override"><code>(gdb) p s
$1 = {e = {a = 0x400600 "aaa", b = 4, c = 5, d = 6}, f = 0x400604 "bbb"}
(gdb) p &s
$5 = (myStruct *) 0x7fffffffde50
(gdb) x/20x 0x7fffffffde50
0x7fffffffde50: 0x00400600  0x00000000  0x00000004  0x00000005
0x7fffffffde60: 0x00000006  0x00007fff  0x00400604  0x00000000
0x7fffffffde70: 0x00000000  0x00000000  0xf7a2f505  0x00007fff
0x7fffffffde80: 0x00000000  0x00000000  0xffffdf58  0x00007fff
0x7fffffffde90: 0x00000000  0x00000001  0x0040052d  0x00000000
</code>```

You can see that the values in the fields of e match up with the raw dump.
Next you see the padding bytes which in this case have the value 0x00007fff.  The next 8 bytes after that match the value of f.

Title: core file memory analysis verification

Body:
An application is generating a core file.

Here is the core info.

The error stack was obtained and the objective is to check the data content within the myStruct variable as this is what gets passed into myFunction when the core occurs.

(gdb) where
#0  0x000000000041bba1 in myFunction (myStruct=0x7ffff9dd0c20) at myTest.c:344
        :
        :
        :

From the above I obtained the address of myStruct at 0x7ffff9dd0c20 and dumped out 200 words.

(gdb) x/200x 0x7ffff9dd0c20
0x7ffff9dd0c20: 0x01938640      0x00000000      0x00001c34      0x000002c8
0x7ffff9dd0c30: 0x00000400      0x00000000      0x01939760      0x00000000
0x7ffff9dd0c40: 0x00000014      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c50: 0x00000000      0x0005000c      0x00000000      0x000d0000
0x7ffff9dd0c60: 0x00000004      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c70: 0x00000000      0x00000000      0x00040000      0x00000000
0x7ffff9dd0c80: 0x0001000c      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c90: 0x00000000      0x00000000      0x00000009      0x00000000
0x7ffff9dd0ca0: 0x00000000      0x00000000      0x410d999a      0x418d999a
0x7ffff9dd0cb0: 0x40b80000      0x41380000      0x000010cc      0x00000000
0x7ffff9dd0cc0: 0x0192edd0      0x00000000      0x00000a30      0x00000158
   :
   :
   :

Now I want to verify I am reading the output of the data correctly.

Here is the structure information .

typedef struct
    {
    char *a;
    unsigned int b;
    unsigned int c;
    int d;
    } structA;

typedef struct
    {
    structA e;
    char *f;
    } myStruct;  <----------This is what gets passed in and what I am trying to examine.

Working on Linux, a program was run to verify datatype size.

Size of char* : 8
Size of int : 4

Knowing the address is  0x7ffff9dd0c20 and the structure is myStruct, I assume
I start with analyzing structA since it is first.

Since char *a is the first part of structA and a char * is 2 words do I look at this :

  0x01938640      0x00000000

Next there are essentially 3 ints (2 unsigned int and 1 int) which I viewed as these from the output :

0x00001c34
0x000002c8
0x00000400

This takes me back into structB and to the char *f attribute which should be 2 words.

Does that meaan this this the proper address :

0x00000000      0x01939760

I copied the memory info here again to make it easier to reference.

(gdb) x/200x 0x7ffff9dd0c20
0x7ffff9dd0c20: 0x01938640      0x00000000      0x00001c34      0x000002c8
0x7ffff9dd0c30: 0x00000400      0x00000000      0x01939760      0x00000000
0x7ffff9dd0c40: 0x00000014      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c50: 0x00000000      0x0005000c      0x00000000      0x000d0000
0x7ffff9dd0c60: 0x00000004      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c70: 0x00000000      0x00000000      0x00040000      0x00000000
0x7ffff9dd0c80: 0x0001000c      0x00000000      0x00000000      0x00000000
0x7ffff9dd0c90: 0x00000000      0x00000000      0x00000009      0x00000000
0x7ffff9dd0ca0: 0x00000000      0x00000000      0x410d999a      0x418d999a
0x7ffff9dd0cb0: 0x40b80000      0x41380000      0x000010cc      0x00000000
0x7ffff9dd0cc0: 0x0192edd0      0x00000000      0x00000a30      0x00000158

Is that the proper way to examine and parse out the data?

Here is the definition of one more structure.

typedef struct
    {
    short w;
    unsigned long x;
    short y;
    short z;
    } otherStruct;

This is what is expected to be stored in f.

    char *f;

Within gdb, I tried the following :

 p (otherStruct *)0x1939760

and it prints out :

 $12 = (otherStruct *) 0x1939760

The strange part is when I originally printed out the data, it showed *f as the following which doesn't look anything like the structure :

  f = 0x1939760 "\315\314\274@"

Body:
You're reading the data the hard way.  gdb knows the struct definitions, so you can tell it to print the structure directly using the p command.

For example, given this code using your structs:

int main()
{
    myStruct s = { { "aaa", 4, 5, 6 }, "bbb" };
    printf("hello\n");
}

Running the code under gdb:

(gdb) start
Temporary breakpoint 1 at 0x400535: file x1.c, line 19.
Starting program: /home/dbush/./x1

Temporary breakpoint 1, main () at x1.c:19
19      myStruct s = { { "aaa", 4, 5, 6 }, "bbb" };
Missing separate debuginfos, use: debuginfo-install glibc-2.17-292.el7.x86_64
(gdb) step
20      printf("hello\n");
(gdb) p s
$1 = {e = {a = 0x400600 "aaa", b = 4, c = 5, d = 6}, f = 0x400604 "bbb"}
(gdb)

With regard to the field f actually containing a otherStruct *, you can print what this contains by casting f and dereferencing the result:

p *(otherStruct *)myStruct->f

That being said, you failed to take into account padding within the structures.    Because structA contains a char * which is 8 bytes in size, the stuct must be aligned on an 8 byte boundary.  Looking at the layout, this means 4 bytes of padding are at the end of the struct.

So the 6th 32-bit word in your dump (0x00000000) is actually that padding.  So the bytes making up f are actually 0x01939760      0x00000000.

Looking at the dump of the sample code above:

(gdb) p s
$1 = {e = {a = 0x400600 "aaa", b = 4, c = 5, d = 6}, f = 0x400604 "bbb"}
(gdb) p &s
$5 = (myStruct *) 0x7fffffffde50
(gdb) x/20x 0x7fffffffde50
0x7fffffffde50: 0x00400600  0x00000000  0x00000004  0x00000005
0x7fffffffde60: 0x00000006  0x00007fff  0x00400604  0x00000000
0x7fffffffde70: 0x00000000  0x00000000  0xf7a2f505  0x00007fff
0x7fffffffde80: 0x00000000  0x00000000  0xffffdf58  0x00007fff
0x7fffffffde90: 0x00000000  0x00000001  0x0040052d  0x00000000

You can see that the values in the fields of e match up with the raw dump.
Next you see the padding bytes which in this case have the value 0x00007fff.  The next 8 bytes after that match the value of f.


来源: stackexchange

问:
Julia - dataframe - How to use string for custom output column naming in by()
I am getting familiar with Julia Dataframes module.
One thing that I haven't found a way yet to do is how to assign programmatically a custom column name of the result of a by() operation.

So for example I have no problem doing the following :

```<code>df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100))
by(df, :grp,result=(:x, :z)=>((x, y),) -> cov(x, y))
</code>```

Giving the following dataframe

```<code>2×2 DataFrame
│ Row │ grp    │ result      │
│     │ String │ Float64     │
├─────┼────────┼─────────────┤
│ 1   │ b      │ -0.00622699 │
│ 2   │ a      │ -0.0303828  │
</code>```

Now I would like the naming of the result to be dependent on some other part of my code. So i am trying things along this

```<code>resultColName="resultBis"
by(df, :grp,resultColName=(:x, :z)=>((x, y),) -> cov(x, y))
</code>```

which gives me the following

```<code>2×2 DataFrame
│ Row │ grp    │ resultColName │
│     │ String │ Float64       │
├─────┼────────┼───────────────┤
│ 1   │ b      │ -0.00622699   │
│ 2   │ a      │ -0.0303828    │
</code>```

Which doesn't work as I want the result column to be named 'resultBis'. I understand why this happens, but is there currently a way to provide a string to chose the custom name of the result column ?

I imagine using macro could be one way to handle that and I would welcome that as an answer, but ideally I would like to do it directly within the DataFrames.jl. Any help is welcome. Thanks

答:
```<code>julia> by(df, :grp, (; Symbol(resultColName)=>(:x, :z)=>((x, y),) -> cov(x, y)))
2×2 DataFrame
│ Row │ grp    │ resultBis  │
│     │ String │ Float64    │
├─────┼────────┼────────────┤
│ 1   │ a      │ -0.0110717 │
│ 2   │ b      │ 0.0102181  │
</code>```

Explanation:

by accepts a NamedTuple as the third parameter.
In order to create it programmatically we use the (; :key => value) operator. For more information type ?NamedTuple into the Julia console.

ContentLicense: CC BY-SA 4.0

Body:
I am getting familiar with Julia Dataframes module.
One thing that I haven't found a way yet to do is how to assign programmatically a custom column name of the result of a by() operation.

So for example I have no problem doing the following :

df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100))
by(df, :grp,result=(:x, :z)=>((x, y),) -> cov(x, y))

Giving the following dataframe

2×2 DataFrame
│ Row │ grp    │ result      │
│     │ String │ Float64     │
├─────┼────────┼─────────────┤
│ 1   │ b      │ -0.00622699 │
│ 2   │ a      │ -0.0303828  │

Now I would like the naming of the result to be dependent on some other part of my code. So i am trying things along this

resultColName="resultBis"
by(df, :grp,resultColName=(:x, :z)=>((x, y),) -> cov(x, y))

which gives me the following

2×2 DataFrame
│ Row │ grp    │ resultColName │
│     │ String │ Float64       │
├─────┼────────┼───────────────┤
│ 1   │ b      │ -0.00622699   │
│ 2   │ a      │ -0.0303828    │

Which doesn't work as I want the result column to be named 'resultBis'. I understand why this happens, but is there currently a way to provide a string to chose the custom name of the result column ?

I imagine using macro could be one way to handle that and I would welcome that as an answer, but ideally I would like to do it directly within the DataFrames.jl. Any help is welcome. Thanks

Body:
julia> by(df, :grp, (; Symbol(resultColName)=>(:x, :z)=>((x, y),) -> cov(x, y)))
2×2 DataFrame
│ Row │ grp    │ resultBis  │
│     │ String │ Float64    │
├─────┼────────┼────────────┤
│ 1   │ a      │ -0.0110717 │
│ 2   │ b      │ 0.0102181  │

Explanation:

by accepts a NamedTuple as the third parameter.
In order to create it programmatically we use the (; :key => value) operator. For more information type ?NamedTuple into the Julia console.


问:
Nested Query count ID if they're related
I've got a project where I need to get the total number of directors and films.

It should be 6 directors and 12 films in total.

However, I have 8 directors and 12 films.

```<code>CREATE TABLE `director` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
 );

INSERT INTO `director` VALUES
(1,'Roman Polanski'),
(2,'George Lucas'),
(3,'Steven Spielberg'),
(4,'Sam Mendes'),
(5,'Sofia Coppola'),
(6,'Michael Bay'),
(7,'Justin Lin'),
(8,'Francis Coppola');

CREATE TABLE `film` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`director_id` int(11) NOT NULL,
 PRIMARY KEY (`id`)
 );

INSERT INTO `film` VALUES
(1,'Saw',7),
(2,'Jaw',3),
(3,'The Pianist',1),
(4,'1917',4),
(5,'Fast and Furious',7),
(6,'Star Wars',2),
(7,'ET',3),
(8,'James bond',4),
(9,'Lost in Translation',5),
(10,'Close Encounter of the Third Kind',3),
(11,'Blood',4),
(12,'Somewhere',5);
</code>```

And this is the query I used:

```<code>SELECT  (
        SELECT COUNT(*)
        FROM   director
        ) AS directors,
        (
        SELECT COUNT(*)
        FROM   film
        ) AS films
FROM    dual
</code>```

I'm wondering if there's a way to count the director id only if it's related to the film's id?

答:
Just count the distinct director IDs in the film table:

```<code>select
  count(*) as films,
  count(distinct director_id) as directors
from film
</code>```

There is no need to touch the director table at all. But as an exercise you could do the following:

```<code>select count(*) as directors
from director d
where exists (
  select *
  from film f
  where f.director_id = d.id
)
</code>```

Which will count directors who have ever directed a film.

See demo on db-fiddle.com

Body:
I've got a project where I need to get the total number of directors and films.

It should be 6 directors and 12 films in total.

However, I have 8 directors and 12 films.

CREATE TABLE `director` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
 );

INSERT INTO `director` VALUES
(1,'Roman Polanski'),
(2,'George Lucas'),
(3,'Steven Spielberg'),
(4,'Sam Mendes'),
(5,'Sofia Coppola'),
(6,'Michael Bay'),
(7,'Justin Lin'),
(8,'Francis Coppola');

CREATE TABLE `film` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`director_id` int(11) NOT NULL,
 PRIMARY KEY (`id`)
 );

INSERT INTO `film` VALUES
(1,'Saw',7),
(2,'Jaw',3),
(3,'The Pianist',1),
(4,'1917',4),
(5,'Fast and Furious',7),
(6,'Star Wars',2),
(7,'ET',3),
(8,'James bond',4),
(9,'Lost in Translation',5),
(10,'Close Encounter of the Third Kind',3),
(11,'Blood',4),
(12,'Somewhere',5);

And this is the query I used:

SELECT  (
        SELECT COUNT(*)
        FROM   director
        ) AS directors,
        (
        SELECT COUNT(*)
        FROM   film
        ) AS films
FROM    dual

I'm wondering if there's a way to count the director id only if it's related to the film's id?

Body:
Just count the distinct director IDs in the film table:

select
  count(*) as films,
  count(distinct director_id) as directors
from film

There is no need to touch the director table at all. But as an exercise you could do the following:

select count(*) as directors
from director d
where exists (
  select *
  from film f
  where f.director_id = d.id
)

Which will count directors who have ever directed a film.

See demo on db-fiddle.com


问:
java transform projection EPSG:900913 to EPSG:4326
in the openlayers
we can simple transform EPSG:900913 to EPSG:4326

I'm look for a java lib can do that.

here I found this,
http://www.jhlabs.com/java/maps/proj/index.html

but the document is in c++

 I don't know how to use it.

If anyone konw that,

please post a simple code

答:
Geotools is probably the best library to use for this.  Taking a look at their CRS tutorial, it looks trivial to transform from one coordinate system to another using:

```<code>CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem worldCRS = map.getCoordinateReferenceSystem();
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);
</code>```

Your CRS references can be retrieved using:

```<code>CRS.decode("EPSG:4326")
</code>```

Per the javadoc.

ContentLicense: CC BY-SA 2.5

Body:
Geotools is probably the best library to use for this.  Taking a look at their CRS tutorial, it looks trivial to transform from one coordinate system to another using:

CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem worldCRS = map.getCoordinateReferenceSystem();
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);

Your CRS references can be retrieved using:

CRS.decode("EPSG:4326")

Per the javadoc.

ContentLicense: CC BY-SA 3.0


问:
Display a Bitmap in OpenGL
I am trying to display a bitmap image to an OpenGL control called GL (I am using SharpGL as the wrapper). In practice, a text string is written to a GDI+ Picture box from which the Bitmap is obtained.
The GLBitmap function requires a Byte() array as input; I convert the Bitmap to a Byte() array. Does not seem to work as I get a bunch of dots on screen. I have also saved the PictureBox image to a Bmp file on disk and cross-checked that it had the desired content. So, the Bmp image does not appear to be the issue here.

Actual OpenGL display

Bmp file created from the code below

Wondering what I am doing wrong. Anybody would have a suggestion ? Thanks in advance.

The VB.Net code appears below.

' Create Bitmap & Graphics context for string
'
' iWidth and iHeight are the dimensions of the bitmap;
' they are a power of 2.
Dim SharpBMap As Bitmap = New Bitmap(iWidth, iHeight)
Dim SharpGraf As Graphics = Graphics.FromImage(SharpBMap)

' Draw text string to SharpGraf PictureBox
'
SharpGraf.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
SharpGraf.Clear(Color.White)
SharpGraf.DrawString(TxtStr, CurrFont, CurrBrush, 0, 0, CurrFormat)

' OutSharpGL is the Picture box to which the text string is sent
OutSharpGL.Image = SharpBMap

' Save the bitmap to disk: when the file is viewed, the image is Ok.
SharpBMap.Save(FilNameStr)

' Set the color
Gl.Color(1.0f, 1.0f, 1.0f)

' Set the Raster position
Gl.RasterPos(0, 0)

' Transfer the Bitmap
Gl.Bitmap(iWidth, iHeight, 0.0f, 0.0f, 0.0f, 0.0f, BitmapToByte(SharpBMap))

' Function to convert a Bitmap to a Byte() array
Friend Function BitmapToByte(ByRef Bmp As Bitmap) As Byte()

    Dim converter As New ImageConverter()

    Return DirectCast(converter.ConvertTo(Bmp, GetType(Byte())), Byte())
End Function
```

答:
OpenGL requires raw pixel data ... BMP has encoding ...

In order to make this work you need to extract the raw pixel data from your BMP. That might be a bit too much to do correctly as there are a lot of format configurations out there ...

So make sure you change your bitmap to format that is easily handled like:

uncompressed

24 or 32 bpp

Now bitmap has a BMP header at its start describing the file is BMP and stuff like resolution, encoding, organization etc ... The header also usually holds the start address of the pixels... So extract that and pass the RAW pixels to your GL texture...

Beware BMP pixels are aligned on ScanLine basis so each line of image has some gap BYTE to align to certain multiple of size (usually 1..4 Bytes) you need to skip it and then process another line. Here related QA (but solved easily by VCL which is not your case)

How to get a pixel array from TBitmap?

However you need to do this on your own so you need:

dive into BMP fileformat

obtain resolution and pixel data start address from the header

construct your raw pixel data by copying the lines into yours memory array

skipping header and the align bytes

pass that as OpenGL texture

its faster to pass whole image than do it on per line basis. Beware you need to set the pixel format so it matches your raw data copied from bmp. So bpp must match and also the R,G,B order.

render textured quad

btw. much easier would be to print the texts directly in OpenGl. There are libs for that like FreeType but you can use textures instead like this:

GLSL debug prints

Of coarse CPU side GL text rendering using such texture is much easier than in GLSL. You just handle the texture as Texture Atlas where the Texture coordinates are computed from ASCII code and Texture font organisation.

Title: Display a Bitmap in OpenGL


问:
RatingBar with pink background when holding
My RatingBar is pretty regular, when selected appears like this

But when touching (and holding) them, all unrated stars are pink, like this

Why does this happen?

The xml:

```<code><RatingBar
    android:id="@+id/ratingBarSchedulesRatingTour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:numStars="5"
    android:progressTint="@color/yellow_star"
    android:secondaryProgressTint="@color/yellow_star"
    android:stepSize="1" />
</code>```

@color/yellow_star is on colors.xml as #F1CD1E

答:
Create Style and color what you want (press/normal)</p>

```<code><style name="RatingBar" parent="Theme.AppCompat">
        <item name="colorControlNormal">#F1CD1E</item>
        <item name="colorControlActivated">#F1CD1E</item>
    </style>

<RatingBar
        android:id="@+id/ratingBarSchedulesRatingTour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:numStars="5"
        android:progressTint="#F1CD1E"
        android:theme="@style/RatingBar"
        android:secondaryProgressTint="#F1CD1E"
        android:stepSize="1" />
</code>```

Body:
My RatingBar is pretty regular, when selected appears like this

But when touching (and holding) them, all unrated stars are pink, like this

Why does this happen?

The xml:

<RatingBar
    android:id="@+id/ratingBarSchedulesRatingTour"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:numStars="5"
    android:progressTint="@color/yellow_star"
    android:secondaryProgressTint="@color/yellow_star"
    android:stepSize="1" />

@color/yellow_star is on colors.xml as #F1CD1E

Body:
Create Style and color what you want (press/normal)

<style name="RatingBar" parent="Theme.AppCompat">
        <item name="colorControlNormal">#F1CD1E</item>
        <item name="colorControlActivated">#F1CD1E</item>
    </style>

<RatingBar
        android:id="@+id/ratingBarSchedulesRatingTour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:numStars="5"
        android:progressTint="#F1CD1E"
        android:theme="@style/RatingBar"
        android:secondaryProgressTint="#F1CD1E"
        android:stepSize="1" />


问:
casting 'findViewByld(...)' to 'EditText' is redundant
In the line txtPass=(EditText) findViewById(R.id.txtPass); it says casting 'findViewByld(...)' to 'EditText' is redundant. How do I fix this?

```<code>
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class datainsert extends AppCompatActivity {
EditText txtPass, txtName, txtNum, txtEmail;
Button btnLogin, btnSignUp;
DatabaseReference reff;
Member member;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        txtPass=(EditText) findViewById(R.id.txtPass);
        txtName=(EditText)findViewById(R.id.txtName);
        txtNum=(EditText)findViewById(R.id.txtNum);
        txtEmail=(EditText)findViewById(R.id.txtEmail);
        btnLogin=(Button)findViewById(R.id.btnLogin);
        btnSignUp=(Button)findViewById(R.id.btnSignUp);
        reff= FirebaseDatabase.getInstance().getReference().child("Member");
        member=new Member();
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Float agea=Float.parseFloat(txtPass.getText().toString().trim());
                Float hit= Float.parseFloat(txtName.getText().toString().trim());
                Float dsa= Float.parseFloat(txtEmail.getText().toString().trim());
                Long phn=Long.parseLong(txtNum.getText().toString().trim());

                member.setName(txtName.getText().toString().trim());
                member.setEmail(txtEmail.getText().toString().trim());
                member.setHt(dsa);
                member.setHm(hit);
                member.setPh(phn);
                member.setHt(agea);
                reff.push().setValue(member);
                Toast.makeText(datainsert.this,"data inserted sucessfully",Toast.LENGTH_LONG).show();
            }
            });
    }
}```
```

答:
Replace these lines

```<code>    txtPass=(EditText) findViewById(R.id.txtPass);
    txtName=(EditText)findViewById(R.id.txtName);
    txtNum=(EditText)findViewById(R.id.txtNum);
    txtEmail=(EditText)findViewById(R.id.txtEmail);
</code>```

with these

```<code>    txtPass=findViewById(R.id.txtPass);
    txtName=findViewById(R.id.txtName);
    txtNum=findViewById(R.id.txtNum);
    txtEmail=findViewById(R.id.txtEmail);
</code>```

Both the View Type and actual view are same i.e EditText so typecasting is not required in this case you can directly assign the values

To more know about TypeCasting Check this
Why do we always type cast in Android/Java?

Body:
In the line txtPass=(EditText) findViewById(R.id.txtPass); it says casting 'findViewByld(...)' to 'EditText' is redundant. How do I fix this?

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class datainsert extends AppCompatActivity {
EditText txtPass, txtName, txtNum, txtEmail;
Button btnLogin, btnSignUp;
DatabaseReference reff;
Member member;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        txtPass=(EditText) findViewById(R.id.txtPass);
        txtName=(EditText)findViewById(R.id.txtName);
        txtNum=(EditText)findViewById(R.id.txtNum);
        txtEmail=(EditText)findViewById(R.id.txtEmail);
        btnLogin=(Button)findViewById(R.id.btnLogin);
        btnSignUp=(Button)findViewById(R.id.btnSignUp);
        reff= FirebaseDatabase.getInstance().getReference().child("Member");
        member=new Member();
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Float agea=Float.parseFloat(txtPass.getText().toString().trim());
                Float hit= Float.parseFloat(txtName.getText().toString().trim());
                Float dsa= Float.parseFloat(txtEmail.getText().toString().trim());
                Long phn=Long.parseLong(txtNum.getText().toString().trim());

                member.setName(txtName.getText().toString().trim());
                member.setEmail(txtEmail.getText().toString().trim());
                member.setHt(dsa);
                member.setHm(hit);
                member.setPh(phn);
                member.setHt(agea);
                reff.push().setValue(member);
                Toast.makeText(datainsert.this,"data inserted sucessfully",Toast.LENGTH_LONG).show();
            }
            });
    }
}```

Body:
Replace these lines

    txtPass=(EditText) findViewById(R.id.txtPass);
    txtName=(EditText)findViewById(R.id.txtName);
    txtNum=(EditText)findViewById(R.id.txtNum);
    txtEmail=(EditText)findViewById(R.id.txtEmail);

with these

    txtPass=findViewById(R.id.txtPass);
    txtName=findViewById(R.id.txtName);
    txtNum=findViewById(R.id.txtNum);
    txtEmail=findViewById(R.id.txtEmail);

Both the View Type and actual view are same i.e EditText so typecasting is not required in this case you can directly assign the values

To more know about TypeCasting Check this
Why do we always type cast in Android/Java?


问:
How change range slider to show money?
I found this slider on codepen .

How do I get it to show me a minimum of € 500 and a maximum of € 6000 but to preserve the red background?

I have tried everything eg.

```<code><input id = "range" type = "range" class = "range-slider" min = "500" max = "6000" step = "100">
</code>```

But the range slider stretches to 6000% and I'm not good at JS.

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}

function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  rangeValue.innerHTML = `${rangeSlider.value}€`;
}

rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  width: 25px;
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}</code>```

  <input id="range" type="range" class="range-slider">

  0

```

答:
you can set the limits min & max to any other value in this code its 500 & 6000

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}
function rangeValueHandler() {
  min=500;  max=6000;
  rangeValueBar.style.setProperty('width',`${rangeSlider.value}%`);
  value = Math.round(min + (max-min) * (rangeSlider.value/100));
  rangeValue.innerHTML = `${value}€`;
}
rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform0: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}</code>```

  <input id="range" type="range" class="range-slider">

  0

```

Title: How change range slider to show money?

Body:
I found this slider on codepen .

How do I get it to show me a minimum of € 500 and a maximum of € 6000 but to preserve the red background?

I have tried everything eg.

<input id = "range" type = "range" class = "range-slider" min = "500" max = "6000" step = "100">

But the range slider stretches to 6000% and I'm not good at JS.

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}

function rangeValueHandler() {
  rangeValueBar.style.setProperty('width', `${rangeSlider.value}%`);
  rangeValue.innerHTML = `${rangeSlider.value}€`;
}

rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);

body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  width: 25px;
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}

  <input id="range" type="range" class="range-slider">

  0

Body:
you can set the limits min & max to any other value in this code its 500 & 6000

const rangeSlider = document.querySelector('.range-slider');
const rangeValueBar = document.querySelector('#range-value-bar');
const rangeValue = document.querySelector('#range-value');

let isDown = false;

function dragHandler() {
  isDown = !isDown;
  if (!isDown) {
    rangeValue.style.setProperty('opacity', '1');
  } else {
    rangeValue.style.setProperty('opacity', '1');
  }
}

function dragOn(e) {
  if (!isDown) return;
  rangeValueHandler();
}
function rangeValueHandler() {
  min=500;  max=6000;
  rangeValueBar.style.setProperty('width',`${rangeSlider.value}%`);
  value = Math.round(min + (max-min) * (rangeSlider.value/100));
  rangeValue.innerHTML = `${value}€`;
}
rangeValueHandler();
rangeSlider.addEventListener('mousedown', dragHandler);
rangeSlider.addEventListener('mousemove', dragOn);
rangeSlider.addEventListener('mouseup', dragHandler);
rangeSlider.addEventListener('click', rangeValueHandler);

body {
  padding: 100px;
}
.range-slider-container {
  position: relative;
}

input[type=range] {
  -webkit-appearance: none;
  margin: 10px 0;
  width: 100%;
  position: absolute;
  top: 0;
  margin: 0;
}
#range-value-bar {
  width: 100%;
  content: "0";
  background-color: #FC6E50;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: 0;
  margin: 0;
  border-radius: 5px;
}
/**/
#range-value {
  content:"0";
  background: rgba(233, 239, 244, 0.1);;
  position: absolute;
  z-index: 10000;
  height: 25px;
  top: -65px;
  margin: 0;
  border-radius: 5px;
  left: 50%;
  transform0: translateX(-50%);
  font-size: 20px;
  padding: 12px;
  color: #41576B;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  text-align: center;
  opacity: 0;
}

input[type=range]:focus {
  outline: none;
}
input[type=range]::-webkit-slider-runnable-track {
  width: 100%;
  height: 25px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #E9EFF4;
  border-radius: 5px;
  border: 0px solid #000101;
}
input[type=range]::-webkit-slider-thumb {
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
  border: 14px solid #FFF;
  height: 53px;
  width: 53px;
  border-radius: 30px;
  background: #FC6E50;
  cursor: pointer;
  -webkit-appearance: none;
  margin-top: -13.5px;
  position: relative;
  z-index: 1000000000;
}
input[type=range]::-moz-range-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  background: #000;
  border-radius: 25px;
  border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000000;
  cursor: pointer;
}
input[type=range]::-ms-track {
  width: 100%;
  height: 12.8px;
  cursor: pointer;
  animate: 0.2s;
  background: transparent;
  border-color: transparent;
  border-width: 39px 0;
  color: transparent;
}
input[type=range]::-ms-fill-lower {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
  background: #000;
  border: 0px solid #000101;
  border-radius: 50px;
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
  box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
  border: 0px solid #000000;
  height: 20px;
  width: 39px;
  border-radius: 7px;
  background: #000;
  cursor: pointer;
}

<div class="range-slider-container">
  <input id="range" type="range" class="range-slider">
  <span id="range-value-bar"></span>
  <span id="range-value">0</span>
</div>


问:
confusion related to implicit contructors and constructor chaining
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

```<code>class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}
</code>```

答:
The default/implicit constructor is there only if there is no other constructor.

By adding

```<code>public Parent(int a) {
    System.out.println(a);
}
</code>```

you remove the default constructor of Parent.

If you want to keep the default constructor, you can write it yourself like this:

```<code>public Parent(){
}
</code>```

The following constructor

```<code>public Child(){

}
</code>```

will be automatically replaced to

```<code>public Child(){
    super();
}
</code>```

This replacement will happen if there is no constructor call(this() or super()) in the first line.

This secures that a super constructor is called in any case.

The replacement will fail if there is no constructor without arguments in the super-class (if you have replaced the default constructor with a parameterized constructor).

Body:
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}

Body:
The default/implicit constructor is there only if there is no other constructor.

By adding

public Parent(int a) {
    System.out.println(a);
}

you remove the default constructor of Parent.

If you want to keep the default constructor, you can write it yourself like this:

public Parent(){
}

The following constructor

public Child(){

}

will be automatically replaced to

public Child(){
    super();
}

This replacement will happen if there is no constructor call(this() or super()) in the first line.

This secures that a super constructor is called in any case.

The replacement will fail if there is no constructor without arguments in the super-class (if you have replaced the default constructor with a parameterized constructor).


问:
JIRA id validation in git commit message
I am using below Regex pattern on Bitbucket application to validate Jira id in commit message

```<code>[A-Z][A-Z_0-9]+-[0-9]
</code>```

Sample commit message:

CLB-181 CLB-168 CLB-84::**** testing 3  jira id CRE-507 validation

Need to validate Jira id(s) before :: , i.e. CLB-181 CLB-168 CLB-84:: but not after ::** Testing 3  jira id CRE-507 validation.

答:
The place many people get hung up in these problems is that they try to match against the entire string. Change the problem so it's easier to solve. In this case, do your steps backward.

Break up the commit message so you have just the portion that you are interested in. Keeping the first element from splitting on :: is one way to do it:

```<code>my( $preamble ) = split /::/, $commit_message;
</code>```

Now that you have the first part of the commit message, get the Jira IDs. Matching groups of non-whitespace in list context returns all the matches:

```<code>my @jira_ids = $preamble =~ m/(\S+)/g;
</code>```

Now validate whatever is in @jira_ids.

There are many other ways to do the same thing, so choose one that is simple and maps onto how you and those around you think about the problem (adjusting for problem redefinition :)

Body:
I am using below Regex pattern on Bitbucket application to validate Jira id in commit message

[A-Z][A-Z_0-9]+-[0-9]

Sample commit message:

CLB-181 CLB-168 CLB-84::**** testing 3  jira id CRE-507 validation

Need to validate Jira id(s) before :: , i.e. CLB-181 CLB-168 CLB-84:: but not after ::** Testing 3  jira id CRE-507 validation.

Body:
The place many people get hung up in these problems is that they try to match against the entire string. Change the problem so it's easier to solve. In this case, do your steps backward.

Break up the commit message so you have just the portion that you are interested in. Keeping the first element from splitting on :: is one way to do it:

my( $preamble ) = split /::/, $commit_message;

Now that you have the first part of the commit message, get the Jira IDs. Matching groups of non-whitespace in list context returns all the matches:

my @jira_ids = $preamble =~ m/(\S+)/g;

Now validate whatever is in @jira_ids.

There are many other ways to do the same thing, so choose one that is simple and maps onto how you and those around you think about the problem (adjusting for problem redefinition :)


问:
Why does `react-native run-ios` show "No bundle URL present" until I reset it?
With my React Native app, when I run react-native run-ios, it shows this screen:

When I press cmd-R to reload, it goes away. This happens most, but not all of the time. It's not just with a particular project; when I create a new project from scratch, it's the same.

I'm sure this could happen for a variety of reasons, and I'd need to give more info to narrow it down, but does anyone know how I could approach figuring out why this happens?

答: It happens because your simulator opening the app faster than metro bundler server. In my case, it's often happened when I stop the metro bundler server and still have simulator running my applications and there is a warning message that saying metro bundler is not connected. Either way, as long as reloading the app still working, that means there is nothing wrong with your react-native configuration.</p>


问:
TypeError: expected string when using re.findall on web page text -- why?
I'm trying to learn how to screen-scrape with BeautifulSoup.

```<code>from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()

patFinderTitle = re.compile('<h4 class="itemtitle"><a href=(.*)</a></h4>')

findPatTitle = re.findall(patFinderTitle,webpage)
listIterator = []
listIterator[:] = range(1, 5)

for i in listIterator:
    print findPatTitle[i]
    print("\n")
</code>```

Error

```<code>Traceback (most recent call last):
File "//da-srv1/users/xxxxx/Desktop/fetcher", line 14, in <module>
print findPatTitle[i]
**IndexError: list index out of range**
</code>```

答:
You left out the parenthesis on the read() function call, so webpage was a function and not a string. </p>

```<code>webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()
</code>```

Body:
I'm trying to learn how to screen-scrape with BeautifulSoup.

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re

webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()

patFinderTitle = re.compile('
<a href=(.*)
')

findPatTitle = re.findall(patFinderTitle,webpage)
listIterator = []
listIterator[:] = range(1, 5)

for i in listIterator:
    print findPatTitle[i]
    print("\n")

Error

Traceback (most recent call last):
File "//da-srv1/users/xxxxx/Desktop/fetcher", line 14, in <module>
print findPatTitle[i]
**IndexError: list index out of range**

Body:
You left out the parenthesis on the read() function call, so webpage was a function and not a string.

webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()


问:
Rotate array (list) in linear time and constant memory
How can I be sure that this Python algorithm uses constant memory?  A theoretical proof is OK.

A textbook* has this exercise: write an algorithm to "rotate" a list of n integers, in other words to shift the list values by k indices each.  The catch is that the algorithm should take linear time (proportional to n) and constant memory (the same amount for any n).  The rotation can be done with slicing:

```<code>>>> n = 5
>>> k = 3
>>> a = [i for i in range(n)]
>>> a = a[k:] + a[:k]
>>> a
[3, 4, 0, 1, 2]
</code>```

I've verified that doubling n doubles the time taken, and so this algorithm takes linear time.  However, I'm not sure it takes constant memory.  I assume Python creates a new array that is the concatenation of the two slices, and then reassigns variable a to that array.  If so, then I think the memory used is proportional to n.  But how can I verify that?

The exercise also gives a hint that is cryptic to me: "Hint: Reverse three subarrays."  Why would there be a need to create three subarrays, and why reverse them?  Is that the trick to using constant memory?  I get that you could reverse the order of elements 0 through k-1, reverse the order of elements k through n-1, then reverse the order of all elements, but that seems like more operations, not less.

*The book is Introduction to Programming in Python, by Sedgewick, Wayne, and Dondero.  I'm teaching myself, not taking a course for credit.

答:
Rather than performing swaps, you could carry a single element around and shift it into the next position:

```<code>def rotate(array,offset): # positive offset rotates left to right
    if not array or not offset: return
    index,value = 0,array[0]
    for _ in array:
        index = (index+offset)%len(array)
        value,array[index] = array[index],value

A = [1,2,3,4,5,6,7]
rotate(A,3)
print(A)

# [5, 6, 7, 1, 2, 3, 4]
</code>```

Because of Python's ability to use negatives to index from the end of the array, the function will also work to rotate right to left by giving it a negative offset:

```<code>A = [1,2,3,4,5,6,7]
rotate(A,-3)
print(A)

# [4, 5, 6, 7, 1, 2, 3]
</code>```

Body:
How can I be sure that this Python algorithm uses constant memory?  A theoretical proof is OK.

A textbook* has this exercise: write an algorithm to "rotate" a list of n integers, in other words to shift the list values by k indices each.  The catch is that the algorithm should take linear time (proportional to n) and constant memory (the same amount for any n).  The rotation can be done with slicing:

>>> n = 5
>>> k = 3
>>> a = [i for i in range(n)]
>>> a = a[k:] + a[:k]
>>> a
[3, 4, 0, 1, 2]

I've verified that doubling n doubles the time taken, and so this algorithm takes linear time.  However, I'm not sure it takes constant memory.  I assume Python creates a new array that is the concatenation of the two slices, and then reassigns variable a to that array.  If so, then I think the memory used is proportional to n.  But how can I verify that?

The exercise also gives a hint that is cryptic to me: "Hint: Reverse three subarrays."  Why would there be a need to create three subarrays, and why reverse them?  Is that the trick to using constant memory?  I get that you could reverse the order of elements 0 through k-1, reverse the order of elements k through n-1, then reverse the order of all elements, but that seems like more operations, not less.

*The book is Introduction to Programming in Python, by Sedgewick, Wayne, and Dondero.  I'm teaching myself, not taking a course for credit.

Body:
Rather than performing swaps, you could carry a single element around and shift it into the next position:

def rotate(array,offset): # positive offset rotates left to right
    if not array or not offset: return
    index,value = 0,array[0]
    for _ in array:
        index = (index+offset)%len(array)
        value,array[index] = array[index],value

A = [1,2,3,4,5,6,7]
rotate(A,3)
print(A)

# [5, 6, 7, 1, 2, 3, 4]

Because of Python's ability to use negatives to index from the end of the array, the function will also work to rotate right to left by giving it a negative offset:

A = [1,2,3,4,5,6,7]
rotate(A,-3)
print(A)

# [4, 5, 6, 7, 1, 2, 3]


问:
C++: Items of std::map are deallocated when temporary std::map goes out of scope
I am a C++ non-user and I am just trying something for fun and I've got stuck and I suppose, I am doing something wrong.

I have a std::map of my own classes (std::map<MyClass*, MyClass*>) and I am trying to filter out a subset, store it as a temporary (local instance) std::map<MyClass*, MyClass*>. The problem is, that when the temporary map goes out of scope, destructors on MyClass are called and the items are deallocated.

What am I doing wrong?

EDIT: Added both Dictionary and MyString classes:

```<code>
#include <iostream>
#include "Dictionary.h"

Dictionary::Dictionary(const char *filename) {
    entries = new std::map<MyString *, MyString *>();
    load(filename);
}

void Dictionary::load(const char *filename) {
    FILE *fh = fopen(filename, "r");
    if (!fh) {
        printf("Unable to open file: %s\n", filename);
        return;
    }

    size_t len;
    while (!feof(fh)) {
        char *line = fgetln(fh, &len);
        if (len > 60) {
            printf("Line too long, skipping.\n");
            continue;
        }

        // find ";" character and change it to \0
        char *delimiter = strstr(line, ";");
        if (delimiter == nullptr) {
            printf("Line does not contain delimiter.\n");
            continue;
        }

        // if last character in line is newline, subtract length
        if (line[len - 1] == '\n') {
            len--;
        }

        entries->insert(std::pair<MyString *, MyString *>(
                new MyString(line, (size_t) (delimiter - line)),
                new MyString(delimiter + 1, (size_t) (len - (delimiter - line + 1)))));
    }

    fclose(fh);
}

void Dictionary::list(ComparisonOperations op, MyString *sub) {
    std::map<MyString *, MyString *> results;

    for (auto &entry : *entries) {
        switch (op) {
            case StartingOp:
                if (entry.first->beginsWith(*sub)) {
                    results.insert(entry);
                }
                break;
            case ContainingOp:
                if (entry.first->contains(*sub)) {
                    results.insert(entry);
                }
                break;
            case EndingOp:
                if (entry.first->endsWith(*sub)) {
                    results.insert(entry);
                }
                break;
        }
    }

    // print results
    Dictionary::print(std::cout, results);
}

void Dictionary::print(std::ostream &os, std::map<MyString *, MyString *> &results) {
    if (results.empty()) {
        os << "No match found." << std::endl;
    } else if (results.size() == 1) {
        auto result = results.begin();
        os << (MyString) *(result->first)
           << " => " << (MyString) *(result->second) << std::endl;
    } else {
        for (auto &result : results) {
             os << (MyString) *(result.first) << std::endl;
        }
    }
}

---

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "MyString.h"

MyString::MyString() {
    buffer = (char *) malloc(1);
    memset(buffer, 0, 1);
}

MyString::MyString(const char *str) {
    buffer = (char *) malloc(MAX_MY_STRING_LEN + 1);
    memset(buffer, 0, MAX_MY_STRING_LEN + 1);
    strncpy(buffer, str, MAX_MY_STRING_LEN);
}

MyString::MyString(const char *str, int len) {
    buffer = (char *) malloc(len + 1);
    memset(buffer, 0, len + 1);
    strncpy(buffer, str, len);
}

MyString::~MyString() {
    if (buffer != nullptr) {
        printf("dealloc string %s!", buffer);
        free(buffer);
    }
    buffer = nullptr;
}

bool MyString::operator==(const MyString &cmp) const {
    return strcmp(buffer, cmp.buffer) == 0;
}

bool MyString::operator<(const MyString &cmp) const {
    return strcmp(buffer, cmp.buffer) < 0;
}

bool MyString::beginsWith(const MyString &sub) const {
    return strstr(buffer, sub.buffer) == buffer;
}

bool MyString::contains(const MyString &sub) const {
    return strstr(buffer, sub.buffer) != nullptr;
}

bool MyString::endsWith(const MyString &sub) const {
    char *pos = strstr(buffer, sub.buffer);
    return (pos - buffer + strlen(sub.buffer)) == strlen(buffer);
}

void MyString::print() {
    printf("%s\n", buffer);
}

std::ostream &operator<<(std::ostream &os, const MyString &str) {
    return os << ((const char *) str.buffer);
}

</code>```

PS: No, it is not my school assignment, it's actually a school assignment of a friend and I am trying it just for fun, because, as you can see, my C++ is beyond rusty.

答:
Since MyString doesn't have a copy constructor, the expression (MyString) *(result->first) inside Dictionary::print created a temporary that borrows a reference to the underlying data and then frees it out from under the original owner prematurely.

That said, using pointer through the Dictionary class means that all the other pointer are leaked when the Dictionary is destroyed.

Body:
I am a C++ non-user and I am just trying something for fun and I've got stuck and I suppose, I am doing something wrong.

I have a std::map of my own classes (std::map<MyClass*, MyClass*>) and I am trying to filter out a subset, store it as a temporary (local instance) std::map<MyClass*, MyClass*>. The problem is, that when the temporary map goes out of scope, destructors on MyClass are called and the items are deallocated.

What am I doing wrong?

EDIT: Added both Dictionary and MyString classes:

#include <iostream>
#include "Dictionary.h"

Dictionary::Dictionary(const char *filename) {
    entries = new std::map<MyString *, MyString *>();
    load(filename);
}

void Dictionary::load(const char *filename) {
    FILE *fh = fopen(filename, "r");
    if (!fh) {
        printf("Unable to open file: %s\n", filename);
        return;
    }

    size_t len;
    while (!feof(fh)) {
        char *line = fgetln(fh, &len);
        if (len > 60) {
            printf("Line too long, skipping.\n");
            continue;
        }

        // find ";" character and change it to \0
        char *delimiter = strstr(line, ";");
        if (delimiter == nullptr) {
            printf("Line does not contain delimiter.\n");
            continue;
        }

        // if last character in line is newline, subtract length
        if (line[len - 1] == '\n') {
            len--;
        }

        entries->insert(std::pair<MyString *, MyString *>(
                new MyString(line, (size_t) (delimiter - line)),
                new MyString(delimiter + 1, (size_t) (len - (delimiter - line + 1)))));
    }

    fclose(fh);
}

void Dictionary::list(ComparisonOperations op, MyString *sub) {
    std::map<MyString *, MyString *> results;

    for (auto &entry : *entries) {
        switch (op) {
            case StartingOp:
                if (entry.first->beginsWith(*sub)) {
                    results.insert(entry);
                }
                break;
            case ContainingOp:
                if (entry.first->contains(*sub)) {
                    results.insert(entry);
                }
                break;
            case EndingOp:
                if (entry.first->endsWith(*sub)) {
                    results.insert(entry);
                }
                break;
        }
    }

    // print results
    Dictionary::print(std::cout, results);
}

void Dictionary::print(std::ostream &os, std::map<MyString *, MyString *> &results) {
    if (results.empty()) {
        os << "No match found." << std::endl;
    } else if (results.size() == 1) {
        auto result = results.begin();
        os << (MyString) *(result->first)
           << " => " << (MyString) *(result->second) << std::endl;
    } else {
        for (auto &result : results) {
             os << (MyString) *(result.first) << std::endl;
        }
    }
}

---

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "MyString.h"

MyString::MyString() {
    buffer = (char *) malloc(1);
    memset(buffer, 0, 1);
}

MyString::MyString(const char *str) {
    buffer = (char *) malloc(MAX_MY_STRING_LEN + 1);
    memset(buffer, 0, MAX_MY_STRING_LEN + 1);
    strncpy(buffer, str, MAX_MY_STRING_LEN);
}

MyString::MyString(const char *str, int len) {
    buffer = (char *) malloc(len + 1);
    memset(buffer, 0, len + 1);
    strncpy(buffer, str, len);
}

MyString::~MyString() {
    if (buffer != nullptr) {
        printf("dealloc string %s!", buffer);
        free(buffer);
    }
    buffer = nullptr;
}

bool MyString::operator==(const MyString &cmp) const {
    return strcmp(buffer, cmp.buffer) == 0;
}

bool MyString::operator<(const MyString &cmp) const {
    return strcmp(buffer, cmp.buffer) < 0;
}

bool MyString::beginsWith(const MyString &sub) const {
    return strstr(buffer, sub.buffer) == buffer;
}

bool MyString::contains(const MyString &sub) const {
    return strstr(buffer, sub.buffer) != nullptr;
}

bool MyString::endsWith(const MyString &sub) const {
    char *pos = strstr(buffer, sub.buffer);
    return (pos - buffer + strlen(sub.buffer)) == strlen(buffer);
}

void MyString::print() {
    printf("%s\n", buffer);
}

std::ostream &operator<<(std::ostream &os, const MyString &str) {
    return os << ((const char *) str.buffer);
}

PS: No, it is not my school assignment, it's actually a school assignment of a friend and I am trying it just for fun, because, as you can see, my C++ is beyond rusty.


问:
NPM package `pem` doesn't seem to work in AWS lambda NodeJS 10.x (results in OpenSSL error)
When I run the function locally on NodeJS 11.7.0 it works, when I run it in AWS Lambda NodeJS 8.10 it works, but I've recently tried to run it in AWS Lambda NodeJS 10.x and get this response and this error in Cloud Watch.

Any thoughts on how to correct this?

Response

```<code>{
    "success": false,
    "error": "Error: Could not find openssl on your system on this path: openssl"
}
</code>```

Cloudwatch Error

```<code>ERROR (node:8) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
</code>```

Function

```<code>...
const util = require('util');
const pem = require('pem');
...

return new Promise((fulfill) => {
        require('./certs').get(req, res, () => {
            return fulfill();
        });
    }).then(() => {
        const createCSR = util.promisify(pem.createCSR);

        //This seems to be where the issue is coming from
        return createCSR({
            keyBitsize: 1024,
            hash: HASH,
            commonName: id.toString(),
            country: 'US',
            state: 'Maryland',
            organization: 'ABC', //Obfuscated
            organizationUnit: 'XYZ', //Obfuscated
        });
    }).then(({ csr, clientKey }) => {
        ...
    }).then(async ({ certificate, clientKey }) => {
        ...
    }, (err) => {
        return res.status(404).json({
            success: false,
            error: err,
        });
    });
...

</code>```

I've tried with
"pem": "^1.14.3", and "pem": "^1.14.2",

答:
I tried the answer documented by @Kris White, but I was not able to get it to work.  Each execution resulted in the error Could not find openssl on your system on this path: /opt/openssl.  I tried several different paths and approaches, but none worked well.  It's entirely possible that I simply didn't copy the OpenSSL executable correctly.

Since I needed a working solution, I used the answer provided by @Wilfred Dittmer.  I modified it slightly since I wasn't using Docker.  I launched an Amazon Linux 2 server, built OpenSSL on it, transferred the package to my local machine, and deployed it via Serverless.

Create a file named create-openssl-zip.sh with the following contents.  The script will create the Lambda Layer OpenSSL package.

```<code>#!/bin/bash -x

# This file should be copied to and run inside the /tmp folder
yum update -y
yum install autoconf bison gcc gcc-c++ libcurl-devel libxml2-devel -y
curl -sL http://www.openssl.org/source/openssl-1.1.1d.tar.gz | tar -xvz
cd openssl-1.1.1d
./config --prefix=/tmp/nodejs/openssl --openssldir=/tmp/nodejs/openssl && make && make install
cd /tmp
rm -rf nodejs/openssl/share nodejs/openssl/include
zip -r lambda-layer-openssl.zip nodejs
rm -rf nodejs openssl-1.1.1d
</code>```

Then, follow these steps:

Open a terminal session in this project's root folder.

Run the following command to upload the Linux bash script.

curl -F "file=@create-openssl-zip.sh" https://file.io

Note: The command above uses the popular tool File.io to copy the script to the cloud temporarily so it can be securely retrieved from the build server.

Note: If curl is not installed on your dev machine, you can also upload the script manually using the File.io website.

Copy the URL for the uploaded file from either the terminal session or the File.io website.

Note: The url will look similar to this example: https://file.io/a1B2c3

Open the AWS Console to the EC2 Instances list.

Launch a new instance with these attributes:

AMI: Amazon Linux 2 AMI (HVM), SSD Volume Type (id: ami-0a887e401f7654935)

Instance Type: t2.micro

Instance Details: (use all defaults)

Storage: (use all defaults)

Tags: Name - 'build-lambda-layer-openssl'

Security Group: 'Create new security group' (use all defaults to ensure Instance will be publicly accessible via SSH over the internet)

When launching the instance and selecting a key pair, be sure to choose a Key Pair from the list to which you have access.

Launch the instance and wait for it to be accessible.

Once the instance is running, use an SSH Client to connect to the instance.

More details on how to open an SSH connection can be found here.

In the SSH terminal session, navigate to the tmp directory by running cd /tmp.

Download the bash script uploaded earlier by running curl {FILE_IO_URL} --output create-openssl-zip.sh.

Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 3.

Execute the bash script by running sudo bash ./create-openssl-zip.sh.  The script may take a while to complete.  You may need to confirm one or more package install prompts.

When the script completes, run the following command to upload the package to File.io: curl -F "file=@lambda-layer-openssl.zip" https://file.io.

Copy the URL for the uploaded file from the terminal session.

In the terminal session on the local development machine, run the following command to download the file: curl {FILE_IO_URL} --output lambda-layer-openssl.zip.

Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 13.

Note: If curl is not installed on your dev machine, you can also download the file manually by pasting the copied URL in the address bar of your favorite browser.

Close the SSH session.

In the EC2 Instances list, terminate the build-lambda-layer-openssl EC2 instance since it is not needed any longer.

The OpenSSL Lambda Layer is now ready to be deployed.

For completeness, here is a portion of my serverless.yml file:

```<code>functions:
  functionName:
    # ...
    layers:
      - { Ref: OpensslLambdaLayer }

layers:
  openssl:
    name: ${self:provider.stage}-openssl
    description: Contains openssl command line utility for lambdas that need it
    package:
      artifact: 'path\to\lambda-layer-openssl.zip'
    compatibleRuntimes:
      - nodejs10.x
      - nodejs12.x
    retain: false
</code>```

...and here is how I configured PEM in the code file:

```<code>import * as pem from 'pem';
process.env.LD_LIBRARY_PATH = '/opt/nodejs/openssl/lib';
pem.config({
    pathOpenSSL: '/opt/nodejs/openssl/bin/openssl',
});
// other code...
</code>```

Body:
When I run the function locally on NodeJS 11.7.0 it works, when I run it in AWS Lambda NodeJS 8.10 it works, but I've recently tried to run it in AWS Lambda NodeJS 10.x and get this response and this error in Cloud Watch.

Any thoughts on how to correct this?

Response

{
    "success": false,
    "error": "Error: Could not find openssl on your system on this path: openssl"
}

Cloudwatch Error

ERROR (node:8) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

Function

...
const util = require('util');
const pem = require('pem');
...

return new Promise((fulfill) => {
        require('./certs').get(req, res, () => {
            return fulfill();
        });
    }).then(() => {
        const createCSR = util.promisify(pem.createCSR);

        //This seems to be where the issue is coming from
        return createCSR({
            keyBitsize: 1024,
            hash: HASH,
            commonName: id.toString(),
            country: 'US',
            state: 'Maryland',
            organization: 'ABC', //Obfuscated
            organizationUnit: 'XYZ', //Obfuscated
        });
    }).then(({ csr, clientKey }) => {
        ...
    }).then(async ({ certificate, clientKey }) => {
        ...
    }, (err) => {
        return res.status(404).json({
            success: false,
            error: err,
        });
    });
...

I've tried with
"pem": "^1.14.3", and "pem": "^1.14.2",

Body:
I tried the answer documented by @Kris White, but I was not able to get it to work.  Each execution resulted in the error Could not find openssl on your system on this path: /opt/openssl.  I tried several different paths and approaches, but none worked well.  It's entirely possible that I simply didn't copy the OpenSSL executable correctly.

Since I needed a working solution, I used the answer provided by @Wilfred Dittmer.  I modified it slightly since I wasn't using Docker.  I launched an Amazon Linux 2 server, built OpenSSL on it, transferred the package to my local machine, and deployed it via Serverless.

Create a file named create-openssl-zip.sh with the following contents.  The script will create the Lambda Layer OpenSSL package.

#!/bin/bash -x

# This file should be copied to and run inside the /tmp folder
yum update -y
yum install autoconf bison gcc gcc-c++ libcurl-devel libxml2-devel -y
curl -sL http://www.openssl.org/source/openssl-1.1.1d.tar.gz | tar -xvz
cd openssl-1.1.1d
./config --prefix=/tmp/nodejs/openssl --openssldir=/tmp/nodejs/openssl && make && make install
cd /tmp
rm -rf nodejs/openssl/share nodejs/openssl/include
zip -r lambda-layer-openssl.zip nodejs
rm -rf nodejs openssl-1.1.1d

Then, follow these steps:

Open a terminal session in this project's root folder.

Run the following command to upload the Linux bash script.

curl -F "file=@create-openssl-zip.sh" https://file.io

Note: The command above uses the popular tool File.io to copy the script to the cloud temporarily so it can be securely retrieved from the build server.

Note: If curl is not installed on your dev machine, you can also upload the script manually using the File.io website.

Copy the URL for the uploaded file from either the terminal session or the File.io website.

Note: The url will look similar to this example: https://file.io/a1B2c3

Open the AWS Console to the EC2 Instances list.

Launch a new instance with these attributes:

AMI: Amazon Linux 2 AMI (HVM), SSD Volume Type (id: ami-0a887e401f7654935)

Instance Type: t2.micro

Instance Details: (use all defaults)

Storage: (use all defaults)

Tags: Name - 'build-lambda-layer-openssl'

Security Group: 'Create new security group' (use all defaults to ensure Instance will be publicly accessible via SSH over the internet)

When launching the instance and selecting a key pair, be sure to choose a Key Pair from the list to which you have access.

Launch the instance and wait for it to be accessible.

Once the instance is running, use an SSH Client to connect to the instance.

More details on how to open an SSH connection can be found here.

In the SSH terminal session, navigate to the tmp directory by running cd /tmp.

Download the bash script uploaded earlier by running curl {FILE_IO_URL} --output create-openssl-zip.sh.

Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 3.

Execute the bash script by running sudo bash ./create-openssl-zip.sh.  The script may take a while to complete.  You may need to confirm one or more package install prompts.

When the script completes, run the following command to upload the package to File.io: curl -F "file=@lambda-layer-openssl.zip" https://file.io.

Copy the URL for the uploaded file from the terminal session.

In the terminal session on the local development machine, run the following command to download the file: curl {FILE_IO_URL} --output lambda-layer-openssl.zip.

Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 13.

Note: If curl is not installed on your dev machine, you can also download the file manually by pasting the copied URL in the address bar of your favorite browser.

Close the SSH session.

In the EC2 Instances list, terminate the build-lambda-layer-openssl EC2 instance since it is not needed any longer.

The OpenSSL Lambda Layer is now ready to be deployed.

For completeness, here is a portion of my serverless.yml file:

functions:
  functionName:
    # ...
    layers:
      - { Ref: OpensslLambdaLayer }

layers:
  openssl:
    name: ${self:provider.stage}-openssl
    description: Contains openssl command line utility for lambdas that need it
    package:
      artifact: 'path\to\lambda-layer-openssl.zip'
    compatibleRuntimes:
      - nodejs10.x
      - nodejs12.x
    retain: false

...and here is how I configured PEM in the code file:

import * as pem from 'pem';
process.env.LD_LIBRARY_PATH = '/opt/nodejs/openssl/lib';
pem.config({
    pathOpenSSL: '/opt/nodejs/openssl/bin/openssl',
});
// other code...


问:
How to keep same background-image ratio/size on all different screen sizes?
How do you keep the background-image same ratio so that it looks fitted for all different screen-sizes? In other words, how can I make sure the background-image always looks perfectly "centered". Please take note I have several other screens with other background-images so the solution should work for different images, not just the houses below.

CSS :

```<code>#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}
</code>```

This is the desired output for ALL screen sizes. Perfectly aligned :

However when I resize and experiment with different sizes, the background gets misplaced and does not look really good. It looks like the image is a bit more to the right :

答:
Since your CSS is telling the page to make sure the background covers the entire screen in both width and height, this will cause some irregularities in screens that don't match your image's aspect ratio. It has to stretch to cover the entire height in your second screen, but "cover" scales in both directions, so it keeps increasing the image size until the whole screen is covered. If you just want to make sure the background fills the screen horizontally (and don't mind that there may be space left at the bottom for taller screens), just set the width to fill the whole screen:

background-size: 100% auto;

Body:
How do you keep the background-image same ratio so that it looks fitted for all different screen-sizes? In other words, how can I make sure the background-image always looks perfectly "centered". Please take note I have several other screens with other background-images so the solution should work for different images, not just the houses below.

CSS :

#background{
     background-image: url("../images/houses.png");
     background-color: whitesmoke; /* Used if the image is unavailable */
     height: 100%; /* You must set a specified height */
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover; /* Resize the background image to cover the entire container */
     text-align: center;
     padding: 2.5%;

}

This is the desired output for ALL screen sizes. Perfectly aligned :

However when I resize and experiment with different sizes, the background gets misplaced and does not look really good. It looks like the image is a bit more to the right :


问:
iOS - QLPreviewController - How to stop QuickLook from Rotating?
I have QuickLook (QLPreviewController) almost working how I want it, but because of the images characteristics I don't want it to rotate into portrait orientation.I have it configured in the "shouldAutoRotateToInterfaceOrientation" method to only return yes for landscape rotations (see code below for details) but it is still rotating to portrait.

Note: The shouldAutoRotateToInterfaceOrientation is a direct copy that is used in all of my view controllers for this project and it is working in the other view controllers.

```<code>//
//  documentViewer.m
//

#import "DocumentViewer.h"

@implementation DocumentViewer

@synthesize documents;

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        return YES;
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight)
        return YES;
    else
        return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

}

//-(void)viewWillAppear:(BOOL)animated {
//
//  self.userInteractionEnabled = YES;
//}

//Nessary for Enabling User Interaction
- (BOOL)canBecomeFirstResponder {
    return YES;
}

-(void) createList:(NSString *) document {

    documents =     [[NSArray arrayWithObjects:document, nil] retain];
}

-(NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller {

    return [documents count];
}

- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index {

    return [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[documents objectAtIndex:index] ofType:nil]];
}
@end
</code>```

答:
According to the ViewController Programming Guide for iOS, the autorotation is roughly controlled by the ViewController that was most recently made visible.

In your case that's probably the QLPreviewController itself, not your DocumentViewer. (And you say that the latter's shouldAutorotateToInterfaceOrientation: isn't called, which is consistent with this hypothesis).

So the autorotation is controlled by the shouldAutorotateToInterfaceOrientation: method of QLPreviewController, which in a little experiment of mine seems to allow everything but upside-down orientation.

So what you can do is define a subclass of QLPreviewController that only overrides shouldAutorotateToInterfaceOrientation: the way you did in DocumentViewer and use this subclass instead of the original QLPreviewController.

LandscapeOnlyQLPreviewController.h:

```<code>#import <QuickLook/QuickLook.h>

@interface LandscapeOnlyQLPreviewController : QLPreviewController {
}
@end
</code>```

LandscapeOnlyQLPreviewController.m:

```<code>#import "LandscapeOnlyQLPreviewController.h"

@implementation LandscapeOnlyQLPreviewController
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
{
  return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
@end
</code>```

Body:
I have QuickLook (QLPreviewController) almost working how I want it, but because of the images characteristics I don't want it to rotate into portrait orientation.I have it configured in the "shouldAutoRotateToInterfaceOrientation" method to only return yes for landscape rotations (see code below for details) but it is still rotating to portrait.

Note: The shouldAutoRotateToInterfaceOrientation is a direct copy that is used in all of my view controllers for this project and it is working in the other view controllers.

//
//  documentViewer.m
//

#import "DocumentViewer.h"

@implementation DocumentViewer

@synthesize documents;

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        return YES;
    else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight)
        return YES;
    else
        return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

}

//-(void)viewWillAppear:(BOOL)animated {
//
//  self.userInteractionEnabled = YES;
//}

//Nessary for Enabling User Interaction
- (BOOL)canBecomeFirstResponder {
    return YES;
}

-(void) createList:(NSString *) document {

    documents =     [[NSArray arrayWithObjects:document, nil] retain];
}

-(NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller {

    return [documents count];
}

- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index {

    return [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[documents objectAtIndex:index] ofType:nil]];
}
@end

Body:
According to the ViewController Programming Guide for iOS, the autorotation is roughly controlled by the ViewController that was most recently made visible.

In your case that's probably the QLPreviewController itself, not your DocumentViewer. (And you say that the latter's shouldAutorotateToInterfaceOrientation: isn't called, which is consistent with this hypothesis).

So the autorotation is controlled by the shouldAutorotateToInterfaceOrientation: method of QLPreviewController, which in a little experiment of mine seems to allow everything but upside-down orientation.

So what you can do is define a subclass of QLPreviewController that only overrides shouldAutorotateToInterfaceOrientation: the way you did in DocumentViewer and use this subclass instead of the original QLPreviewController.

LandscapeOnlyQLPreviewController.h:

#import <QuickLook/QuickLook.h>

@interface LandscapeOnlyQLPreviewController : QLPreviewController {
}
@end

LandscapeOnlyQLPreviewController.m:

#import "LandscapeOnlyQLPreviewController.h"

@implementation LandscapeOnlyQLPreviewController
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
{
  return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
@end


问:
How do I reference the output of the previous "pipe" in a Powershell pipeline?
I wrote this code to get some (relative) file path:

```<code>function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"
</code>```

This threw the error:

```<code>Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
</code>```

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

```<code>$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"
</code>```

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

```<code>$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data
</code>```

I'd like to know where I'm going wrong both on a conceptual and a technical level.

答:
Just use a code block.

```<code>function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json"
$some_file_path

read-host
</code>```

The reason it doesn't work in this code @ get-content is because it's evaluating to false there.

```<code>Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json" | Get-Content {$_} and Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json" | Get-Content $_
</code>```

An object can only be passed on using $_ or $psItem if it evaluates to $True.

Here is why it works in the first example.

```<code>function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

if(Get-ExecutingScriptDirectory -eq $True){
    write-host This is true
}

Output: This is true
</code>```

You can use Parethesis to isolate your objects in the pipeline also.

example:

```<code>Get-Content (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json")
</code>```

"|" deals with the object to the left of it, so doing get-content | get-content | doesn't make sense to the script. You will need to separate it into multiple commands with a semi-colon if you're doing something like that. Or use a "Foreach" cmdlet.

gc (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json");gc (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "bar.json")

Body:
I wrote this code to get some (relative) file path:

function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "foo.json"

This threw the error:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
+ $some_file_path  = Get-ExecutingScriptDirectory | Join-Path -Path $_ -ChildPath "fo ...
+                                                     ~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand

This indicates to me that the output of Get-ExecutingScriptDirectory is null - but it isn't - when I write the script out like this, it's fine:

$this_directory = Get-ExecutingScriptDirectory
$some_file_path = Join-Path -Path $this_directory -ChildPath "foo.json"

So the problem is that $_ is null.  I would expect $_ to be reference to the previous pipe's standard output.  The MSDN documentation also suggests this, but then it seems to immediately contradict itself:

$_ contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

In the context of my code, $_ seems to qualify as the "current object in the pipeline object" - but I am not using this with a command that performs an action on every object or on selected objects in a pipeline.

$$ and $^ looked promising, but the MSDN documentation just says a few vague things here about lexical tokens.  The documentation on $PSItem was equally terse.

What I would actually like to do is create a big pipeline:

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {{PREVIOUS STDOUT}} -ChildPath "foo.json" | Get-Content {{PREVIOUS STDOUT}} | Convert-FromJson {{PREVIOUS STDOUT}} | {{PREVIOUS STDOUT}}.data

I'd like to know where I'm going wrong both on a conceptual and a technical level.

Body:
Just use a code block.

function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

$some_file_path = Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json"
$some_file_path

read-host

The reason it doesn't work in this code @ get-content is because it's evaluating to false there.

Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json" | Get-Content {$_} and Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json" | Get-Content $_

An object can only be passed on using $_ or $psItem if it evaluates to $True.

Here is why it works in the first example.

function Get-ExecutingScriptDirectory() {
    return Split-Path $script:MyInvocation.MyCommand.Path  # returns this script's directory
}

if(Get-ExecutingScriptDirectory -eq $True){
    write-host This is true
}

Output: This is true

You can use Parethesis to isolate your objects in the pipeline also.

example:

Get-Content (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json")

"|" deals with the object to the left of it, so doing get-content | get-content | doesn't make sense to the script. You will need to separate it into multiple commands with a semi-colon if you're doing something like that. Or use a "Foreach" cmdlet.

gc (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "foo.json");gc (Get-ExecutingScriptDirectory | Join-Path -Path {$_} -ChildPath "bar.json")