问:
event start-end into hot encoding in python
I have a pandas dataframe with 2 columns "type" and "sign" as follows

```<code>    type    sign
0   open    A
1   open    B
2   open    D
3   close   B
4   close   D
5   open    B
6   close   B
7   close   A
</code>```

"A" + "open" means that event A has started happening. "A" + "close" means that event A has stopped.
I need to vectorize it, when time is a major issue (the list is actually about 40 million lines long).
Kind of like one-hot-encoding, but i need "1" to exist if and only if an event is "active".
for example, for this case the results should be:

```<code>    A   B   C   D   type    sign
0   1   0   0   0   open    A
1   1   1   0   0   open    B
2   1   1   0   1   open    D
3   1   0   0   1   close   B
4   1   0   0   0   close   D
5   1   1   0   0   open    B
6   1   0   0   0   close   B
7   0   0   0   0   close   A
</code>```

Ideas?
thanks

答:
IIUC let do get_dummies then do cumsum

```<code>s=df.sign.str.get_dummies().reindex(columns=list('ABCD'),fill_value=0).\
    mul(df.type.map({'open':1,'close':-1}),axis=0).cumsum()
   A  B  C  D
0  1  0  0  0
1  1  1  0  0
2  1  1  0  1
3  1  0  0  1
4  1  0  0  0
5  1  1  0  0
6  1  0  0  0
7  0  0  0  0
df=df.join(s)
</code>```

Body:
I have a pandas dataframe with 2 columns "type" and "sign" as follows

    type    sign
0   open    A
1   open    B
2   open    D
3   close   B
4   close   D
5   open    B
6   close   B
7   close   A

"A" + "open" means that event A has started happening. "A" + "close" means that event A has stopped.
I need to vectorize it, when time is a major issue (the list is actually about 40 million lines long).
Kind of like one-hot-encoding, but i need "1" to exist if and only if an event is "active".
for example, for this case the results should be:

    A   B   C   D   type    sign
0   1   0   0   0   open    A
1   1   1   0   0   open    B
2   1   1   0   1   open    D
3   1   0   0   1   close   B
4   1   0   0   0   close   D
5   1   1   0   0   open    B
6   1   0   0   0   close   B
7   0   0   0   0   close   A

Ideas?
thanks

Body:
IIUC let do get_dummies then do cumsum

s=df.sign.str.get_dummies().reindex(columns=list('ABCD'),fill_value=0).\
    mul(df.type.map({'open':1,'close':-1}),axis=0).cumsum()
   A  B  C  D
0  1  0  0  0
1  1  1  0  0
2  1  1  0  1
3  1  0  0  1
4  1  0  0  0
5  1  1  0  0
6  1  0  0  0
7  0  0  0  0
df=df.join(s)


来源: stackexchange

问:
Create a function that separates the characters of a word by symbols
I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l

I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols

This is the code I used for separating with a space

```<code>Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim str As String = "mis programing II"
        Dim str2 As String = ""
        Dim cc As String
        For i = 1 To Len(str)
            cc = Mid(str, i, 1)
            str2 = str2 & cc & " "
        Next
        MsgBox(str2)
    End Sub
End Class
</code>```

答:
Nice exercise:

Can be done using LINQ as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim str As String = txtInput.Text '"mis programing II" for this example..
    Dim sep As Char

    'Validate your inputs:
    If String.IsNullOrWhiteSpace(str) OrElse
        Not Char.TryParse(cmbSep.Text, sep) Then
        Return
    End If

    'and in one line:
    Dim str2 = String.Join("", str.Split(" "c).
                            SelectMany(Function(x) x.ToCharArray.Append(" "c)).
                            Select(Function(x) $"{x}{If(Char.IsWhiteSpace(x), " ", sep)}")).
                            Replace($"{sep} ", " ").Trim

    MessageBox.Show(str2)

End Sub
```

<p>If you are not allowed to use <code>LINQ</code>, then the next snippet will do the same:</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim str As String = txtInput.Text '"mis programing II" for this example..
    Dim sep As Char

    'Validate your inputs:
    If String.IsNullOrWhiteSpace(str) OrElse
        Not Char.TryParse(cmbSep.Text, sep) Then
        Return
    End If

    Dim str2 As New StringBuilder

    For Each word In str.Split(" "c)
        For i = 0 To word.Length - 2
            str2.Append(word(i)).Append(sep)
        Next
        str2.Append(word(word.Length - 1)).Append("  ")
    Next

    MessageBox.Show(str2.ToString.Trim)

End Sub
</code>```

Some outputs:

```<code>m.i.s  p.r.o.g.r.a.m.i.n.g  I.I
m^i^s  p^r^o^g^r^a^m^i^n^g  I^I
m*i*s  p*r*o*g*r*a*m*i*n*g  I*I
m-i-s  p-r-o-g-r-a-m-i-n-g  I-I
m_i_s  p_r_o_g_r_a_m_i_n_g  I_I
m i s  p r o g r a m i n g  I I
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create a function where, for example, if I put the word visual in the input box I have to select from the ComboBox one of these 3 symbols: space, . , or *, in the output box I want the result of the word visual to come out like this: v.i.s.u.a.l or v i s u a l

I already know how to output a result that separates the string by a space but I don't know how to do it using a ComboBox with 3 symbols

This is the code I used for separating with a space

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim str As String = "mis programing II"
        Dim str2 As String = ""
        Dim cc As String
        For i = 1 To Len(str)
            cc = Mid(str, i, 1)
            str2 = str2 & cc & " "
        Next
        MsgBox(str2)
    End Sub
End Class

Body:
Nice exercise:

Can be done using LINQ as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim str As String = txtInput.Text '"mis programing II" for this example..
    Dim sep As Char

    'Validate your inputs:
    If String.IsNullOrWhiteSpace(str) OrElse
        Not Char.TryParse(cmbSep.Text, sep) Then
        Return
    End If

    'and in one line:
    Dim str2 = String.Join("", str.Split(" "c).
                            SelectMany(Function(x) x.ToCharArray.Append(" "c)).
                            Select(Function(x) $"{x}{If(Char.IsWhiteSpace(x), " ", sep)}")).
                            Replace($"{sep} ", " ").Trim

    MessageBox.Show(str2)

End Sub

If you are not allowed to use LINQ, then the next snippet will do the same:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim str As String = txtInput.Text '"mis programing II" for this example..
    Dim sep As Char

    'Validate your inputs:
    If String.IsNullOrWhiteSpace(str) OrElse
        Not Char.TryParse(cmbSep.Text, sep) Then
        Return
    End If

    Dim str2 As New StringBuilder

    For Each word In str.Split(" "c)
        For i = 0 To word.Length - 2
            str2.Append(word(i)).Append(sep)
        Next
        str2.Append(word(word.Length - 1)).Append("  ")
    Next

    MessageBox.Show(str2.ToString.Trim)

End Sub

Some outputs:

m.i.s  p.r.o.g.r.a.m.i.n.g  I.I
m^i^s  p^r^o^g^r^a^m^i^n^g  I^I
m*i*s  p*r*o*g*r*a*m*i*n*g  I*I
m-i-s  p-r-o-g-r-a-m-i-n-g  I-I
m_i_s  p_r_o_g_r_a_m_i_n_g  I_I
m i s  p r o g r a m i n g  I I


问:
Replace "/" in a string using shell script
```<code>PATH="/dir1/subdir1"
</code>```

Want to replace "/" with "-" from the above string
and the result should be

-dir1-subdir1

答:
In bash you can use a pattern substitution of the form ${parameter//pattern/string} to replace all matches of pattern with string:

```<code>echo "${PATH//\//-}"
</code>```

Note that your pattern string / must be escaped with \/.

Body:
PATH="/dir1/subdir1"

Want to replace "/" with "-" from the above string
and the result should be

-dir1-subdir1

Body:
In bash you can use a pattern substitution of the form ${parameter//pattern/string} to replace all matches of pattern with string:

echo "${PATH//\//-}"

Note that your pattern string / must be escaped with \/.


问:
How to display departments as nodes in Laravel
I have a table i db 'departments' .I want it do display it with jstree.I have a parent_id,the root node that is 0 and another that is 1 .I have problems in displaying them in a parent and child relationship..Here is my code and what i have tried but the problem is that it is displaying like this:

```<code> - IT Department
     - IT Department
 - IT Department
     - IT Department
</code>```

and i want it like this

```<code> - IT Department
     - Research and development
 - Finance
     - Product development
</code>```

```<code>    <ul>
    if({{ $department->parent_id }} == 0)
    {

      <li>{{ $department->name }}
        <ul>
          <li id="child_node_1">{{ $department->id }}</li>
          <li >{{ $department->name }}</li>
        </ul>
      </li>
    }
    if({{ $department->parent_id }} == 1)
    {
      <li>{{ $department->name }}
      <ul>
          <li id="child_node_2">{{ $department->id }}</li>
          <li >{{ $department->name }}</li>
        </ul>
      </li>
    }

    </ul>
</code>```

答:
It sounds like you might want to create a self referential relationship, using laravel's ORM. Check out the one to one relationship.

Your finished code may look something like this:

Department.php

```<code>class Department extends Eloquent {

    public function parents()
    {
        return $this->belongsTo('Department', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('Department', 'parent_id');
    }
}
</code>```

department.blade.php

```<code><li>{{ $parent->name }}
    <ul>
    @foreach($department->parents as $parent)
        <li id="child_node_1">{{ $parent->id }}</li>
        <li>{{ $parent->name }}</li>
    @endforeach
    </ul>
</li>
</code>```

Body:
I have a table i db 'departments' .I want it do display it with jstree.I have a parent_id,the root node that is 0 and another that is 1 .I have problems in displaying them in a parent and child relationship..Here is my code and what i have tried but the problem is that it is displaying like this:

 - IT Department
     - IT Department
 - IT Department
     - IT Department

and i want it like this

 - IT Department
     - Research and development
 - Finance
     - Product development

    if({{ $department->parent_id }} == 0)
    {

{{ $department->name }}

{{ $department->id }}

{{ $department->name }}

    }
    if({{ $department->parent_id }} == 1)
    {

{{ $department->name }}

{{ $department->id }}

{{ $department->name }}

    }

Body:
It sounds like you might want to create a self referential relationship, using laravel's ORM. Check out the one to one relationship.

Your finished code may look something like this:

Department.php

class Department extends Eloquent {

    public function parents()
    {
        return $this->belongsTo('Department', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('Department', 'parent_id');
    }
}

department.blade.php

<li>{{ $parent->name }}
    <ul>
    @foreach($department->parents as $parent)
        <li id="child_node_1">{{ $parent->id }}</li>
        <li>{{ $parent->name }}</li>
    @endforeach
    </ul>
</li>


问:
Cannot assign to 'd' because it is not a variable typescript
Hi I am having two files that use the same interface and variable so I am trying to import the variable to another typescript file. The interface is imported too from a global interface file.

```<code>declare interface personInterface {
    name: string;
    surname: string;
}

export let d: personInterface = {
    name: '',
    surname: ''
};
</code>```

I am importing then d in another file:

```<code>import { d } from "./file";

d = sessionStorage.getItem("person");
</code>```

I get the following error:
Cannot assign to 'd' because it is not a variable.

答:
import {d} from ... works like

```<code>const d = ...;
</code>```

that is why you cannot reassign a constant

Body:
Hi I am having two files that use the same interface and variable so I am trying to import the variable to another typescript file. The interface is imported too from a global interface file.

declare interface personInterface {
    name: string;
    surname: string;
}

export let d: personInterface = {
    name: '',
    surname: ''
};

I am importing then d in another file:

import { d } from "./file";

d = sessionStorage.getItem("person");

I get the following error:
Cannot assign to 'd' because it is not a variable.

Body:
import {d} from ... works like

const d = ...;

that is why you cannot reassign a constant


问:
What's the difference between useCallback and useMemo
Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.

I passed inputs - as a second argument to useCallback - non-ever-changeable constants - but returned memoized callback still runs my expensive calculations at every render (I'm pretty sure - you can check by yourself in the snippet below).

I've changed useCallback to useMemo - and useMemo works as expected — runs when passed inputs changes. And really memoizes the expensive calculations.

Live example:

'use strict';

const { useState, useCallback, useMemo } = React;

const neverChange = 'I never change';
const oneSecond = 1000;

function App() {
  const [second, setSecond] = useState(0);

  // This  expensive function executes everytime when render happens:
  const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
  const computedCallback = calcCallback();

  // This  executes once
  const computedMemo = useMemo(() => expensiveCalc('useMemo'), [neverChange]);

  setTimeout(() => setSecond(second + 1), oneSecond);

  return `
    useCallback: ${computedCallback} times |
    useMemo: ${computedMemo} |
    App lifetime: ${second}sec.
  `;
}

const tenThousand = 10 * 1000;
let expensiveCalcExecutedTimes = { 'useCallback': 0, 'useMemo': 0 };

function expensiveCalc(hook) {
  let i = 0;
  while (i < tenThousand) i++;

  return ++expensiveCalcExecutedTimes[hook];
}

ReactDOM.render(
  React.createElement(App),
  document.querySelector('#app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>useCallback vs useMemo:</h1>
<div id="app">Loading...</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script></code>```

答:
useMemo is intended to run the function and return a value at when the component renders (assuming one of the dependancies has changed). useCallback is intended to return a (memoized) function at render time, but does not actually call the function yet; typically you just pass this function to an onClick parameter or something like that.

You can use them interchangeably if called correctly, for example having useMemo return a function is equivalent to useCallback, or using useCallback and then calling the returned function is similar to useMemo

Body:
Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.

I passed inputs - as a second argument to useCallback - non-ever-changeable constants - but returned memoized callback still runs my expensive calculations at every render (I'm pretty sure - you can check by yourself in the snippet below).

I've changed useCallback to useMemo - and useMemo works as expected — runs when passed inputs changes. And really memoizes the expensive calculations.

Live example:

'use strict';

const { useState, useCallback, useMemo } = React;

const neverChange = 'I never change';
const oneSecond = 1000;

function App() {
  const [second, setSecond] = useState(0);

  // This  expensive function executes everytime when render happens:
  const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
  const computedCallback = calcCallback();

  // This  executes once
  const computedMemo = useMemo(() => expensiveCalc('useMemo'), [neverChange]);

  setTimeout(() => setSecond(second + 1), oneSecond);

  return `
    useCallback: ${computedCallback} times |
    useMemo: ${computedMemo} |
    App lifetime: ${second}sec.
  `;
}

const tenThousand = 10 * 1000;
let expensiveCalcExecutedTimes = { 'useCallback': 0, 'useMemo': 0 };

function expensiveCalc(hook) {
  let i = 0;
  while (i < tenThousand) i++;

  return ++expensiveCalcExecutedTimes[hook];
}

ReactDOM.render(
  React.createElement(App),
  document.querySelector('#app')
);

useCallback vs useMemo:

Loading...


问:
How to use a type from a child package / generic package instantiation
I can make the primitive subprograms of a type directly visible with
use all type like this:

```<code>package Type_Package is
   type T is null record;
   procedure Action(X: T) is null;
end Type_Package;

with Type_Package;
procedure Use_Type is
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;
</code>```

However, it does not seem to work when I move Type_Package inside
Use_Type.

```<code>procedure Use_Type is
   package Type_Package is
      type T is null record;
      procedure Action(X: T) is null;
   end Type_Package;
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;
</code>```

I get

```<code>gcc -c use_type.adb
use_type.adb:9:04: "Action" is not visible
use_type.adb:9:04: non-visible declaration at line 4
gnatmake: "use_type.adb" compilation error
</code>```

The same thing occurs when I instantiate a generic package.  For
example, when I want to use the data types in Ada.Containers.

```<code>package Element_Set is
   new Ada.Containers.Hashed_Sets(Element_Type, Hash, "=");
use all type Element_Set.Set;
</code>```

The use type clause here seems to have no effect.

How to use a type when the type is declared in a child package or an
instantiation of a generic package?

答:
You have indeed found a compiler bug.

There are a set of tests (the Ada Conformity Assessment Test Suite, ACATS - also here) in which the "B series" are designed to check that compilers catch errors.

One of those tests, B840003, starts off like your problem: a cut-down and slightly modified version behaves like this:

```<code> 1. procedure B840003 is
 2. begin
 3.
 4.    declare
 5.       package Pkg_1 is
 6.          type Enum is (Aaa, Bbb, Ccc);
 7.          procedure Prim_Proc (X : Enum := Aaa) is null;
 8.          function Prim_Func return Enum is (Bbb);
 9.
10.          package Nested is
11.             procedure Nonprim_Proc (X : Enum := Bbb) is null;
12.             function Nonprim_Func return Enum is (Ccc);
13.          end Nested;
14.
15.       end Pkg_1;
16.
17.    begin
18.       declare
19.          use all type Pkg_1.Enum;
20.       begin
21.          if Prim_Func /= Bbb then                                  -- OK.
22.             null;
23.          end if;
24.          if Nonprim_Func (Ccc) /= Ccc then                         -- ERROR:
                |
    >>> "Nonprim_Func" is not visible
    >>> non-visible declaration at line 12

25.             null;
26.          end if;
27.          Prim_Proc;                                                -- OK.
28.          Nonprim_Proc (Aaa);                                       -- ERROR:
             |
    >>> "Nonprim_Proc" is not visible
    >>> non-visible declaration at line 11

29.       end;
30.    end;
31.
32. end B840003;
</code>```

(see line 27) whereas one more closely like your example (pulling the package declaration up to the declarative region of the subprogram) does this:

```<code> 1. procedure B840003_Mod is
 2.    package Pkg_1 is
 3.       type Enum is (Aaa, Bbb, Ccc);
 4.       procedure Prim_Proc (X : Enum := Aaa) is null;
 5.       function Prim_Func return Enum is (Bbb);
 6.
 7.       package Nested is
 8.          procedure Nonprim_Proc (X : Enum := Bbb) is null;
 9.          function Nonprim_Func return Enum is (Ccc);
10.       end Nested;
11.
12.    end Pkg_1;
13.
14.    use all type Pkg_1.Enum;
15. begin
16.    if Prim_Func /= Bbb then                                  -- OK.
17.       null;
18.    end if;
19.    if Nonprim_Func (Ccc) /= Ccc then                         -- ERROR:
          |
    >>> "Nonprim_Func" is not visible
    >>> non-visible declaration at line 9

20.       null;
21.    end if;
22.    Prim_Proc;                                                -- OK.
       |
    >>> "Prim_Proc" is not visible
    >>> non-visible declaration at line 4

23.    Nonprim_Proc (Aaa);                                       -- ERROR:
       |
    >>> "Nonprim_Proc" is not visible
    >>> non-visible declaration at line 8

24.
25. end B840003_Mod;
</code>```

See line 22 (a procedure call; the function call at line 16 is OK!).

This is worth a bug report to AdaCore (though I wouldn’t expect them to drop everything and rush to fix it).

Interestingly, earlier versions of the compiler e.g. GNAT CE 2018) find Bbb, Ccc not visible.

Body:
I can make the primitive subprograms of a type directly visible with
use all type like this:

package Type_Package is
   type T is null record;
   procedure Action(X: T) is null;
end Type_Package;

with Type_Package;
procedure Use_Type is
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;

However, it does not seem to work when I move Type_Package inside
Use_Type.

procedure Use_Type is
   package Type_Package is
      type T is null record;
      procedure Action(X: T) is null;
   end Type_Package;
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;

I get

gcc -c use_type.adb
use_type.adb:9:04: "Action" is not visible
use_type.adb:9:04: non-visible declaration at line 4
gnatmake: "use_type.adb" compilation error

The same thing occurs when I instantiate a generic package.  For
example, when I want to use the data types in Ada.Containers.

package Element_Set is
   new Ada.Containers.Hashed_Sets(Element_Type, Hash, "=");
use all type Element_Set.Set;

The use type clause here seems to have no effect.

How to use a type when the type is declared in a child package or an
instantiation of a generic package?

Body:
You have indeed found a compiler bug.

There are a set of tests (the Ada Conformity Assessment Test Suite, ACATS - also here) in which the "B series" are designed to check that compilers catch errors.

One of those tests, B840003, starts off like your problem: a cut-down and slightly modified version behaves like this:

 1. procedure B840003 is
 2. begin
 3.
 4.    declare
 5.       package Pkg_1 is
 6.          type Enum is (Aaa, Bbb, Ccc);
 7.          procedure Prim_Proc (X : Enum := Aaa) is null;
 8.          function Prim_Func return Enum is (Bbb);
 9.
10.          package Nested is
11.             procedure Nonprim_Proc (X : Enum := Bbb) is null;
12.             function Nonprim_Func return Enum is (Ccc);
13.          end Nested;
14.
15.       end Pkg_1;
16.
17.    begin
18.       declare
19.          use all type Pkg_1.Enum;
20.       begin
21.          if Prim_Func /= Bbb then                                  -- OK.
22.             null;
23.          end if;
24.          if Nonprim_Func (Ccc) /= Ccc then                         -- ERROR:
                |
    >>> "Nonprim_Func" is not visible
    >>> non-visible declaration at line 12

25.             null;
26.          end if;
27.          Prim_Proc;                                                -- OK.
28.          Nonprim_Proc (Aaa);                                       -- ERROR:
             |
    >>> "Nonprim_Proc" is not visible
    >>> non-visible declaration at line 11

29.       end;
30.    end;
31.
32. end B840003;

(see line 27) whereas one more closely like your example (pulling the package declaration up to the declarative region of the subprogram) does this:

 1. procedure B840003_Mod is
 2.    package Pkg_1 is
 3.       type Enum is (Aaa, Bbb, Ccc);
 4.       procedure Prim_Proc (X : Enum := Aaa) is null;
 5.       function Prim_Func return Enum is (Bbb);
 6.
 7.       package Nested is
 8.          procedure Nonprim_Proc (X : Enum := Bbb) is null;
 9.          function Nonprim_Func return Enum is (Ccc);
10.       end Nested;
11.
12.    end Pkg_1;
13.
14.    use all type Pkg_1.Enum;
15. begin
16.    if Prim_Func /= Bbb then                                  -- OK.
17.       null;
18.    end if;
19.    if Nonprim_Func (Ccc) /= Ccc then                         -- ERROR:
          |
    >>> "Nonprim_Func" is not visible
    >>> non-visible declaration at line 9

20.       null;
21.    end if;
22.    Prim_Proc;                                                -- OK.
       |
    >>> "Prim_Proc" is not visible
    >>> non-visible declaration at line 4

23.    Nonprim_Proc (Aaa);                                       -- ERROR:
       |
    >>> "Nonprim_Proc" is not visible
    >>> non-visible declaration at line 8

24.
25. end B840003_Mod;

See line 22 (a procedure call; the function call at line 16 is OK!).

This is worth a bug report to AdaCore (though I wouldn’t expect them to drop everything and rush to fix it).

Interestingly, earlier versions of the compiler e.g. GNAT CE 2018) find Bbb, Ccc not visible.


答:
You can check the more detailed version.

```<code>$ var="001244abc"
$ replace="polo"
$ echo ${var//001244/$replace}
poloabc
</code>```

Hope it helps..

Title: Replace "/" in a string using shell script

Body:
You can check the more detailed version.

$ var="001244abc"
$ replace="polo"
$ echo ${var//001244/$replace}
poloabc

Hope it helps..


问:
How can I group and sum multiple columns in CSV file?
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

```<code>     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100
</code>```

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

```<code>     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400
</code>```

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

```<code>df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')
</code>```

答:
You can do the following</p>

```<code># group rows by 'id' column
df.groupby('id', as_index=False).agg({'date':'max',
                                      'name':'first',
                                      'unitCount':'sum',
                                      'orderCount':'sum',
                                      'invoiceCount':'sum'}

# change the order of the columns
df = df[['date', 'id', 'name', 'unitCount', 'orderCount'  ,'invoiceCount']]

# set the new column names
df.columns=['date', 'id', 'name', 'total_unitCount', 'total_orderCount'  ,'total_invoiceCount']

# save the dataframe as .csv file
df.to_csv('path/to/myfile_sum.csv')
</code>```

Body:
I'm still new to python and pandas and currently trying to get sum of multiple columns in a CSV file.

I have a CSV file with columns that I want to sum unitCount, orderCount, invoiceCount:

     date       id   name   unitCount   orderCount   invoiceCount
 2020-02-12     1   Guitar     200          100           200
 2020-02-12     2   Drums      300          200           100
 2020-02-12     3   Piano      400          700           300
 2020-02-11     1   Guitar     100          500           300
 2020-02-11     2   Drums      200          400           400
 2020-02-11     3   Piano      300          300           100

My desired output would be a CSV file with sum of those last 3 columns (grouped by ID) and linked to the latest date only:

     date       id   name   total_unitCount   total_orderCount   total_invoiceCount
 2020-02-12     1   Guitar        300              600                   500
 2020-02-12     2   Drums         500              600                   500
 2020-02-12     3   Piano         700              1000                  400

Would someone be able to help?

so far I was trying the below, but it doesn't work for me. Would be possible to add groupby to the first line of the below code? Or I started completely wrong? Thanks!

df = pd.read_csv(r'path/to/myfile.csv', sep=';').sum()
df.to_csv(r'path/to/myfile_sum.csv')

Body:
You can do the following

# group rows by 'id' column
df.groupby('id', as_index=False).agg({'date':'max',
                                      'name':'first',
                                      'unitCount':'sum',
                                      'orderCount':'sum',
                                      'invoiceCount':'sum'}

# change the order of the columns
df = df[['date', 'id', 'name', 'unitCount', 'orderCount'  ,'invoiceCount']]

# set the new column names
df.columns=['date', 'id', 'name', 'total_unitCount', 'total_orderCount'  ,'total_invoiceCount']

# save the dataframe as .csv file
df.to_csv('path/to/myfile_sum.csv')


问:
Combine multiple Regex.Replace calls
I've got a text processor, which includes hundreds of Regex.Replace calls. Many of them work on the same text. They would for example remove white spaces and unwanted characters, put brackets around numbers, remove black-listed words, etc.

Is there a way to make multiple replacements with different patterns with a single call? I'm wondering about that, because my code currently is quite slow and I guess that would save some cycles.

答:
If it is just for whitespaces, unwanted characters and blacklisted words, why don't you try string / StringBuilder functions?

```<code>string newString = oldString.Replace('`','\0');
string newString = oldString.Replace("blackword","");
</code>```

Also have a look here: Replace multiple words in string and Replace Multiple String Elements in C#

ContentLicense: CC BY-SA 3.0

Title: Combine multiple Regex.Replace calls

Body:
If it is just for whitespaces, unwanted characters and blacklisted words, why don't you try string / StringBuilder functions?

string newString = oldString.Replace('`','\0');
string newString = oldString.Replace("blackword","");

Also have a look here: Replace multiple words in string and Replace Multiple String Elements in C#


问:
TypeError: Cannot read property after refresh or after manipulation
I am getting the following error after a refresh and sometimes on initial project run:

TypeError: Cannot read property 'statements' of undefined

This is really confusing because the data is rendering fine it just seems the connection fails. Any idea what may be causing the error?

There are no additional errors when I remove the statements.map

I used this medium article to get everything up and running: Medium Article

index.js:

```<code>import React, { useState, useReducer } from 'react'
import { useQuery } from '@apollo/react-hooks'

// Custom layout
import Layout from "../components/layout"

import '../sass/styles.scss'

// Data Query
import STATEMENTS_QUERY from '../graphql/statements'

function StatementCall(context) {

  const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});

  return (
    <Layout>
      <div className="container">
        <div className="row spaces">
          <div className="col-md-12">
            <p>Testing</p>
            {data.statements.data.map((statement, index) => (
              <div>
                <p>{statement.id}</p>
                <p>{statement.title}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}

export default StatementCall
</code>```

graphql/statements.js:

```<code>import gql from 'graphql-tag';

const STATEMENTS_QUERY = gql`
  query {
      statements(filter: {destination: 1991}) {
        data {
          id
          title
          body
        }
      }
    }
`;

export default STATEMENTS_QUERY;
</code>```

答:
You could check if the results are loading, before you try to render them.

Example:

```<code>function StatementCall(context) {

  const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    // Handle error?
    return <p>{error}</p>;
  }

  return (
    <Layout>
      <div className="container">
        <div className="row spaces">
          <div className="col-md-12">
            <p>Testing</p>
            {data.statements.data.map((statement, index) => (
              <div>
                <p>{statement.id}</p>
                <p>{statement.title}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}
</code>```

Check the example in useQuery docs.

Body:
I am getting the following error after a refresh and sometimes on initial project run:

TypeError: Cannot read property 'statements' of undefined

This is really confusing because the data is rendering fine it just seems the connection fails. Any idea what may be causing the error?

There are no additional errors when I remove the statements.map

I used this medium article to get everything up and running: Medium Article

index.js:

import React, { useState, useReducer } from 'react'
import { useQuery } from '@apollo/react-hooks'

// Custom layout
import Layout from "../components/layout"

import '../sass/styles.scss'

// Data Query
import STATEMENTS_QUERY from '../graphql/statements'

function StatementCall(context) {

  const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});

  return (
    <Layout>

Testing

            {data.statements.data.map((statement, index) => (

{statement.id}

{statement.title}

            ))}

    </Layout>
  )
}

export default StatementCall

graphql/statements.js:

import gql from 'graphql-tag';

const STATEMENTS_QUERY = gql`
  query {
      statements(filter: {destination: 1991}) {
        data {
          id
          title
          body
        }
      }
    }
`;

export default STATEMENTS_QUERY;

Body:
You could check if the results are loading, before you try to render them.

Example:

function StatementCall(context) {

  const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    // Handle error?
    return <p>{error}</p>;
  }

  return (
    <Layout>
      <div className="container">
        <div className="row spaces">
          <div className="col-md-12">
            <p>Testing</p>
            {data.statements.data.map((statement, index) => (
              <div>
                <p>{statement.id}</p>
                <p>{statement.title}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Layout>
  )
}

Check the example in useQuery docs.


问:
Exe created by Exe4j with external libs dependation
We are trying to wrap our jar file with exe4j to exe file. Our jar depends on several jar libraries stored in libs folder.
We don't want to distribute jar file, only exe and jar libraries in libs folder.
For execution of application we are using own JRE.

Here is the file structure of application:

```<code>/java
/libs
application.exe
</code>```

In the project type, we are using "Jar in exe mode" option.
Exe is generated but its execution failed. In errors.log I can see, that
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
If I add slf4j.jar to classpath, generated exe is bigger and there is another NoClassDefFoundError in error.log file.

If I try "Regular mode" and specify folder with external libs - application is working well. But to specify folder is not accessible for "Jar in exe mode".

Is there any way, to have exe which wraps jar file, and uses jar libraries which are stored in external libs folder, without manual specify them and pack them to the exe?

答:
We don't want to distribute jar file, only exe and jar libraries in libs folder.

The JAR file in the generated executable is not protected in any way, because it will be extracted to the %TEMP% directory when the executable is started. This is why you can just use the regular mode and put the JAR file in the lib directory.

To protect the JAR file, use an obfuscator like proguard.

Body:
We are trying to wrap our jar file with exe4j to exe file. Our jar depends on several jar libraries stored in libs folder.
We don't want to distribute jar file, only exe and jar libraries in libs folder.
For execution of application we are using own JRE.

Here is the file structure of application:

/java
/libs
application.exe

In the project type, we are using "Jar in exe mode" option.
Exe is generated but its execution failed. In errors.log I can see, that
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
If I add slf4j.jar to classpath, generated exe is bigger and there is another NoClassDefFoundError in error.log file.

If I try "Regular mode" and specify folder with external libs - application is working well. But to specify folder is not accessible for "Jar in exe mode".

Is there any way, to have exe which wraps jar file, and uses jar libraries which are stored in external libs folder, without manual specify them and pack them to the exe?


答:
useMemo() makes the function run only when inputs change. Else it returns the memoized(cached) result. It is only suggested to use useMemo() for functions involving complex calculations(more time complexity) as there is cost in running useMemo()

useCallback() prevents the new instance of the function(I mean function is redefined) being created on each rerender and thus prevents the rerendering of child components if we pass the function as props to them

Title: What's the difference between useCallback and useMemo


问:
How can i make sound on and off using my native iPhone Application?
I want to make sound On and Off thru my Native iPhone Application so please give me some suggestion for doing that.It's only up to my Native application.</p>

答:
Are you aiming for Mute on and Off ?

Refer this thread for more info if you are aiming for it

Is it possible to programmatically mute the iPhone?


问:
Infrequent ffmpeg in Google Cloud
Which service should I use for my Go program that runs ffmpeg in Google Cloud Platform?

The Go program downloads videos from my Google Cloud Storage and runs ffmpeg command to combine them into ~5 minutes mp4 file. I use this program only around 10 times in a month.

I thought of using a compute instance with GPU to get fast ffmpeg processing. However, because of infrequency of the invocation, I don’t want to run the pricey GPU instance for all the time. Cloud Run does not seem to support GPU.

What service would you choose for such workload?

答:
As mentioned in the comments of the question, you can use Cloud Run and you would only pay for the time your code is running.

You can also use a Cloud Function. Here you have a Quickstart

Title: Infrequent ffmpeg in Google Cloud


问:
how to get a specific output from different elements of a list?
I want to get a specific output for an element which doesn't belong in a list, I wish to perform the following function:
I have defined a list(lst1) ,the program then asks for an input from the user and then converts the given integer to a list and compares the input to lst1. If the elements don't match correctly (even 1)
then the program prints that the specific element doesn't belong in the given list (example showed below):

```<code>lst1=[1,2,3]

a=int(input())

b=a.split()
</code>```

now for eg i enter 234

i wish to get an output:

```<code>'4' does not belong in lst1
</code>```

答:
The following should do the trick:

```<code>lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

for num in user_input:
    if num not in lst1:
        raise ValueError(f"{num} does not belong to lst1")
</code>```

Alternatively, you can use set difference:

```<code>lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

if len(set(user_input) - set(lst1)) > 0:
    raise ValueError("...")
</code>```

EDIT

If you want to handle multiple user inputs the following will do the trick:

```<code>lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    for num in [int(i) for i in str(_input)]:
        if num not in lst1:
            print(f"{num} does not belong to lst1")
</code>```

or

```<code>lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    num = [int(i) for i in str(_input)]

    diff = set(num) - set(lst1)
    if len(diff) > 0:
        print(f"The following numbers are invalid: {diff}")
</code>```

Body:
I want to get a specific output for an element which doesn't belong in a list, I wish to perform the following function:
I have defined a list(lst1) ,the program then asks for an input from the user and then converts the given integer to a list and compares the input to lst1. If the elements don't match correctly (even 1)
then the program prints that the specific element doesn't belong in the given list (example showed below):

lst1=[1,2,3]

a=int(input())

b=a.split()

now for eg i enter 234

i wish to get an output:

'4' does not belong in lst1

Body:
The following should do the trick:

lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

for num in user_input:
    if num not in lst1:
        raise ValueError(f"{num} does not belong to lst1")

Alternatively, you can use set difference:

lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

if len(set(user_input) - set(lst1)) > 0:
    raise ValueError("...")

EDIT

If you want to handle multiple user inputs the following will do the trick:

lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    for num in [int(i) for i in str(_input)]:
        if num not in lst1:
            print(f"{num} does not belong to lst1")

or

lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    num = [int(i) for i in str(_input)]

    diff = set(num) - set(lst1)
    if len(diff) > 0:
        print(f"The following numbers are invalid: {diff}")


问:
Given a BST and its root, print all sequences of nodes which give rise to the same bst
Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

```<code>  3
 /  \
1    5
</code>```

the answer should be 3,1,5 and 3,5,1.

another example

```<code>       5
     /   \
    4     7
   /     / \
  1     6   10
</code>```

the outputs will be

5,4,1,7,6,10

5,4,7,6,10,1

5,7,6,10,4,1

etc

The invariant here however is that the parent's index must always be lesser than its children. I am having difficulty implementing it.

答:
Note that the question is actually about topological sorting of a tree: find all the possible ways to perform topological sort. That is, we don't care about the specific way the tree was built, what's important is that elements are always added as leaves, never changing the structure of existing nodes. The constraint on the output is that nodes never precede their ancestors - treating the tree as a classic dependency graph.

But unlike topological sort for a general DAG, there's no need for reference counting here, since this is a tree - the number of references is always 1 or 0.

Here's a simple Python implementation:

    def all_toposorts_tree(sources, history):
        if not sources:
            print(history)
            return
        for t in sources:
            all_toposorts((sources - {t}) | {t.left, t.right} - {None}, history + [t.v])

    all_toposorts_tree({root}, [])
```

This is question 4.9 in Cracking the Coding Interview, 6th Edition.

Body:
Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

  3
 /  \
1    5

the answer should be 3,1,5 and 3,5,1.

another example

       5
     /   \
    4     7
   /     / \
  1     6   10

the outputs will be

5,4,1,7,6,10

5,4,7,6,10,1

5,7,6,10,4,1

etc

The invariant here however is that the parent's index must always be lesser than its children. I am having difficulty implementing it.

Body:
Note that the question is actually about topological sorting of a tree: find all the possible ways to perform topological sort. That is, we don't care about the specific way the tree was built, what's important is that elements are always added as leaves, never changing the structure of existing nodes. The constraint on the output is that nodes never precede their ancestors - treating the tree as a classic dependency graph.

But unlike topological sort for a general DAG, there's no need for reference counting here, since this is a tree - the number of references is always 1 or 0.

Here's a simple Python implementation:

    def all_toposorts_tree(sources, history):
        if not sources:
            print(history)
            return
        for t in sources:
            all_toposorts((sources - {t}) | {t.left, t.right} - {None}, history + [t.v])

    all_toposorts_tree({root}, [])

This is question 4.9 in Cracking the Coding Interview, 6th Edition.


问:
How to create a sign in method using firestore database and firebase authentication
Hi im making a app with a register page where the user enters email, password, shared secret and then a sign in page. Using firestore i store the users shared secret which works fine. I also use the firebase authentication method for email and password. The issue i have is on the sign up page using the firebase authentication signInWithEmailAndPassword method i can only call the email and password. How would i go about checking the shared secret of the user as well as the email and password?

thanks for any help

答:
The easiest way that I know how to do this is to add additional statements. I am assuming the shared secret is saved in the Realtime database. In this case, you are going to want to call that data and compare it to the user's input:

```<code>FirebaseAuth auth;
DatabaseReference secretRef; //before onCreate
private String currentUserId;
</code>```

Now for your signin method

```<code>final EditText sharedSecret = findViewById(R.id.sharedSecret); //find user input
auth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
secretRef = FirebaseDatabase.getInstance().getReference().child("User").child(currentUserId).child("sharedSecret");
final String checkedSecret = secretRef.toString();
</code>```

Then you would compare it by using code like:

```<code>if(checkedSecret != sharedSecret)
{
//user is not login
}else{
//continue with login
}
</code>```

Good luck

Body:
The easiest way that I know how to do this is to add additional statements. I am assuming the shared secret is saved in the Realtime database. In this case, you are going to want to call that data and compare it to the user's input:

FirebaseAuth auth;
DatabaseReference secretRef; //before onCreate
private String currentUserId;

Now for your signin method

final EditText sharedSecret = findViewById(R.id.sharedSecret); //find user input
auth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
secretRef = FirebaseDatabase.getInstance().getReference().child("User").child(currentUserId).child("sharedSecret");
final String checkedSecret = secretRef.toString();

Then you would compare it by using code like:

if(checkedSecret != sharedSecret)
{
//user is not login
}else{
//continue with login
}

Good luck


答:
You can do something like this:

```<code>>>> a=set([int(x) for x in raw_input()])
234
>>> [x for x in a if x not in lst1]
[4]
>>>
</code>```

You can also make lst1 a set (set(lst1)) for faster access and do something like a - lst1 as well (which results in set([4])).

EDIT:

```<code>>>> lst1 = set(lst1)
>>> for i in a - lst1:
    print (str(i) + ' does not belong to lst1')

4 does not belong to lst1
>>>
</code>```

Title: how to get a specific output from different elements of a list?

Body:
You can do something like this:

>>> a=set([int(x) for x in raw_input()])
234
>>> [x for x in a if x not in lst1]
[4]
>>>

You can also make lst1 a set (set(lst1)) for faster access and do something like a - lst1 as well (which results in set([4])).

EDIT:

>>> lst1 = set(lst1)
>>> for i in a - lst1:
    print (str(i) + ' does not belong to lst1')

4 does not belong to lst1
>>>


问:
Split list of objects into multiple lists of fields values using Java streams
Let's say I have such object:

```<code>public class Customer {

    private Integer id;
    private String country;
    private Integer customerId;
    private String name;
    private String surname;
    private Date dateOfBirth;
}
</code>```

and I have a List<Customer>. I would like to split such list with Java streams so that I would get a list of ids List<Integer>, countries List<String>, customerIds List<Integer> etc.

I know that I could do it as simple as making 6 streams such as:

```<code>List<Integer> idsList = customerList.stream()
        .map(Customer::getId)
        .collect(Collectors.toList());
</code>```

but doing it that many times that I have fields seems pretty dull. I was thinking about custom Collector but I could not come up with anything useful that would be both neat and efficient.

答:
You can create a method like so:

```<code>public <T> List<T> getByFieldName(List<Customer> customerList, Function<Customer, T> field){
    return customerList.stream()
            .map(field)
            .collect(Collectors.toList());
}
</code>```

Then just call your method with the field you want:

```<code>List<Integer> ids = getByFieldName(customerList, Customer::getId);
List<String> countries = getByFieldName(customerList, Customer::getCountry);
List<Integer> customerIds = getByFieldName(customerList, Customer::getCustomerId);
//...
</code>```

Body:
Let's say I have such object:

public class Customer {

    private Integer id;
    private String country;
    private Integer customerId;
    private String name;
    private String surname;
    private Date dateOfBirth;
}

and I have a List<Customer>. I would like to split such list with Java streams so that I would get a list of ids List<Integer>, countries List<String>, customerIds List<Integer> etc.

I know that I could do it as simple as making 6 streams such as:

List<Integer> idsList = customerList.stream()
        .map(Customer::getId)
        .collect(Collectors.toList());

but doing it that many times that I have fields seems pretty dull. I was thinking about custom Collector but I could not come up with anything useful that would be both neat and efficient.

Body:
You can create a method like so:

public <T> List<T> getByFieldName(List<Customer> customerList, Function<Customer, T> field){
    return customerList.stream()
            .map(field)
            .collect(Collectors.toList());
}

Then just call your method with the field you want:

List<Integer> ids = getByFieldName(customerList, Customer::getId);
List<String> countries = getByFieldName(customerList, Customer::getCountry);
List<Integer> customerIds = getByFieldName(customerList, Customer::getCustomerId);
//...


问:
How can I animate an element from a static layout position to an absolute layout position?
I have a form and inside this form a button. Initially the button is statically positioned at its default position based on usual layout. On an event (in the example below, button click) I want to move it to the center of the form through animation and during this animation doing a horizontal flip (using scale transform) and when the animation is in the middle (when the rendered width is 0) changing the contents of the button to a paragraph that once loaded will show an animation probably done with svg and a link.

This snippet does a part of what I want (everything until the second part of the flip with changing the contents and resizing the button to be bigger), but without an initial static position from which to start the animation:

var form = $("form")
var button = $("button")

button.on("click", function(){
  var x = (form.outerWidth() - button.outerWidth()) / 2;
  var y = (form.outerHeight() - button.outerHeight()) / 2;

  button.css({
   transform: `translateX(${x}px) translateY(${y}px) scaleX(0)`
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form {
  background: #aaa;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
  position: relative;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  position: absolute;
  left: 0;
  top: 0;

  transition: transform 1s;
}</code>```

<form>

Hello World

  <button onclick="return false;">Do something</button>
</form>```

(https://jsfiddle.net/silviubogan/L1ogpf6a/)

How can I achieve what I want in the most correct manner? Please note that the rest of the form should remain in place.

Thank you.

答:
There's two ways you can do this. First is using setTimeout (reference) with 1000ms as a parameter, since your css animation lasts 1 second, and a callback function that displays the SVG. The second is using jQuery animate (reference) instead of css, and using the parameter complete to show your SVG. Since you are already using css for the animation, let's go with the first option:

```<code>button.on("click", function(){
  // hide button
  window.setTimeout(transform2, 1000);
})

function transform2() {
  // change contents
  // resize button
}
</code>```

Example fiddle: https://jsfiddle.net/eynL91qu/

Body:
I have a form and inside this form a button. Initially the button is statically positioned at its default position based on usual layout. On an event (in the example below, button click) I want to move it to the center of the form through animation and during this animation doing a horizontal flip (using scale transform) and when the animation is in the middle (when the rendered width is 0) changing the contents of the button to a paragraph that once loaded will show an animation probably done with svg and a link.

This snippet does a part of what I want (everything until the second part of the flip with changing the contents and resizing the button to be bigger), but without an initial static position from which to start the animation:

var form = $("form")
var button = $("button")

button.on("click", function(){
  var x = (form.outerWidth() - button.outerWidth()) / 2;
  var y = (form.outerHeight() - button.outerHeight()) / 2;

  button.css({
   transform: `translateX(${x}px) translateY(${y}px) scaleX(0)`
  });
})

form {
  background: #aaa;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
  position: relative;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  position: absolute;
  left: 0;
  top: 0;

  transition: transform 1s;
}

<form>

Hello World

  <button onclick="return false;">Do something</button>
</form>

(https://jsfiddle.net/silviubogan/L1ogpf6a/)

How can I achieve what I want in the most correct manner? Please note that the rest of the form should remain in place.

Thank you.

Body:
There's two ways you can do this. First is using setTimeout (reference) with 1000ms as a parameter, since your css animation lasts 1 second, and a callback function that displays the SVG. The second is using jQuery animate (reference) instead of css, and using the parameter complete to show your SVG. Since you are already using css for the animation, let's go with the first option:

button.on("click", function(){
  // hide button
  window.setTimeout(transform2, 1000);
})

function transform2() {
  // change contents
  // resize button
}

Example fiddle: https://jsfiddle.net/eynL91qu/


问:
Pure CSS Loading indicator fit to container size
I want to use the following loading indicator for containers while data is being loaded.
The problem is, that the slider has a fixed width and height (300px & 300px), but I want it to fit dynamically into a container. When I try to add width: 140px; and height: 140px; to the main-container class the loading indicator looks awful and the proportions are not correct.

EDIT by Rickard

I added a slider and border so it's easier to see what's going wrong.

let sliderElement = document.getElementById("slider");
let mainContainerDiv = document.querySelector(".main-container");

sliderElement.oninput = function() {
  changeContainerSize(this.value);
}

function changeContainerSize(value) {
  mainContainerDiv.style.width = value + "px";
  mainContainerDiv.style.height = value + "px";
}

changeContainerSize(sliderElement.value);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-container {
  border: 1px solid; /* for demo purpose :: Rickard */
}
.reverse-spinner {
  position: relative;
  height: 100px;
  width: 100px;
  border: 4px solid transparent;
  border-top-color: #1976d2;
  border-left-color: #1976d2;
  border-radius: 50%;
  -webkit-animation: spin 1.5s linear infinite;
  animation: spin 1.5s linear infinite;
}
.reverse-spinner::before {
  position: absolute;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
  content: "";
  border: 4px solid transparent;
  border-top-color: #03a9f4;
  border-left-color: #03a9f4;
  border-radius: 50%;
  -webkit-animation: spinBack 1s linear infinite;
  animation: spinBack 1s linear infinite;
}

.flexbox {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.flexbox > div {
  width: 140px;
  height: 140px;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border: 2px dashed green; /* for demo purpose :: Rickard */
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  overflow: hidden;
}

-webkit-@keyframes spin {
  -webkit-from {
    -webkit-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  -webkit-to {
    -webkit-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-webkit-keyframes spinBack {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(-720deg);
    transform: rotate(-720deg);
  }
}

@keyframes spinBack {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(-720deg);
    transform: rotate(-720deg);
  }
}</code>```

<input id="slider" type="range" min="100" max="500" value="500">

```

答:
Alternatively, you can make a loader using SVG. In which to set viewBox =" 0 0 140 140 "
Wrap the div loader and set the width of the parent container as a percentage.

In the example below,  uses the same id = "loader" loader in three containers

 with dimensions: width: 10%, width: 20%, width: 30%

.reverse-spinner {
display: inline-block;
}
.container {
width:100vw;
height:100vh;
background:#EAEAEA;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container" >
     <!-- Container width:10% -->
<div class="reverse-spinner" style="width:10%; background-color:gold; " >
 <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
 <g id="loader" >
    <circle cx="70" cy="70" r="60" fill="none" stroke="#1976D2" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="188.4" stroke-linecap="round" >
      <animate attributeName="stroke-dashoffset" begin="0s" dur="1.5s" values="0;376.8" repeatCount="indefinite" />
 </circle>
   <circle cx="70" cy="70" r="40" fill="none" stroke="#03A9F4" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="125.5" stroke-linecap="round" >
      <animate attributeName="stroke-dashoffset" begin="0s" dur="1s" values="251.2;0" repeatCount="indefinite" />
 </circle>
  </g>
</svg>
</div>
         <!-- Container width:20% -->
<div class="reverse-spinner" style="width:20%; background:#31C1B0;">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
     <use xlink:href="#loader" > </use>
  </svg>
</div>
            <!-- Container width:30% -->
  <div class="reverse-spinner" style="width:30%; background:#FFA6E3;">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
       <use xlink:href="#loader" > </use>
</svg>
</div>
</div></code>```

This example uses input to dynamically change the width of the parent container:

.container {
width: var(--w1,40px);
background:#EAEAEA;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<input type="range" min="40" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="50"><span>width Container</span><br>
</div>
<div class="container" >

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140" style="border:1px solid;" >
 <g id="loader" >
<circle cx="70" cy="70" r="60" fill="none" stroke="#1976D2" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="188.4" stroke-linecap="round" >
   <animate attributeName="stroke-dashoffset" begin="0s" dur="1.5s" values="0;376.8" repeatCount="indefinite" />
 </circle>
   <circle cx="70" cy="70" r="40" fill="none" stroke="#03A9F4" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="125.5" stroke-linecap="round" >
    <animate attributeName="stroke-dashoffset" begin="0s" dur="1s" values="251.2;0" repeatCount="indefinite" />
 </circle>
  </g>
</svg>
</div> </code>```

UPDATE

Added another example with text wrapping around the parent container.

This example further demonstrates the adaptability of filling a parent container with an SVG application.

.container {
width: var(--w1,60px);
background:#EAEAEA;
 float:left;
 margin-right: 1em;
}
.txt {
font-size:1.2em;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cont" >
<input type="range" min="60" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="60">
</div>
<div class="container" >
<svg  viewBox="0 0 120 120">

<defs>
  <mask id="msk1">
      <circle class="maskCircle" cx="60" cy="60" r="40" fill="none" stroke="white" stroke-width="8" stroke-dashoffset="0" stroke-dasharray="251.2">
      <animate attributeName="stroke-dashoffset" dur="3s" values="251.2;0" fill="freeze" repeatCount="indefinite" />
  </circle>
  </mask>
</defs>
    <circle class="background" cx="60" cy="60" r="40" fill="none" stroke="#E4E4E4" stroke-width="8" />
  <circle class="default" cx="60" cy="60" r="40" fill="none" stroke="black" stroke-width="8"
  stroke-dasharray="3.14" stroke-dashoffset="40"  mask="url(#msk1)">

  </circle>
</svg>
</div>
<div class="txt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt dignissim nibh a facilisis. Phasellus pretium nisl vel turpis suscipit, quis posuere quam laoreet. Vestibulum fringilla porttitor felis, non lacinia dolor mattis vitae. Donec gravida et purus eu pellentesque. Nam consequat nisl id velit interdum eleifend. Mauris nulla turpis, sollicitudin in vestibulum nec, ornare quis lacus. Proin eros diam, lacinia id blandit a, efficitur eget mauris. Morbi ullamcorper velit non urna malesuada molestie. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vehicula est non nunc ultricies, sit amet pharetra nulla congue. Vestibulum hendrerit ante ac rhoncus aliquet. Quisque vitae est turpis. Nulla sit amet felis nec nisl blandit mollis.

Nullam ornare turpis quis orci hendrerit, vitae varius est tincidunt. In quis malesuada tellus. Aliquam nunc mauris, aliquam quis lectus ut, ultrices lobortis ante. Maecenas tincidunt ligula felis, in consequat lectus finibus eget. Maecenas molestie placerat odio, at malesuada risus consequat id. Integer congue facilisis enim porta pretium. Morbi scelerisque tincidunt purus, vitae rhoncus tortor tristique nec. Nullam laoreet turpis nec felis vehicula finibus.

Fusce ultricies maximus ante vitae imperdiet. Proin magna orci, pretium nec pretium id, ultricies in risus. Praesent mauris ipsum, semper nec convallis sit amet, vestibulum non enim. Quisque volutpat nulla ac nulla venenatis, ac cursus nulla laoreet. Aliquam malesuada dui a orci tristique tristique. Phasellus fringilla, velit eget ultrices efficitur, justo lacus elementum lorem, nec convallis augue lacus non dui. Aliquam erat volutpat. Mauris sagittis, sapien in tristique mollis, ex libero laoreet magna, ut pellentesque dolor augue accumsan elit. Nunc ut augue at eros sollicitudin malesuada. Pellentesque urna felis, posuere sit amet odio et, vestibulum aliquet ex. Nulla eu dolor blandit, bibendum nibh in, tincidunt ex. Ut nisl justo, tincidunt a augue et, gravida sollicitudin neque. Donec id dignissim elit, a sollicitudin leo. Aliquam placerat orci justo, et faucibus nibh volutpat vel.

Nulla varius, est eu dictum vulputate, risus tellus euismod augue, ac tempus velit elit nec dui. Duis eleifend metus eu nisi mattis scelerisque. Proin finibus neque ut pellentesque porta. Etiam quis ligula non ligula sollicitudin efficitur at a turpis. Morbi tristique maximus quam eu imperdiet. Morbi dolor augue, sagittis non urna quis, fringilla scelerisque erat. Praesent et tempor tortor. In hac habitasse platea dictumst. Sed ut consectetur arcu, id vestibulum sapien. Integer in metus et lacus sollicitudin sollicitudin. Curabitur vulputate mollis odio, sit amet dictum mauris condimentum non. Vestibulum enim risus, luctus a tristique sit amet, semper non enim. Nunc laoreet hendrerit massa at blandit.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris dapibus eu ipsum ac semper. Suspendisse turpis nunc, mattis sit amet lorem id, fringilla iaculis purus. Praesent egestas est id ullamcorper tristique. Nulla tempus sem rutrum, sagittis dui quis, condimentum massa. Nam efficitur purus sed sapien euismod imperdiet. Donec laoreet augue eget justo dapibus suscipit. Etiam eleifend neque iaculis, pellentesque elit vel, malesuada justo. Aenean efficitur eros quis mattis convallis. Quisque hendrerit libero ligula, vel fermentum orci ultrices vel. In porttitor congue interdum. Duis ac vehicula est. Nullam sollicitudin eros a tortor semper, laoreet facilisis neque hendrerit. Integer faucibus elementum nibh, id venenatis urna consectetur a.
</div></code>```

Body:
I want to use the following loading indicator for containers while data is being loaded.
The problem is, that the slider has a fixed width and height (300px & 300px), but I want it to fit dynamically into a container. When I try to add width: 140px; and height: 140px; to the main-container class the loading indicator looks awful and the proportions are not correct.

EDIT by Rickard

I added a slider and border so it's easier to see what's going wrong.

let sliderElement = document.getElementById("slider");
let mainContainerDiv = document.querySelector(".main-container");

sliderElement.oninput = function() {
  changeContainerSize(this.value);
}

function changeContainerSize(value) {
  mainContainerDiv.style.width = value + "px";
  mainContainerDiv.style.height = value + "px";
}

changeContainerSize(sliderElement.value);

.main-container {
  border: 1px solid; /* for demo purpose :: Rickard */
}
.reverse-spinner {
  position: relative;
  height: 100px;
  width: 100px;
  border: 4px solid transparent;
  border-top-color: #1976d2;
  border-left-color: #1976d2;
  border-radius: 50%;
  -webkit-animation: spin 1.5s linear infinite;
  animation: spin 1.5s linear infinite;
}
.reverse-spinner::before {
  position: absolute;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
  content: "";
  border: 4px solid transparent;
  border-top-color: #03a9f4;
  border-left-color: #03a9f4;
  border-radius: 50%;
  -webkit-animation: spinBack 1s linear infinite;
  animation: spinBack 1s linear infinite;
}

.flexbox {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.flexbox > div {
  width: 140px;
  height: 140px;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border: 2px dashed green; /* for demo purpose :: Rickard */
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  overflow: hidden;
}

-webkit-@keyframes spin {
  -webkit-from {
    -webkit-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  -webkit-to {
    -webkit-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@-webkit-keyframes spinBack {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(-720deg);
    transform: rotate(-720deg);
  }
}

@keyframes spinBack {
  from {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(-720deg);
    transform: rotate(-720deg);
  }
}

<input id="slider" type="range" min="100" max="500" value="500">

Body:
Alternatively, you can make a loader using SVG. In which to set viewBox =" 0 0 140 140 "
Wrap the div loader and set the width of the parent container as a percentage.

In the example below,  uses the same id = "loader" loader in three containers
<div class = "reverse-spinner"> with dimensions: width: 10%, width: 20%, width: 30%

.reverse-spinner {
display: inline-block;
}
.container {
width:100vw;
height:100vh;
background:#EAEAEA;
}

<div class="container" >
     <!-- Container width:10% -->
<div class="reverse-spinner" style="width:10%; background-color:gold; " >
 <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
 <g id="loader" >
    <circle cx="70" cy="70" r="60" fill="none" stroke="#1976D2" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="188.4" stroke-linecap="round" >
      <animate attributeName="stroke-dashoffset" begin="0s" dur="1.5s" values="0;376.8" repeatCount="indefinite" />
 </circle>
   <circle cx="70" cy="70" r="40" fill="none" stroke="#03A9F4" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="125.5" stroke-linecap="round" >
      <animate attributeName="stroke-dashoffset" begin="0s" dur="1s" values="251.2;0" repeatCount="indefinite" />
 </circle>
  </g>
</svg>
</div>
         <!-- Container width:20% -->
<div class="reverse-spinner" style="width:20%; background:#31C1B0;">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
     <use xlink:href="#loader" > </use>
  </svg>
</div>
            <!-- Container width:30% -->
  <div class="reverse-spinner" style="width:30%; background:#FFA6E3;">
    <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140"  >
       <use xlink:href="#loader" > </use>
</svg>
</div>
</div>

This example uses input to dynamically change the width of the parent container:

.container {
width: var(--w1,40px);
background:#EAEAEA;

}

<div>
<input type="range" min="40" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="50"><span>width Container</span><br>
</div>
<div class="container" >

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
         viewBox="0 0 140 140" style="border:1px solid;" >
 <g id="loader" >
<circle cx="70" cy="70" r="60" fill="none" stroke="#1976D2" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="188.4" stroke-linecap="round" >
   <animate attributeName="stroke-dashoffset" begin="0s" dur="1.5s" values="0;376.8" repeatCount="indefinite" />
 </circle>
   <circle cx="70" cy="70" r="40" fill="none" stroke="#03A9F4" stroke-width="4" stroke-dashoffset="0" stroke-dasharray="125.5" stroke-linecap="round" >
    <animate attributeName="stroke-dashoffset" begin="0s" dur="1s" values="251.2;0" repeatCount="indefinite" />
 </circle>
  </g>
</svg>
</div>

UPDATE

Added another example with text wrapping around the parent container.

This example further demonstrates the adaptability of filling a parent container with an SVG application.

.container {
width: var(--w1,60px);
background:#EAEAEA;
 float:left;
 margin-right: 1em;
}
.txt {
font-size:1.2em;

}

<div class="cont" >
<input type="range" min="60" max="600" oninput="document.querySelector('.container').style.setProperty('--w1', this.value + 'px');" value="60">
</div>
<div class="container" >
<svg  viewBox="0 0 120 120">

<defs>
  <mask id="msk1">
      <circle class="maskCircle" cx="60" cy="60" r="40" fill="none" stroke="white" stroke-width="8" stroke-dashoffset="0" stroke-dasharray="251.2">
      <animate attributeName="stroke-dashoffset" dur="3s" values="251.2;0" fill="freeze" repeatCount="indefinite" />
  </circle>
  </mask>
</defs>
    <circle class="background" cx="60" cy="60" r="40" fill="none" stroke="#E4E4E4" stroke-width="8" />
  <circle class="default" cx="60" cy="60" r="40" fill="none" stroke="black" stroke-width="8"
  stroke-dasharray="3.14" stroke-dashoffset="40"  mask="url(#msk1)">

  </circle>
</svg>
</div>
<div class="txt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tincidunt dignissim nibh a facilisis. Phasellus pretium nisl vel turpis suscipit, quis posuere quam laoreet. Vestibulum fringilla porttitor felis, non lacinia dolor mattis vitae. Donec gravida et purus eu pellentesque. Nam consequat nisl id velit interdum eleifend. Mauris nulla turpis, sollicitudin in vestibulum nec, ornare quis lacus. Proin eros diam, lacinia id blandit a, efficitur eget mauris. Morbi ullamcorper velit non urna malesuada molestie. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec vehicula est non nunc ultricies, sit amet pharetra nulla congue. Vestibulum hendrerit ante ac rhoncus aliquet. Quisque vitae est turpis. Nulla sit amet felis nec nisl blandit mollis.

Nullam ornare turpis quis orci hendrerit, vitae varius est tincidunt. In quis malesuada tellus. Aliquam nunc mauris, aliquam quis lectus ut, ultrices lobortis ante. Maecenas tincidunt ligula felis, in consequat lectus finibus eget. Maecenas molestie placerat odio, at malesuada risus consequat id. Integer congue facilisis enim porta pretium. Morbi scelerisque tincidunt purus, vitae rhoncus tortor tristique nec. Nullam laoreet turpis nec felis vehicula finibus.

Fusce ultricies maximus ante vitae imperdiet. Proin magna orci, pretium nec pretium id, ultricies in risus. Praesent mauris ipsum, semper nec convallis sit amet, vestibulum non enim. Quisque volutpat nulla ac nulla venenatis, ac cursus nulla laoreet. Aliquam malesuada dui a orci tristique tristique. Phasellus fringilla, velit eget ultrices efficitur, justo lacus elementum lorem, nec convallis augue lacus non dui. Aliquam erat volutpat. Mauris sagittis, sapien in tristique mollis, ex libero laoreet magna, ut pellentesque dolor augue accumsan elit. Nunc ut augue at eros sollicitudin malesuada. Pellentesque urna felis, posuere sit amet odio et, vestibulum aliquet ex. Nulla eu dolor blandit, bibendum nibh in, tincidunt ex. Ut nisl justo, tincidunt a augue et, gravida sollicitudin neque. Donec id dignissim elit, a sollicitudin leo. Aliquam placerat orci justo, et faucibus nibh volutpat vel.

Nulla varius, est eu dictum vulputate, risus tellus euismod augue, ac tempus velit elit nec dui. Duis eleifend metus eu nisi mattis scelerisque. Proin finibus neque ut pellentesque porta. Etiam quis ligula non ligula sollicitudin efficitur at a turpis. Morbi tristique maximus quam eu imperdiet. Morbi dolor augue, sagittis non urna quis, fringilla scelerisque erat. Praesent et tempor tortor. In hac habitasse platea dictumst. Sed ut consectetur arcu, id vestibulum sapien. Integer in metus et lacus sollicitudin sollicitudin. Curabitur vulputate mollis odio, sit amet dictum mauris condimentum non. Vestibulum enim risus, luctus a tristique sit amet, semper non enim. Nunc laoreet hendrerit massa at blandit.

Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Mauris dapibus eu ipsum ac semper. Suspendisse turpis nunc, mattis sit amet lorem id, fringilla iaculis purus. Praesent egestas est id ullamcorper tristique. Nulla tempus sem rutrum, sagittis dui quis, condimentum massa. Nam efficitur purus sed sapien euismod imperdiet. Donec laoreet augue eget justo dapibus suscipit. Etiam eleifend neque iaculis, pellentesque elit vel, malesuada justo. Aenean efficitur eros quis mattis convallis. Quisque hendrerit libero ligula, vel fermentum orci ultrices vel. In porttitor congue interdum. Duis ac vehicula est. Nullam sollicitudin eros a tortor semper, laoreet facilisis neque hendrerit. Integer faucibus elementum nibh, id venenatis urna consectetur a.
</div>


问:
How do I change font awesome icon and button class onclick?
How do I change button class and font-awesome icon onclick? When I click on the button the class and icon should be changed and vice versa.

<button type="button" id="btn_hideshow" data-id="{{$user->id}}" class="btn btn-primary btn-sm btn_hideshow">

</button>
```

<pre class="lang-js prettyprint-override"><code>$(function() {
  $(".btn_hideshow").click(function() {
    let id = $(this).data('id');
    $.ajax({
      url: "/user-hide-show/" + id,
      method: "POST",
      data: {
        'id': id
      },
      dataType: "json",
      success: function(data) {
        if ($("button#btn_hideshow").hasClass() == "btn btn-primary btn-sm") {
          $("button#btn_hideshow").removeClass("btn btn-primary btn-sm").addClass("btn btn-info btn-sm")
            .append().html("<i class='fa fa-eye-slash'><i/>")
        } else {
          $("button#hideAndShow").removeClass("btn btn-info btn-sm").addClass("btn btn-primary btn-sm").append().html("<i class='fa fa-eye'><i/>")
        }
      }
    });
  });
});
</code>```

答:
Assuming your AJAX call is working then the issue is in the if statement. hasClass() returns a boolean value, yet you're trying to compare that to the class string to search for. Instead the string needs to be provided as an argument to the function, eg:

```<code>if ($("button#btn_hideshow").hasClass("btn-primary") {
</code>```

That being said, there's a better way to do what you require.

As the btn and btn-sm classes are always present on the element they can be removed from your logic. All you then need to do is toggle the btn-primary and btn-info classes on the button. Similarly the child  element can be kept instead of removed/re-added, and the fa-eye and fa-eye-slash classes can be toggled. As such, try this:

```<code>// outside AJAX callback:
let $button = $("#btn_hideshow");

// inside AJAX callback:
$button.toggleClass('btn-primary btn-info').find('i').toggleClass('fa-eye-slash fa-eye')
</code>```

Body:
How do I change button class and font-awesome icon onclick? When I click on the button the class and icon should be changed and vice versa.

<button type="button" id="btn_hideshow" data-id="{{$user->id}}" class="btn btn-primary btn-sm btn_hideshow">

</button>

$(function() {
  $(".btn_hideshow").click(function() {
    let id = $(this).data('id');
    $.ajax({
      url: "/user-hide-show/" + id,
      method: "POST",
      data: {
        'id': id
      },
      dataType: "json",
      success: function(data) {
        if ($("button#btn_hideshow").hasClass() == "btn btn-primary btn-sm") {
          $("button#btn_hideshow").removeClass("btn btn-primary btn-sm").addClass("btn btn-info btn-sm")
            .append().html("")
        } else {
          $("button#hideAndShow").removeClass("btn btn-info btn-sm").addClass("btn btn-primary btn-sm").append().html("")
        }
      }
    });
  });
});

Body:
Assuming your AJAX call is working then the issue is in the if statement. hasClass() returns a boolean value, yet you're trying to compare that to the class string to search for. Instead the string needs to be provided as an argument to the function, eg:

if ($("button#btn_hideshow").hasClass("btn-primary") {

That being said, there's a better way to do what you require.

As the btn and btn-sm classes are always present on the element they can be removed from your logic. All you then need to do is toggle the btn-primary and btn-info classes on the button. Similarly the child <i> element can be kept instead of removed/re-added, and the fa-eye and fa-eye-slash classes can be toggled. As such, try this:

// outside AJAX callback:
let $button = $("#btn_hideshow");

// inside AJAX callback:
$button.toggleClass('btn-primary btn-info').find('i').toggleClass('fa-eye-slash fa-eye')


问:
Spatial index/query (finding k nearest points)
I have +10k points (latitude, longitude) and I'm building an app that shows you the k nearest points to a user's location.

I think this is a very common problem and I don't want to reinvent the wheel. I'm learning about Quadtrees. It seems to be a good approach to solve this spatial problem.

I'm using these tools:

Python 2.5

MySQL

MongoDb

Building the Quadtree is not that hard: http://donar.umiacs.umd.edu/quadtree/points/pointquad.html But once I've created the tree and saved it to a db (MySQL or MongoDb), how I run the query?

I need to run queries like these:

Find all points within 10 km of the user's location.

Find the 6 (or at least 6) nearest points to the
user's location.

What's the standard and common approach to do it?

EDIT 1:

I've loaded the +10k points into MongoDB (Geospatial indexing) and it works fine at first glance. Anyway I've found PostGis:

PostGIS is an extension to the PostgreSQL object-relational database system which allows GIS (Geographic Information Systems) objects to be stored in the database.

So I think I'll give PostGis a try.

I've also found SimpleGeo. You can store points/places in the cloud and then query them via an API: https://simplegeo.com/docs/tutorials/python#how-do-radial-nearby-query

答:
MongoDB has support for spatial indexes built-in, so all you'd need to do is load your points using the correct format, create the spatial index, and then run your queries.

For a quick example, I loaded the center points for all 50 states in the mongo shell:

```<code>> db.places.ensureIndex({loc: "2d"})
> db.places.save({name: "AK", loc: {long: -152.2683, lat: 61.3850}})
> db.places.save({name: "AL", loc: {long: -86.8073, lat: 32.7990}})
> db.places.save({name: "AR", loc: {long: -92.3809, lat: 34.9513}})
> db.places.save({name: "AS", loc: {long: -170.7197, lat: 14.2417}})
> ...
</code>```

Next, to query for the 6 nearest points to a given location:

```<code>> db.places.find({loc: { $near: {long: -90, lat: 50}}}).limit(6)
{"name" : "WI", "loc" : { "long" : -89.6385, "lat" : 44.2563 } }
{"name" : "MN", "loc" : { "long" : -93.9196, "lat" : 45.7326 } }
{"name" : "MI", "loc" : { "long" : -84.5603, "lat" : 43.3504 } }
{"name" : "IA", "loc" : { "long" : -93.214, "lat" : 42.0046 } }
{"name" : "IL", "loc" : { "long" : -89.0022, "lat" : 40.3363 } }
{"name" : "ND", "loc" : { "long" : -99.793, "lat" : 47.5362 } }
</code>```

Next, to query for all points within 10km of a given location. Since I'm calculating the nearest states, I'll use 888km (which is approximately 8 degrees of latitude):

```<code>> db.places.find({loc: { $near: {long: -90, lat: 50}, $maxDistance: 8}})
{"name" : "WI", "loc" : { "long" : -89.6385, "lat" : 44.2563 } }
{"name" : "MN", "loc" : { "long" : -93.9196, "lat" : 45.7326 } }
</code>```

Since one degree of latitude is approximately 111.12km, you'd use a $maxDistance: 0.08999 to represent 10km for your application.

Updated By default MongoDB assumes an "idealized flat earth model" but this results in inaccuracies since longitude lines converge at the poles.  MongoDB versions 1.7+ support spherical distance calculations, which provides the increased precision.

Here is an example of running the above query using spherical distance. the maxDistance is in radians, so we need to divide by the earth's average radius:

```<code>> db.runCommand({geoNear: "places", near: [-90, 50], spherical: true,
                 maxDistance: 800/6378});
(summarizing results as they're too verbose to include)
"MN"  dis: 0.087..
"WI"  dis: 0.100..
"ND"  dis: 0.120..
</code>```

Body:
MongoDB has support for spatial indexes built-in, so all you'd need to do is load your points using the correct format, create the spatial index, and then run your queries.

For a quick example, I loaded the center points for all 50 states in the mongo shell:

> db.places.ensureIndex({loc: "2d"})
> db.places.save({name: "AK", loc: {long: -152.2683, lat: 61.3850}})
> db.places.save({name: "AL", loc: {long: -86.8073, lat: 32.7990}})
> db.places.save({name: "AR", loc: {long: -92.3809, lat: 34.9513}})
> db.places.save({name: "AS", loc: {long: -170.7197, lat: 14.2417}})
> ...

Next, to query for the 6 nearest points to a given location:

> db.places.find({loc: { $near: {long: -90, lat: 50}}}).limit(6)
{"name" : "WI", "loc" : { "long" : -89.6385, "lat" : 44.2563 } }
{"name" : "MN", "loc" : { "long" : -93.9196, "lat" : 45.7326 } }
{"name" : "MI", "loc" : { "long" : -84.5603, "lat" : 43.3504 } }
{"name" : "IA", "loc" : { "long" : -93.214, "lat" : 42.0046 } }
{"name" : "IL", "loc" : { "long" : -89.0022, "lat" : 40.3363 } }
{"name" : "ND", "loc" : { "long" : -99.793, "lat" : 47.5362 } }

Next, to query for all points within 10km of a given location. Since I'm calculating the nearest states, I'll use 888km (which is approximately 8 degrees of latitude):

> db.places.find({loc: { $near: {long: -90, lat: 50}, $maxDistance: 8}})
{"name" : "WI", "loc" : { "long" : -89.6385, "lat" : 44.2563 } }
{"name" : "MN", "loc" : { "long" : -93.9196, "lat" : 45.7326 } }

Since one degree of latitude is approximately 111.12km, you'd use a $maxDistance: 0.08999 to represent 10km for your application.

Updated By default MongoDB assumes an "idealized flat earth model" but this results in inaccuracies since longitude lines converge at the poles.  MongoDB versions 1.7+ support spherical distance calculations, which provides the increased precision.

Here is an example of running the above query using spherical distance. the maxDistance is in radians, so we need to divide by the earth's average radius:

> db.runCommand({geoNear: "places", near: [-90, 50], spherical: true,
                 maxDistance: 800/6378});
(summarizing results as they're too verbose to include)
"MN"  dis: 0.087..
"WI"  dis: 0.100..
"ND"  dis: 0.120..


问:
Sorting of list by matching the 'input' lists in Python
I have a (probably quite simple) problem I cannot figure out in Python.

Say I have a list
X1 = [1,2,3]
with the corresponding list
Y1 = [5,6,7]
and a list
X2 = [2,1,3]
with corresponding list
Y2 = [8,9,10]
where X1 and X2 contain the same values but in different order. How can I match the order of X2 to that of X1, while the X2 Y2 pairs remain intact? The answer should be then Y2 = [9,8,10].

Thank you in advance!

答:
You can do something like this:

```<code>[Y2[X1.index(x)] for x in X2]
</code>```

This has a O(n^2) time complexity, if you build a dictionary with X1's indices before, you can get O(n) time complexity:

```<code>d = {x: i for i, x in enumerate(X1)}
[Y2[d[x]] for x in X2]
</code>```

Body:
You can do something like this:

[Y2[X1.index(x)] for x in X2]

This has a O(n^2) time complexity, if you build a dictionary with X1's indices before, you can get O(n) time complexity:

d = {x: i for i, x in enumerate(X1)}
[Y2[d[x]] for x in X2]


问:
What is the best way to send a GET request to the server in vanilla JavaScript?
What is the best way to send a GET request to the server in vanilla JavaScript?</p>

答:
You can do a redirection to do a synchronous GET request:</p>

```<code>var url = 'http://domain/path/?var1=&var2=';

window.location = url;
</code>```

Body:
You can do a redirection to do a synchronous GET request:

var url = 'http://domain/path/?var1=&var2=';

window.location = url;


问:
PHP check "variable variables" isset
For normal variables I can use isset($var) to check if it is set.

How to check if a variable variable (a variable that have the name stored in another variable) is set?

答:
I found the solution with this:</p>

```<code>if(isset(${$variable_name})...
</code>```

Title: PHP check "variable variables" isset

Body:
I found the solution with this:

if(isset(${$variable_name})...


答:
```<code>    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", THE_URL, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
</code>```

Title: What is the best way to send a GET request to the server in vanilla JavaScript?


问:
C# JSON Data wrongly manipulated after import
Hello (im a noob so please correct me if im using the wrong terms),

I have a problem with a JSON file that im trying to import using StreamReader which looks like the following:

```<code>    public List<Category> Items;

        try
        {
            using (var r =
                new StreamReader(
                    FilePath1)
            )
            {
                var json = r.ReadToEnd();
                Items = JsonConvert.DeserializeObject<List<Category>>(json);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(Convert.ToString(e), "Error");
            Environment.Exit(1);
        }
</code>```

This exact code worked for me before and the list should hold the following data:

```<code>[
  {
    "name": "Elektronik",
    "subcategories": [
      {
        "name": "Elektrotechnische Physik",
        "questions": [
          {
            **"question": "Wie ändert sich die Anzahl der freien Elektronen vor und nach dem Schließen eines Stromkreises innerhalb eines Leiters?"**,
            "answer": "Die Anzahl bleibt gleich.",
            "answers": [
              "Die Anzahl verringert sich.",
              "Die Anzahl bleibt gleich.",
              "Die Anzahl erhöht sich.",
              "Es gibt keine freien Elektronen in einem Leiter."
            ]
          }, .....
</code>```

The bold part is the problematic one because the list actually holds the following data:

```<code>[
  {
    "name": "Elektronik",
    "subcategories": [
      {
        "name": "Elektrotechnische Physik",
        "questions": [
          {
            **"SubQuestion": null**,
            "answer": "Die Anzahl bleibt gleich.",
            "answers": [
              "Die Anzahl verringert sich.",
              "Die Anzahl bleibt gleich.",
              "Die Anzahl erhöht sich.",
              "Es gibt keine freien Elektronen in einem Leiter."
            ]
          },
</code>```

It deletes all questions and replaces it with "SubQuestion = null". Does anyone know why or know how to help me?

Thanks!

答:
Looks like the property name in your json does not match the property name in your model. Your model's likely look like below ... with the exception of Question, which appears to  have a property called "SubQuestion" instead of "question". If that is your intent, as Colin mentioned, you could put a json property on it so that the json can be mapped to the correct property.</p>

```<code>public class Category
{
    public string name { get; set; }
    public Subcategory[] subcategories { get; set; }
}

public class Subcategory
{
    public string name { get; set; }
    public Question[] questions { get; set; }
}

public class Question
{
    public string question { get; set; }
    public string answer { get; set; }
    public string[] answers { get; set; }
}
</code>```

Body:
Hello (im a noob so please correct me if im using the wrong terms),

I have a problem with a JSON file that im trying to import using StreamReader which looks like the following:

    public List<Category> Items;

        try
        {
            using (var r =
                new StreamReader(
                    FilePath1)
            )
            {
                var json = r.ReadToEnd();
                Items = JsonConvert.DeserializeObject<List<Category>>(json);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(Convert.ToString(e), "Error");
            Environment.Exit(1);
        }

This exact code worked for me before and the list should hold the following data:

[
  {
    "name": "Elektronik",
    "subcategories": [
      {
        "name": "Elektrotechnische Physik",
        "questions": [
          {
            **"question": "Wie ändert sich die Anzahl der freien Elektronen vor und nach dem Schließen eines Stromkreises innerhalb eines Leiters?"**,
            "answer": "Die Anzahl bleibt gleich.",
            "answers": [
              "Die Anzahl verringert sich.",
              "Die Anzahl bleibt gleich.",
              "Die Anzahl erhöht sich.",
              "Es gibt keine freien Elektronen in einem Leiter."
            ]
          }, .....

The bold part is the problematic one because the list actually holds the following data:

[
  {
    "name": "Elektronik",
    "subcategories": [
      {
        "name": "Elektrotechnische Physik",
        "questions": [
          {
            **"SubQuestion": null**,
            "answer": "Die Anzahl bleibt gleich.",
            "answers": [
              "Die Anzahl verringert sich.",
              "Die Anzahl bleibt gleich.",
              "Die Anzahl erhöht sich.",
              "Es gibt keine freien Elektronen in einem Leiter."
            ]
          },

It deletes all questions and replaces it with "SubQuestion = null". Does anyone know why or know how to help me?

Thanks!

Body:
Looks like the property name in your json does not match the property name in your model. Your model's likely look like below ... with the exception of Question, which appears to  have a property called "SubQuestion" instead of "question". If that is your intent, as Colin mentioned, you could put a json property on it so that the json can be mapped to the correct property.

public class Category
{
    public string name { get; set; }
    public Subcategory[] subcategories { get; set; }
}

public class Subcategory
{
    public string name { get; set; }
    public Question[] questions { get; set; }
}

public class Question
{
    public string question { get; set; }
    public string answer { get; set; }
    public string[] answers { get; set; }
}