问:
Regex pattern that contains a limited set of special characters
The requirements I've been set are...

MUST match (1 minimum character/number):

1 number (?=.*\d)

1 lower case character (?=.*[a-z])

1 upper case character (?=.*[A-Z])

no whitespace (?!.*\s)

Between 8 and 40 characters .{8,40}

CAN match, but doesn't have to:

Special characters limited to $*%!.,^

This is what I have so far: /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,40}/

I'd like to keep it segmented out the way I do for readability - Unless there's a reason not to?!  Happy to change if there are any performance benefits, or if I've done something silly/pointless?

The above works for the most part, including my special characters.  However, when I type in a "restricted" character, such as @, it still matches.

I'm a bit lost, so any help would be very much appreciated!  Thank you!

Examples of what SHOULD match:

abcABC123

aaBB33!!

!a*Bc9!.abBC*4

Examples of what SHOULD NOT match:

abc ABC 123

abc@ABC?123

áááBBB333

Restrictions:

Anything that is NOT a-z A-Z 0-9 or $*%!.,^ is considered a restricted character

答:
You can use:

```<code>^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[a-zA-Z\d$*%!.,^]{8,40}$
</code>```

^(?=\D*\d) - require a digit somewhere

(?=[^a-z]*[a-z]) - require a lowercase char somewhere

(?=[^A-Z]*[A-Z]) - require a uppercase char somewhere

[a-zA-Z\d$*%!.,^]{8,40}$ - from start to finish require 8 to 40 of these whitelisted chars in any order

Test your strings one at a time at https://regex101.com/r/lrABwJ/1

Body:
You can use:

^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])[a-zA-Z\d$*%!.,^]{8,40}$

^(?=\D*\d) - require a digit somewhere

(?=[^a-z]*[a-z]) - require a lowercase char somewhere

(?=[^A-Z]*[A-Z]) - require a uppercase char somewhere

[a-zA-Z\d$*%!.,^]{8,40}$ - from start to finish require 8 to 40 of these whitelisted chars in any order

Test your strings one at a time at https://regex101.com/r/lrABwJ/1


来源: stackexchange

问:
data passing in navigation based application
i am working on a navigation based application
in the rootviewcontroller i hav a few UITextFields. There is a button on rootviewController, on clicking that button i am changing the view using pushviewcontroller. I want to use values entered in these UItextFields in mapview ie my 2nd view.

PLZ suggest me something.

答:
you could pass all the information to your second controller before pushing to navigation stack.

See the pseudo code for your reference :

First:

```<code>MyMapController* myController = [MyMapController alloc] initWithValues:Value1,value2,value3,......valuen];
[self.navigationController pushViewController:myController animated:YES];

[myController release];
myController = nil;
</code>```

Second:

```<code>MyMapController* myController = [MyMapController alloc] init];

myController.value1 = value1;
myController.value2 = value2;
myController.value3 = value3;
............

myController.value7 = value7;
myController.value8 = value8;
[self.navigationController pushViewController:myController animated:YES];

[myController release];
myController = nil;
</code>```

There could be more approach for sending the data,

ContentLicense: CC BY-SA 3.0

Body:
you could pass all the information to your second controller before pushing to navigation stack.

See the pseudo code for your reference :

First:

MyMapController* myController = [MyMapController alloc] initWithValues:Value1,value2,value3,......valuen];
[self.navigationController pushViewController:myController animated:YES];

[myController release];
myController = nil;

Second:

MyMapController* myController = [MyMapController alloc] init];

myController.value1 = value1;
myController.value2 = value2;
myController.value3 = value3;
............

myController.value7 = value7;
myController.value8 = value8;
[self.navigationController pushViewController:myController animated:YES];

[myController release];
myController = nil;

There could be more approach for sending the data,


问:
Passing an arrow function to a component that uses hooks causes useEffect to fire again
How to pass an arrow function as a prop to a component that uses hooks without causing useEffect to fire when it shouldn't?

Codesandbox

```<code>function Apple(props) {
  const { text, cb } = props;
  useEffect(() => {
    pretendFetch().then(result => cb(result));
    // eslint-plugin-react-hooks dictates that `cb` should be within the dependencies array
  }, [cb]);
  return <div>{text}</div>;
}
</code>```

When the component is passed an arrow function as cb it will fire the useEffect on every render.  Ideally it should just use the callback once, but I cannot just pass [] as the dependency array without eslint-plugin-react-hooks issuing a warning.  I've read that useRef can be used to wrap the callback but that seems like an unsatisfying bandaid to this issue.

答: The issue here is that the callback function is recreated on each render and therefore triggers the update in useEffect. You can change this behaviour by using the useCallback hook to wrap the callback function in the overlying component like I did in this CodeSandbox

ContentLicense: CC BY-SA 4.0

Body:
How to pass an arrow function as a prop to a component that uses hooks without causing useEffect to fire when it shouldn't?

Codesandbox

function Apple(props) {
  const { text, cb } = props;
  useEffect(() => {
    pretendFetch().then(result => cb(result));
    // eslint-plugin-react-hooks dictates that `cb` should be within the dependencies array
  }, [cb]);
  return
{text}
;
}

When the component is passed an arrow function as cb it will fire the useEffect on every render.  Ideally it should just use the callback once, but I cannot just pass [] as the dependency array without eslint-plugin-react-hooks issuing a warning.  I've read that useRef can be used to wrap the callback but that seems like an unsatisfying bandaid to this issue.


问:
Is it possible to read File from same folder where Azure function exists
In my Azure C# function I need to read a .txt file. I make the .txt file in Visual studio and set it to "copy Always".

Now I am using this code to read the file

```<code>var dir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);

var path = System.IO.Path.Combine(dir, "twinkle.txt");
</code>```

this code doesn't work. When I open the folder which is the value of dir. It lead me to this directory ""C:\Users{username}\AppData\Local\Azure.Functions.Cli\1.0.9""

How I can store a simple txt file in Azure function. Or I need Azure Storage for this.

Anything else I can do to get this done.

Update for showing file copied

答:
For those like me who doesn't have access to ExecutionContext since we have to read a file in Startup.

var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var rootDirectory = Path.GetFullPath(Path.Combine(binDirectory, ".."));

///then you can read the file as you would expect yew!
File.ReadAllText(rootDirectory + "/path/to/file.ext");
```

Also worth noting that Environment.CurrentDirectory might work on a local environment, but will not work when deployed to Azure.

Works inside functions too.

Reference

Body:
In my Azure C# function I need to read a .txt file. I make the .txt file in Visual studio and set it to "copy Always".

Now I am using this code to read the file

var dir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);

var path = System.IO.Path.Combine(dir, "twinkle.txt");

this code doesn't work. When I open the folder which is the value of dir. It lead me to this directory ""C:\Users{username}\AppData\Local\Azure.Functions.Cli\1.0.9""

How I can store a simple txt file in Azure function. Or I need Azure Storage for this.

Anything else I can do to get this done.

Update for showing file copied

Body:
For those like me who doesn't have access to ExecutionContext since we have to read a file in Startup.

var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var rootDirectory = Path.GetFullPath(Path.Combine(binDirectory, ".."));

///then you can read the file as you would expect yew!
File.ReadAllText(rootDirectory + "/path/to/file.ext");

Also worth noting that Environment.CurrentDirectory might work on a local environment, but will not work when deployed to Azure.

Works inside functions too.

Reference


问:
Correct way of getting Client's IP Addresses from http.Request
What's the correct way to get all client's IP Addresses from http.Request? In PHP there are a lot of variables that I should check. Is it the same on Go?

One that I found is:

```<code>req.RemoteAddr
</code>```

And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))

答:
According to Mozilla MDN: "The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client."

They publish clear information in their X-Forwarded-For article.

Body:
What's the correct way to get all client's IP Addresses from http.Request? In PHP there are a lot of variables that I should check. Is it the same on Go?

One that I found is:

req.RemoteAddr

And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))


问:
easySilder 1.7 jquery - moce to latest selected slide after page reloads
I have a menu implemented with easySlider 1.7.

Code is like this:

```<code><div id="slider">
    <ul>
        <?
            $rezultat = mysql_query("SELECT DISTINCT catid,name FROM categories ORDER BY name ASC");
            $count = 1;
            echo "<li>";
            while($camp = mysql_fetch_array($rezultat))
            {
                if ($count <= 7)
                {
                    $count++;
                    if ($pagina == $camp['catid'])
                    {
                        echo "<a href='index.php?catid=";
                        echo $camp['catid'];
                        echo "' style='color: #F00;'>".$camp['name']."</a><br />";
                    }
                    else
                    {
                        echo "<a href='index.php?catid=";
                        echo $camp['catid'];
                        echo "'>".$camp['name']."</a><br />";
                    }
                }
                else
                {
                    $count = 1;
                    echo "</li><li>";
                }
            }
        ?>
    </ul>
</div>
</code>```

Now, after I click a link on the menu, the page reloads and i loose track of "previous current slide" where I have the selected link.

How can i go to that slide after reload or make it default slide ?

PS: Works with ajax but if i use ajax i have problem with some other php generated javascript variables that depends of each link. You can see a preview at: http://5election.com. Notice the scrolling menu on the bottom left side that's I'm having problems with.

Thanks in advance.

答:
You can add to the hyperlink the current slide.

In this way, when the page loads, you will know from where it came.

Body:
I have a menu implemented with easySlider 1.7.

Code is like this:

        <?
            $rezultat = mysql_query("SELECT DISTINCT catid,name FROM categories ORDER BY name ASC");
            $count = 1;
            echo "
";
            while($camp = mysql_fetch_array($rezultat))
            {
                if ($count <= 7)
                {
                    $count++;
                    if ($pagina == $camp['catid'])
                    {
                        echo "".$camp['name']."
";
                    }
                    else
                    {
                        echo "".$camp['name']."
";
                    }
                }
                else
                {
                    $count = 1;
                    echo "

";
                }
            }
        ?>

Now, after I click a link on the menu, the page reloads and i loose track of "previous current slide" where I have the selected link.

How can i go to that slide after reload or make it default slide ?

PS: Works with ajax but if i use ajax i have problem with some other php generated javascript variables that depends of each link. You can see a preview at: http://5election.com. Notice the scrolling menu on the bottom left side that's I'm having problems with.

Thanks in advance.


问:
Spring Boot: Type cannot be null; nested exception is java.lang.IllegalArgumentException: Type cannot be null when running Stored Procedue
Good morning, I am new to Spring Boot, and I am performing a rest service that must invoke a procedure stored in the database, the question is that you receive the mobile and must return a code and result, as shown below:

This is my code:

Main Class

```<code>package com.app.validacion;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

Controller

```<code>package com.app.validacion.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.app.validacion.dao.DriverBonificadosRepository;
import com.app.validacion.entity.RespuestaVo;

@RestController
public class DriverBonificadosController {

    @Autowired
    private DriverBonificadosRepository dao;

    @GetMapping("/service/{movil}")
    public RespuestaVo  ConsultarMovil(@PathVariable String movil) {
        return dao.validarClienteBonifiado(movil);

    }
}
</code>```

Repository

```<code>package com.app.validacion.dao;

import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Procedure(procedureName="ValidacionClienteBonificado")
    RespuestaVo validarClienteBonifiado(String pMovil);
}
</code>```

My entity

```<code>import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;

@NamedStoredProcedureQueries({
    @NamedStoredProcedureQuery(
            name="SPValidationClienteBonus4G",
            procedureName="ValidacionClienteBonificado",
            parameters = {
                    @StoredProcedureParameter(mode=ParameterMode.IN, name="p_movil",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="code",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="result",type=String.class),
            })

})

@Entity
@Table
public class DriverBonificados {

    @Id
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMovil() {
        return movil;
    }
    public void setMovil(String movil) {
        this.movil = movil;
    }
    public String getContador() {
        return contador;
    }
    public void setContador(String contador) {
        this.contador = contador;
    }
    public Date getFecha_driver() {
        return fecha_driver;
    }
    public void setFecha_driver(Date fecha_driver) {
        this.fecha_driver = fecha_driver;
    }
    public Date getFecha_alta() {
        return fecha_alta;
    }
    public void setFecha_alta(Date fecha_alta) {
        this.fecha_alta = fecha_alta;
    }
    public Date getFecha_fin() {
        return fecha_fin;
    }
    public void setFecha_fin(Date fecha_fin) {
        this.fecha_fin = fecha_fin;
    }
    public Date getCodigo_transaccion() {
        return codigo_transaccion;
    }
    public void setCodigo_transaccion(Date codigo_transaccion) {
        this.codigo_transaccion = codigo_transaccion;
    }
    private String movil;
    private String contador;
    private Date fecha_driver;
    private Date fecha_alta;
    private Date fecha_fin;
    private Date codigo_transaccion;
</code>```

My Class RespuestaVo

```<code>package com.app.validacion.entity;

public class RespuestaVo {

    private String code;
    private String result;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

}
</code>```

And I get the following error (the mobile parameter must be received as a String, since in the database it is found as Varchar):

Anyone have an idea how this problem could be solved? I need to consult via Stored Procedue if or if

UPDATE

Using @Query and modifying the code as follows:

```<code>package com.app.validacion.dao;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
    RespuestaVo validarClienteBonifiado(@Param("movil") String pMovil);
}
</code>```

I get the following error:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap]
  to type [com.app.validacion.entity.RespuestaVo]   at
  org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:170)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)
  ~[spring-data-jpa-2.2.1.RELEASE.jar:2.2.1.RELEASE]

答:
SOLVED

I managed to solve my problem, using the @Query annotation, and building an interface for the response I was going to receive, in these cases with 2 methods (according to the number of parameters that I will receive), and With this I got my answer in a Json, I leave the interface code below:

```<code>public interface RespuestaVo {

    String getCode();
    String getResult();

}
</code>```

I recommend using @Query to run Stored Procedue with Spring Boot

Body:
Good morning, I am new to Spring Boot, and I am performing a rest service that must invoke a procedure stored in the database, the question is that you receive the mobile and must return a code and result, as shown below:

This is my code:

Main Class

package com.app.validacion;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Controller

package com.app.validacion.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.app.validacion.dao.DriverBonificadosRepository;
import com.app.validacion.entity.RespuestaVo;

@RestController
public class DriverBonificadosController {

    @Autowired
    private DriverBonificadosRepository dao;

    @GetMapping("/service/{movil}")
    public RespuestaVo  ConsultarMovil(@PathVariable String movil) {
        return dao.validarClienteBonifiado(movil);

    }
}

Repository

package com.app.validacion.dao;

import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Procedure(procedureName="ValidacionClienteBonificado")
    RespuestaVo validarClienteBonifiado(String pMovil);
}

My entity

import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;

@NamedStoredProcedureQueries({
    @NamedStoredProcedureQuery(
            name="SPValidationClienteBonus4G",
            procedureName="ValidacionClienteBonificado",
            parameters = {
                    @StoredProcedureParameter(mode=ParameterMode.IN, name="p_movil",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="code",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="result",type=String.class),
            })

})

@Entity
@Table
public class DriverBonificados {

    @Id
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMovil() {
        return movil;
    }
    public void setMovil(String movil) {
        this.movil = movil;
    }
    public String getContador() {
        return contador;
    }
    public void setContador(String contador) {
        this.contador = contador;
    }
    public Date getFecha_driver() {
        return fecha_driver;
    }
    public void setFecha_driver(Date fecha_driver) {
        this.fecha_driver = fecha_driver;
    }
    public Date getFecha_alta() {
        return fecha_alta;
    }
    public void setFecha_alta(Date fecha_alta) {
        this.fecha_alta = fecha_alta;
    }
    public Date getFecha_fin() {
        return fecha_fin;
    }
    public void setFecha_fin(Date fecha_fin) {
        this.fecha_fin = fecha_fin;
    }
    public Date getCodigo_transaccion() {
        return codigo_transaccion;
    }
    public void setCodigo_transaccion(Date codigo_transaccion) {
        this.codigo_transaccion = codigo_transaccion;
    }
    private String movil;
    private String contador;
    private Date fecha_driver;
    private Date fecha_alta;
    private Date fecha_fin;
    private Date codigo_transaccion;

My Class RespuestaVo

package com.app.validacion.entity;

public class RespuestaVo {

    private String code;
    private String result;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

}

And I get the following error (the mobile parameter must be received as a String, since in the database it is found as Varchar):

Anyone have an idea how this problem could be solved? I need to consult via Stored Procedue if or if

UPDATE

Using @Query and modifying the code as follows:

package com.app.validacion.dao;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
    RespuestaVo validarClienteBonifiado(@Param("movil") String pMovil);
}

I get the following error:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap]
  to type [com.app.validacion.entity.RespuestaVo]   at
  org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:170)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)
  ~[spring-data-jpa-2.2.1.RELEASE.jar:2.2.1.RELEASE]

Body:
SOLVED

I managed to solve my problem, using the @Query annotation, and building an interface for the response I was going to receive, in these cases with 2 methods (according to the number of parameters that I will receive), and With this I got my answer in a Json, I leave the interface code below:

public interface RespuestaVo {

    String getCode();
    String getResult();

}

I recommend using @Query to run Stored Procedue with Spring Boot


问:
Create wide (desummarized) R data.table
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

```<code>dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8
</code>```

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

```<code># Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

</code>```

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

答:
You can do:

```<code>dt.compact[, .(chr, num = seq(start, stop)), by = 1:nrow(dt.compact)][, -1]
</code>```

Output:

```<code>     chr num
 1: chr1   1
 2: chr1   2
 3: chr1   3
 4: chr1   5
 5: chr1   6
 6: chr1   7
 7: chr2   2
 8: chr2   3
 9: chr2   7
10: chr2   8
</code>```

Edit: There is indeed a dupe for that, however here is a variation on the above approach provided by @jogo & not mentioned in the other topic:

```<code>dt.compact[, mapply(seq, start, stop), chr]
</code>```

Title: Create wide (desummarized) R data.table

Body:
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

# Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

Body:
You can do:

dt.compact[, .(chr, num = seq(start, stop)), by = 1:nrow(dt.compact)][, -1]

Output:

     chr num
 1: chr1   1
 2: chr1   2
 3: chr1   3
 4: chr1   5
 5: chr1   6
 6: chr1   7
 7: chr2   2
 8: chr2   3
 9: chr2   7
10: chr2   8

Edit: There is indeed a dupe for that, however here is a variation on the above approach provided by @jogo & not mentioned in the other topic:

dt.compact[, mapply(seq, start, stop), chr]


问:
CUnit return 0 on test fail
I built a simple program that executes a test in CUnit.
The main function is:

```<code>int main()
 50 {
 51         CU_pSuite pSuite = NULL;
 52
 53         /* initialize the CUnit test registry */
 54         if (CUE_SUCCESS != CU_initialize_registry())
 55                 return CU_get_error();
 56
 57         /* add a suite to the registry */
 58         pSuite = CU_add_suite("Suite_1", init_suite1, clean_suite1);
 59         if (NULL == pSuite) {
 60                 CU_cleanup_registry();
 61                 return CU_get_error();
 62         }
 63
 64         if ((NULL == CU_add_test(pSuite, "test of fprintf()", test_parse))) {
 65                 CU_cleanup_registry();
 66                 return CU_get_error();
 67         }
 68
 69         /* Run all tests using the CUnit Basic interface */
 70         CU_basic_set_mode(CU_BRM_VERBOSE);
 71         CU_basic_run_tests();
 72         CU_cleanup_registry();
 73         printf("ERROR CODE: %d", CU_get_error());
 74         return CU_get_error();
 75 }
</code>```

The test_parse function uses CU_ASSERT_FATAL. The test fails, but the output of main is the following:

```<code>CUnit - A unit testing framework for C - Version 2.1-3
http://cunit.sourceforge.net/

Suite: Suite_1
  Test: test of fprintf() ...FAILED
    1. /home/fedetask/Desktop/curl/tests/main.c:42  - parsed == 3

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      1      1    n/a      0        0
               tests      1      1      0      1        0
             asserts      5      5      4      1      n/a

Elapsed time =    0.000 seconds
ERROR CODE: 0
</code>```

The main() returns 0. It returns 0 also if the test passes. What am I doing wrong?

答:
Ran into the same issue with this. Indeed, CU_get_error() will be 0 even if a testcase if failing. The following variables store the results as shown in the doc

```<code>unsigned int CU_get_number_of_suites_run(void)
unsigned int CU_get_number_of_suites_failed(void)
unsigned int CU_get_number_of_tests_run(void)
unsigned int CU_get_number_of_tests_failed(void)
unsigned int CU_get_number_of_asserts(void)
unsigned int CU_get_number_of_successes(void)
unsigned int CU_get_number_of_failures(void)
</code>```

So a simple approach for checking if there has been any error, would be something like:

if (CU_get_number_of_tests_failed() != 0){
  // Do Something
}
```

Title: CUnit return 0 on test fail

Body:
I built a simple program that executes a test in CUnit.
The main function is:

int main()
 50 {
 51         CU_pSuite pSuite = NULL;
 52
 53         /* initialize the CUnit test registry */
 54         if (CUE_SUCCESS != CU_initialize_registry())
 55                 return CU_get_error();
 56
 57         /* add a suite to the registry */
 58         pSuite = CU_add_suite("Suite_1", init_suite1, clean_suite1);
 59         if (NULL == pSuite) {
 60                 CU_cleanup_registry();
 61                 return CU_get_error();
 62         }
 63
 64         if ((NULL == CU_add_test(pSuite, "test of fprintf()", test_parse))) {
 65                 CU_cleanup_registry();
 66                 return CU_get_error();
 67         }
 68
 69         /* Run all tests using the CUnit Basic interface */
 70         CU_basic_set_mode(CU_BRM_VERBOSE);
 71         CU_basic_run_tests();
 72         CU_cleanup_registry();
 73         printf("ERROR CODE: %d", CU_get_error());
 74         return CU_get_error();
 75 }

The test_parse function uses CU_ASSERT_FATAL. The test fails, but the output of main is the following:

CUnit - A unit testing framework for C - Version 2.1-3
http://cunit.sourceforge.net/

Suite: Suite_1
  Test: test of fprintf() ...FAILED
    1. /home/fedetask/Desktop/curl/tests/main.c:42  - parsed == 3

Run Summary:    Type  Total    Ran Passed Failed Inactive
              suites      1      1    n/a      0        0
               tests      1      1      0      1        0
             asserts      5      5      4      1      n/a

Elapsed time =    0.000 seconds
ERROR CODE: 0

The main() returns 0. It returns 0 also if the test passes. What am I doing wrong?

Body:
Ran into the same issue with this. Indeed, CU_get_error() will be 0 even if a testcase if failing. The following variables store the results as shown in the doc

unsigned int CU_get_number_of_suites_run(void)
unsigned int CU_get_number_of_suites_failed(void)
unsigned int CU_get_number_of_tests_run(void)
unsigned int CU_get_number_of_tests_failed(void)
unsigned int CU_get_number_of_asserts(void)
unsigned int CU_get_number_of_successes(void)
unsigned int CU_get_number_of_failures(void)

So a simple approach for checking if there has been any error, would be something like:

if (CU_get_number_of_tests_failed() != 0){
  // Do Something
}


问:
Log4j - logging of internal Log4j events
I am having some issue with log4j settings.

In order to solve them i have enabled internal log4j logging in log4j properties as that:

```<code>log4j.debug=true
</code>```

It is working as i am getting logs like this in console which is fine:

```<code>log4j: Parsing for [root] with value=[DEBUG, console, rollingFile, test].
log4j: enter code here`: Level token is [DEBUG].
log4j: Category root set to DEBUG
log4j: Parsing appender named "console".
log4j: Parsing layout options for "console".
</code>```

Now i need to save those logs also to file.
I have added FileAppender which works for other logs, but does not save the internal log4j logs.

Whole log4j configuration:

```<code>#log4j.category.org.hibernate=INFO, hibernate
log4j.category.org.hibernate.SQL=ERROR, hibernate
#log4j.category.org.hibernate.type=ALL, hibernate
log4j.additivity.org.hibernate.SQL=false

#Root logger setting
log4j.rootLogger=DEBUG, console, rollingFile, test

#Appenders configurations.
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} %5p [%t] (%F:%L) - %m%n

log4j.appender.rollingFile=eu.unicorn.pcr.broker.logging.CustodianDailyRollingFileAppender
log4j.appender.rollingFile.File=${catalina.home}/logs/pcr-app.log
log4j.appender.rollingFile.DatePattern='.'yyyy-MM-dd-HH-mm
log4j.appender.rollingFile.MaxNumberOfDays=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} %5p [%t] (%F:%L) - %m%n

#apender for stress request logging
log4j.appender.stressTest=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stressTest.File=${catalina.home}/logs/requests.log
log4j.appender.stressTest.MaxBackupIndex=10
log4j.appender.stressTest.layout = org.apache.log4j.PatternLayout
log4j.appender.stressTest.layout.conversionPattern=%d{HH:mm:ss.SSS} [%t] - %m%n

log4j.category.stressTestLogger=TRACE, stressTest
log4j.additivty.stressTestLogger=false

log4j.appender.hibernate=org.apache.log4j.RollingFileAppender
log4j.appender.hibernate.File=${catalina.home}/logs/hibernate.log
log4j.appender.hibernate.MaxFileSize=20MB
log4j.appender.hibernate.MaxBackupIndex=10
log4j.appender.hibernate.layout = org.apache.log4j.PatternLayout
log4j.appender.hibernate.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} [%t] (%F:%L) - %m%n

# Define the test file appender
log4j.appender.test=org.apache.log4j.FileAppender
log4j.appender.test.File=${catalina.home}/logs/test.log
log4j.appender.test.ImmediateFlush=true
log4j.appender.test.Threshold=debug
log4j.appender.test.Append=false
log4j.appender.test.layout=org.apache.log4j.PatternLayout
log4j.appender.test.layout.conversionPattern=%m%n

log4j.debug=true
</code>```

Any tips how to set up that the internal log4j logs will be also saved also in file? Would be glad for any hints.

答:
If you want save your log in a file you must use the propierties for that.</p>

```<code>
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender

# Set the name of the file
log4j.appender.FILE.File=${log}/log.out

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

</code>```

Body:
I am having some issue with log4j settings.

In order to solve them i have enabled internal log4j logging in log4j properties as that:

log4j.debug=true

It is working as i am getting logs like this in console which is fine:

log4j: Parsing for [root] with value=[DEBUG, console, rollingFile, test].
log4j: enter code here`: Level token is [DEBUG].
log4j: Category root set to DEBUG
log4j: Parsing appender named "console".
log4j: Parsing layout options for "console".

Now i need to save those logs also to file.
I have added FileAppender which works for other logs, but does not save the internal log4j logs.

Whole log4j configuration:

#log4j.category.org.hibernate=INFO, hibernate
log4j.category.org.hibernate.SQL=ERROR, hibernate
#log4j.category.org.hibernate.type=ALL, hibernate
log4j.additivity.org.hibernate.SQL=false

#Root logger setting
log4j.rootLogger=DEBUG, console, rollingFile, test

#Appenders configurations.
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} %5p [%t] (%F:%L) - %m%n

log4j.appender.rollingFile=eu.unicorn.pcr.broker.logging.CustodianDailyRollingFileAppender
log4j.appender.rollingFile.File=${catalina.home}/logs/pcr-app.log
log4j.appender.rollingFile.DatePattern='.'yyyy-MM-dd-HH-mm
log4j.appender.rollingFile.MaxNumberOfDays=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} %5p [%t] (%F:%L) - %m%n

#apender for stress request logging
log4j.appender.stressTest=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stressTest.File=${catalina.home}/logs/requests.log
log4j.appender.stressTest.MaxBackupIndex=10
log4j.appender.stressTest.layout = org.apache.log4j.PatternLayout
log4j.appender.stressTest.layout.conversionPattern=%d{HH:mm:ss.SSS} [%t] - %m%n

log4j.category.stressTestLogger=TRACE, stressTest
log4j.additivty.stressTestLogger=false

log4j.appender.hibernate=org.apache.log4j.RollingFileAppender
log4j.appender.hibernate.File=${catalina.home}/logs/hibernate.log
log4j.appender.hibernate.MaxFileSize=20MB
log4j.appender.hibernate.MaxBackupIndex=10
log4j.appender.hibernate.layout = org.apache.log4j.PatternLayout
log4j.appender.hibernate.layout.conversionPattern=%d{yyyyMMdd HH:mm:ss.SSS} [%t] (%F:%L) - %m%n

# Define the test file appender
log4j.appender.test=org.apache.log4j.FileAppender
log4j.appender.test.File=${catalina.home}/logs/test.log
log4j.appender.test.ImmediateFlush=true
log4j.appender.test.Threshold=debug
log4j.appender.test.Append=false
log4j.appender.test.layout=org.apache.log4j.PatternLayout
log4j.appender.test.layout.conversionPattern=%m%n

log4j.debug=true

Any tips how to set up that the internal log4j logs will be also saved also in file? Would be glad for any hints.

Body:
If you want save your log in a file you must use the propierties for that.

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender

# Set the name of the file
log4j.appender.FILE.File=${log}/log.out

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n


问:
Angular - How to prevent nested piping with dependent observables?
In order to keep my code clean I try to prevent nested piping when it comes to observables. However I encountered a constellation (see code below) where I could not find a way to do without. I wonder if there is a way to solve this problem with only one pipe?

Example code:

```<code>class CannotSimplify {

  observableA(): Observable<number> {
    return of(1);
  }

  bDependentA(a: number): Observable<number> {
    return of(2 + a, 3 + a);
  }

  cDependentOnAAndB(a: number, b: number): Observable<number> {
    return of(a + b);
  }

  printResult(): void {
    this.observableA()
      .pipe(
        switchMap(a => this.bDependentA(a)),
        switchMap(b => this.cDependentOnAAndB(a, b)) // <-- error: a is undefined
      )
      .subscribe(c => console.log(c));
  }

}
</code>```

The only solution I could think of is to pipe this.bDependentOnA() again.
Is there a better approach?

Thanks in advance!

答:
I think you want to call three functions within one pipe. It's my solution is to use zip.

```<code>import { Observable, of, Subscription, zip } from 'rxjs';

    printResult(): void {
        this.observableA()
        .pipe(
           switchMap(a => zip(of(a), this.bDependentA(a))),
           switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
        ).subscribe(c => console.log(c));
    }
</code>```

My example: https://stackblitz.com/edit/angular-4ipoen

Body:
In order to keep my code clean I try to prevent nested piping when it comes to observables. However I encountered a constellation (see code below) where I could not find a way to do without. I wonder if there is a way to solve this problem with only one pipe?

Example code:

class CannotSimplify {

  observableA(): Observable<number> {
    return of(1);
  }

  bDependentA(a: number): Observable<number> {
    return of(2 + a, 3 + a);
  }

  cDependentOnAAndB(a: number, b: number): Observable<number> {
    return of(a + b);
  }

  printResult(): void {
    this.observableA()
      .pipe(
        switchMap(a => this.bDependentA(a)),
        switchMap(b => this.cDependentOnAAndB(a, b)) // <-- error: a is undefined
      )
      .subscribe(c => console.log(c));
  }

}

The only solution I could think of is to pipe this.bDependentOnA() again.
Is there a better approach?

Thanks in advance!

Body:
I think you want to call three functions within one pipe. It's my solution is to use zip.

import { Observable, of, Subscription, zip } from 'rxjs';

    printResult(): void {
        this.observableA()
        .pipe(
           switchMap(a => zip(of(a), this.bDependentA(a))),
           switchMap(([a, b]) => this.cDependentOnAAndB(a, b))
        ).subscribe(c => console.log(c));
    }

My example: https://stackblitz.com/edit/angular-4ipoen


问:
Fill complex object property List<T> based on string.split condition
I have a complex object and need to fill the data based on split condition that I get from reader.
Below object need to filter data based on "--" ( Example given below).

```<code>Class Employee {
    public string fName {get;} {set;}
    public List<string> Departments {get;} {set;}
}
</code>```

once I get the data from reader, I am looping and one of the column Department has value like {"Sales -- Payroll -- HR"}

```<code>while (dr.read())
{
    new Employee() {
        fname = dr["name],
            Departments = new List<string>
            {
                dr["Department"].ToString().Split(
                    new string[] {" -- "},
                    StringSplitOptions.None).ToString()
            }
    }
}
</code>```

I tried above option but still not getting desired results.. I need 3 string array based on above example part of Departments property.

Any idea what I am missing?

答:
I think you mean to use the RemoveEmptyEntries + to make the result as ToList() and assigned it.

```<code>Departments = dr["Department"].ToString().Split(new string[] {"--"}, StringSplitOptions.RemoveEmptyEntries).ToList()
</code>```

In you're example you tried to make a Splitted array ToString() which will give you a string representation of an object (and not an actual list object) and then you tried to put it in a list.

Instead, i've splitted the result into a list and assign it directly to Departments and not to new List<string>.

Body:
I have a complex object and need to fill the data based on split condition that I get from reader.
Below object need to filter data based on "--" ( Example given below).

Class Employee {
    public string fName {get;} {set;}
    public List<string> Departments {get;} {set;}
}

once I get the data from reader, I am looping and one of the column Department has value like {"Sales -- Payroll -- HR"}

while (dr.read())
{
    new Employee() {
        fname = dr["name],
            Departments = new List<string>
            {
                dr["Department"].ToString().Split(
                    new string[] {" -- "},
                    StringSplitOptions.None).ToString()
            }
    }
}

I tried above option but still not getting desired results.. I need 3 string array based on above example part of Departments property.

Any idea what I am missing?

Body:
I think you mean to use the RemoveEmptyEntries + to make the result as ToList() and assigned it.

Departments = dr["Department"].ToString().Split(new string[] {"--"}, StringSplitOptions.RemoveEmptyEntries).ToList()

In you're example you tried to make a Splitted array ToString() which will give you a string representation of an object (and not an actual list object) and then you tried to put it in a list.

Instead, i've splitted the result into a list and assign it directly to Departments and not to new List<string>.


问:
Excel formula to total cells containing numbers in brackets without the text
I would like to know if there's an Excel formula to input into Cell B2 to total up the number of 'A' hours in Row 1?

Thank you

答: To change the formula by @JLCH to use ADEL instead of A you need to adjust the LEFT(B10:F10,1)="A" to instead read LEFT(B10:F10,4)="ADEL" so that it looks at the first 4 letters in the cells and checks if it matches "ADEL"


问:
Dropdown menu behind text
I tried to create a drop down menu. That's what I did so far:
http://gegensinn.org/test.html
(I made the drop down menu visible at all time for "debugging")

I think the problem is quite obvious: The menu is behind the text.

First I thought I could fix this with z-index.

Although I'm not quite sure which element has to get the z-index property.

I tried to set the whole menu to z-index:100; and at the same time set the z-index:1; of  .main.

Afterwards I tried to set only the z-index of
 and   but nothing worked.

答: add position:relative on #header :)

Title: Dropdown menu behind text

Body: add position:relative on #header :)


问:
Two different objects implement the same Interface in the same way - how to stay DRY
I have the interface:

IColored that guarantees the function getColor.

Now I have two objects:

 1. Ferrari

 2. RedApple

that both implement this interface/function in the same way.

(But cannot inherit from the same object - no multi-inheritance allowed).

How would you avoid code-duplication?

答:
I guess what you are looking for is object aggregation.

Check out TAggregatedObject. The idea is to have an object that implements
the behavior and as a property it delegates the interface functions to that
inner object.


问:
how to use the same container which was exited in docker
I had created a lot of containers. I am new to this docker container system.
I do a docker ps -a then I get following result

```<code>debian@osboxes:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                       PORTS               NAMES
a6a62181dcf0        python              "/bin/bash"              About a minute ago   Exited (127) 8 seconds ago                       try1
ed5ef0b8155d        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          pedantic_ellis
19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                22 hours ago         Exited (0) 22 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (0) 24 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   28 hours ago         Exited (127) 28 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (1) 28 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              29 hours ago         Exited (0) 29 hours ago                          vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              30 hours ago         Exited (0) 29 hours ago                          gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              30 hours ago         Created                                          nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 22 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 46 hours ago                          strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (255) 2 minutes ago                       objective_napier
ebae378d9152        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            brave_ritchie
23c7f4293b30        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            suspicious_lumiere
5090081f6809        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quizzical_keller
425d59be9cbf        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            distracted_lederberg
11c55ce7f011        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_noyce
1ccaf0477995        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          mystifying_tu
62528115f4b7        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          determined_meninsky
fca64af2f595        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_goldwasser
eecb3153bded        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          cool_cray
30b6d61fcac9        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quirky_kapitsa
cf992a8b8286        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          hungry_goldstine
0f9a951f7593        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          crazy_wright
e25dcf8a8be8        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          bold_pasteur
73d068e0d756        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            condescending_goodall
adda325294cd        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            serene_wilson
75a9a3262505        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            hardcore_khorana
e38726a74e9b        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (255) 2 days ago                          beautiful_clarke
4060dbc85d2d        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (0) 3 days ago                            strange_yonath
174509213b30        hadoop-build-1001   "/bin/bash"              8 days ago           Exited (255) 7 days ago                          hadoop-c
fa82c595e214        1d1a162a72a6        "/bin/bash"              8 days ago           Exited (0) 8 days ago                            agitated_edison
4b07fcc45271        python              "python3"                2 weeks ago          Exited (255) 8 days ago                          pyC
1cc06f213eb7        abee520343a4        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        compassionate_kowalevski
8c1eb67f7325        1b1c7b120b48        "/bin/sh -c 'cd /opt…"   3 months ago         Exited (255) 3 months ago                        dreamy_jepsen
1406d7476a28        1180f37ef8b1        "/bin/sh -c 'mkdir -…"   3 months ago         Exited (35) 3 months ago                         upbeat_taussig
e88bcf7743e2        f0f5acc11f91        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        tender_cohen
</code>```

I had made some changes in a container which was created using one of hadoop image as below

```<code>debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB
</code>```

I powered off the machine and rebooted etc.
I want to know that I made changes to one of the containers say in above output of docker ps -a the container was

```<code>25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1)
</code>```

how can after a reboot etc I connect or start the same container again.
What I am currently doing is

```<code>docker run -it 1d1a162a72a6 /bin/bash
</code>```

I make some changes and run a few python programms. But after a reboot all the changes are gone that means those python files which I had edited I have to copy paste them again in the container and do every thing from scratch.I have to install vim each time and then each time I do apt-get update install softwares and then check edit the programe.
I am not able to understand how to go back to same container which was created moments ago before exiting. What mistake I am doing here?

答:
I had made some changes in a container... after a reboot all the changes are gone that means those python files which I had edited I have to copy paste them again in the container and do every thing from scratch.I have to install vim each time and then each time I do apt-get update install softwares and then check edit the programe.

Containers are, by definition, immutable. What you were editing was a temporary runtime layer. If the container stopped or exited, you lose those changes.

In order to preserve changes, you must edit the Dockerfile and rebuild the container in order to create those immutable layers that the image contains

Realistically, you'd use a volume mount from the host into the container and edit code locally, which syncs into the container. No need for text editors or repeated apt updates

Body:
I had created a lot of containers. I am new to this docker container system.
I do a docker ps -a then I get following result

debian@osboxes:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS                       PORTS               NAMES
a6a62181dcf0        python              "/bin/bash"              About a minute ago   Exited (127) 8 seconds ago                       try1
ed5ef0b8155d        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          pedantic_ellis
19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              22 hours ago         Exited (0) 22 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                22 hours ago         Exited (0) 22 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (0) 24 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   28 hours ago         Exited (127) 28 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              28 hours ago         Exited (1) 28 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              29 hours ago         Exited (0) 29 hours ago                          vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              30 hours ago         Exited (0) 29 hours ago                          gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              30 hours ago         Created                                          nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 22 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              46 hours ago         Created                                          funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              46 hours ago         Exited (1) 46 hours ago                          strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         2 days ago           Created                                          elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (255) 2 minutes ago                       objective_napier
ebae378d9152        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1) 2 days ago                            brave_ritchie
23c7f4293b30        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            suspicious_lumiere
5090081f6809        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quizzical_keller
425d59be9cbf        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            distracted_lederberg
11c55ce7f011        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_noyce
1ccaf0477995        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          mystifying_tu
62528115f4b7        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          determined_meninsky
fca64af2f595        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          elastic_goldwasser
eecb3153bded        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          cool_cray
30b6d61fcac9        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (1) 2 days ago                            quirky_kapitsa
cf992a8b8286        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          hungry_goldstine
0f9a951f7593        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          crazy_wright
e25dcf8a8be8        hadoop-build-1001   "/bin/bash"              2 days ago           Created                                          bold_pasteur
73d068e0d756        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            condescending_goodall
adda325294cd        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            serene_wilson
75a9a3262505        hadoop-build-1001   "/bin/bash"              2 days ago           Exited (0) 2 days ago                            hardcore_khorana
e38726a74e9b        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (255) 2 days ago                          beautiful_clarke
4060dbc85d2d        hadoop-build-1001   "/bin/bash"              3 days ago           Exited (0) 3 days ago                            strange_yonath
174509213b30        hadoop-build-1001   "/bin/bash"              8 days ago           Exited (255) 7 days ago                          hadoop-c
fa82c595e214        1d1a162a72a6        "/bin/bash"              8 days ago           Exited (0) 8 days ago                            agitated_edison
4b07fcc45271        python              "python3"                2 weeks ago          Exited (255) 8 days ago                          pyC
1cc06f213eb7        abee520343a4        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        compassionate_kowalevski
8c1eb67f7325        1b1c7b120b48        "/bin/sh -c 'cd /opt…"   3 months ago         Exited (255) 3 months ago                        dreamy_jepsen
1406d7476a28        1180f37ef8b1        "/bin/sh -c 'mkdir -…"   3 months ago         Exited (35) 3 months ago                         upbeat_taussig
e88bcf7743e2        f0f5acc11f91        "/bin/sh -c 'apt-get…"   3 months ago         Exited (100) 3 months ago                        tender_cohen

I had made some changes in a container which was created using one of hadoop image as below

debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB

I powered off the machine and rebooted etc.
I want to know that I made changes to one of the containers say in above output of docker ps -a the container was

25bfc74fab3b        1d1a162a72a6        "/bin/bash"              2 days ago           Exited (1)

how can after a reboot etc I connect or start the same container again.
What I am currently doing is

docker run -it 1d1a162a72a6 /bin/bash

I make some changes and run a few python programms. But after a reboot all the changes are gone that means those python files which I had edited I have to copy paste them again in the container and do every thing from scratch.I have to install vim each time and then each time I do apt-get update install softwares and then check edit the programe.
I am not able to understand how to go back to same container which was created moments ago before exiting. What mistake I am doing here?


问:
Creating object from CSV
How can I create C# object from a CSV in single string as input?

For example if I have string as string fields = "Id,Name,Code"

All should be string type and default value should be string empty.

答:
You can use ExpandoObject to create.

Updated My answer with Code :

```<code>   public object createDynamicObjectWithProperty(string fields)
  {
    var reqFields=fields.split(',');
    dynamic returnObj = new ExpandoObject();
     foreach(var propertiesName in reqFields)
      {

      AddProperty(returnObj,propertiesName,string.empty);
       }
    return returnObj ;

}

    public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
     {
            //Take use of the IDictionary implementation
            var expandoDict = expando as IDictionary;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
       }
</code>```

Title: Creating object from CSV

Body:
You can use ExpandoObject to create.

Updated My answer with Code :

   public object createDynamicObjectWithProperty(string fields)
  {
    var reqFields=fields.split(',');
    dynamic returnObj = new ExpandoObject();
     foreach(var propertiesName in reqFields)
      {

      AddProperty(returnObj,propertiesName,string.empty);
       }
    return returnObj ;

}

    public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
     {
            //Take use of the IDictionary implementation
            var expandoDict = expando as IDictionary;
            if (expandoDict.ContainsKey(propertyName))
                expandoDict[propertyName] = propertyValue;
            else
                expandoDict.Add(propertyName, propertyValue);
       }


问:
reactjs error while consuming the graphql API
Trying to consume the graphql API in react js application. not sure whether this approach is correct or not.

```<code>import React, { Component } from 'react'
import "./styles.css";
import axios from 'axios';

const appBaseUrl = axios.create({
  baseURL: 'http://localhost:8099/graphql'
});

const tagslist = ` {
  getTags
  {
    id
    tagName
    tagDesc
    tagVersion
    tagVersion
  }
}
`;

class TagsController extends React.Component {
  constructor(props) {
    super(props);
    this.state = { tags: []};
    this.headers = [
      { key: "id", label: "Tag Id" },
      { key: "tagName", label: "Tag Name" },
      { key: "tagDesc", label: "Tag Description" },
      { key: "tagVersion", label: "Tag Version" }
    ];
  }

  componentDidMount() {
    appBaseUrl
      .post('', { query: tagslist })
      .then(result =>
        this.setState(() => ({
          tags: result
        })),
      );
  }

  render() {
    console.log("...... url builder ......")
    const { tags } = this.state;
    return (
      <table border ="1">
        <thead>
        <tr>
                    {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            )
                        })
                    }
                    </tr>
        </thead>
        <tbody>
          {tags &&
            tags.data &&
            tags.data.getTags.map(function(item, key) {
              return (
                <tr key={key}>
                  <td>{item.id}</td>
                  <td>{item.tagName}</td>
                  <td>{item.tagDesc}</td>
                  <td>{item.tagVersion}</td>
                </tr>
              );
            })}
        </tbody>
      </table>
    );
  }
}

export default TagsController;
</code>```

Here exception below.

×
      Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

```<code>TagsController.render
  src/TagsController.js:59
  56 | }
  57 | </tr>
  58 |    </thead>
  59 |    <tbody>
     | ^  60 |      {tags &&
  61 |        tags.data &&
  62 |        tags.data.getTags.map(function(item, key) {
View compiled
▶ 18 stack frames were collapsed.
(anonymous function)
src/TagsController.js:35
  32 |
  33 | componentDidMount() {
  34 |   appBaseUrl
  35 |     .post('', { query: tagslist })
     | ^  36 |     .then(result =>
  37 |       this.setState(() => ({
  38 |         tags: result
</code>```

Excepted response from the API as below.

```<code>{
    "data": {
        "getTags": [
            {
                "id": "ef718cce-1269-4fbd-827c-832f7824c025",
                "tagName": "Veera6",
                "tagDesc": "Test Tag6",
                "tagVersion": 0
            },
            {
                "id": "0cda5ae9-e287-4666-804a-03f25e642d1f",
                "tagName": "Veera9",
                "tagDesc": "Test Tag9",
                "tagVersion": 0
            },
            {
                "id": "31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39",
                "tagName": "Veera8",
                "tagDesc": "Test Tag8",
                "tagVersion": 0
            },
            {
                "id": "6292054c-8bfc-4d2d-b2f8-92e2bac5a578",
                "tagName": "Veera7",
                "tagDesc": "Test Tag7",
                "tagVersion": 0
            },
            {
                "id": "c6756e5c-8fa5-40a9-ab92-5242bda97de3",
                "tagName": "Veera10",
                "tagDesc": "Test Tag10",
                "tagVersion": 0
            }
        ]
    }
}
</code>```

Basically i am trying to consume the graphql query API and display the result list with the react js application but getting the error as above. Looks like i am missing something when consume the graphql api and constructing the graphql query parameter

any help is really appreciate.

答:
tags in the state won't be an array while the data is requested.
You need to add another conditional to show a loading message while the data is requested.

```<code>componentDidMount() {
this.setState(() => ({ loading: true }))
    appBaseUrl
      .post('', { query: tagslist })
      .then(result =>
        this.setState(() => ({
          tags: result,
          loading: false
        })),
      );
  }

render() {
    console.log("...... url builder ......")
    const { tags, loading } = this.state;

    if (loading) {
      return "Loading data..."
    }
}
</code>```

You can find a lot of idea over the Internet, for example: http://nikolay.rocks/2017-06-18-better-redux-loading

Body:
Trying to consume the graphql API in react js application. not sure whether this approach is correct or not.

import React, { Component } from 'react'
import "./styles.css";
import axios from 'axios';

const appBaseUrl = axios.create({
  baseURL: 'http://localhost:8099/graphql'
});

const tagslist = ` {
  getTags
  {
    id
    tagName
    tagDesc
    tagVersion
    tagVersion
  }
}
`;

class TagsController extends React.Component {
  constructor(props) {
    super(props);
    this.state = { tags: []};
    this.headers = [
      { key: "id", label: "Tag Id" },
      { key: "tagName", label: "Tag Name" },
      { key: "tagDesc", label: "Tag Description" },
      { key: "tagVersion", label: "Tag Version" }
    ];
  }

  componentDidMount() {
    appBaseUrl
      .post('', { query: tagslist })
      .then(result =>
        this.setState(() => ({
          tags: result
        })),
      );
  }

  render() {
    console.log("...... url builder ......")
    const { tags } = this.state;
    return (

                    {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            )
                        })
                    }

          {tags &&
            tags.data &&
            tags.data.getTags.map(function(item, key) {
              return (

                  {item.id}
                  {item.tagName}
                  {item.tagDesc}
                  {item.tagVersion}

              );
            })}

    );
  }
}

export default TagsController;

Here exception below.

×
      Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

TagsController.render
  src/TagsController.js:59
  56 | }
  57 |

  58 |

  59 |

     | ^  60 |      {tags &&
  61 |        tags.data &&
  62 |        tags.data.getTags.map(function(item, key) {
View compiled
▶ 18 stack frames were collapsed.
(anonymous function)
src/TagsController.js:35
  32 |
  33 | componentDidMount() {
  34 |   appBaseUrl
  35 |     .post('', { query: tagslist })
     | ^  36 |     .then(result =>
  37 |       this.setState(() => ({
  38 |         tags: result

Excepted response from the API as below.

{
    "data": {
        "getTags": [
            {
                "id": "ef718cce-1269-4fbd-827c-832f7824c025",
                "tagName": "Veera6",
                "tagDesc": "Test Tag6",
                "tagVersion": 0
            },
            {
                "id": "0cda5ae9-e287-4666-804a-03f25e642d1f",
                "tagName": "Veera9",
                "tagDesc": "Test Tag9",
                "tagVersion": 0
            },
            {
                "id": "31f8f042-dbc0-4dbf-ada8-b94c7e2d2a39",
                "tagName": "Veera8",
                "tagDesc": "Test Tag8",
                "tagVersion": 0
            },
            {
                "id": "6292054c-8bfc-4d2d-b2f8-92e2bac5a578",
                "tagName": "Veera7",
                "tagDesc": "Test Tag7",
                "tagVersion": 0
            },
            {
                "id": "c6756e5c-8fa5-40a9-ab92-5242bda97de3",
                "tagName": "Veera10",
                "tagDesc": "Test Tag10",
                "tagVersion": 0
            }
        ]
    }
}

Basically i am trying to consume the graphql query API and display the result list with the react js application but getting the error as above. Looks like i am missing something when consume the graphql api and constructing the graphql query parameter

any help is really appreciate.

Body:
tags in the state won't be an array while the data is requested.
You need to add another conditional to show a loading message while the data is requested.

componentDidMount() {
this.setState(() => ({ loading: true }))
    appBaseUrl
      .post('', { query: tagslist })
      .then(result =>
        this.setState(() => ({
          tags: result,
          loading: false
        })),
      );
  }

render() {
    console.log("...... url builder ......")
    const { tags, loading } = this.state;

    if (loading) {
      return "Loading data..."
    }
}

You can find a lot of idea over the Internet, for example: http://nikolay.rocks/2017-06-18-better-redux-loading


问:
Why doesn't 'encode("utf-8", 'ignore').decode("utf-8")' strip non-UTF8 chars in Python 3?
I'm using Python 3.7 and Django 2.0.  I want to strip out non-UTF-8 characters from a string, that I'm obtaining by reading this CSV file.  I tried this ...

```<code>web_site = row['website'].strip().encode("utf-8", 'ignore').decode("utf-8")
</code>```

but this doesn't seem to be doing the job, since I have a resulting string that looks like ...

```<code>web_site: "wbez.org<200e>"
</code>```

Whatever this "<200e>" thing is, is evidently non-UTF-8 string, because when I try and insert this into a MySQL database (deployed as a docker image), I get the following error ...

```<code>web_1     | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/seed_data.yaml': Could not load maps.Coop(pk=191): (1366, "Incorrect string value: '\\xE2\\x80\\x8E' for column 'web_site' at row 1")
</code>```

答:
I think you are confusing the encodings.

Python has a standard character set: Unicode

UTF-8 is just and encoding of Unicode. All characters in Unicode can be encoded in UTF-8, and all valid UTF-8 codes can be interpreted as unicode characters.

So you are just encoding and decoding Unicode strings, so the code should do nothing. (There is really some exceptional cases: Python strings really are a superset of Unicode, so your code would just remove non Unicode characters, see surrogateescape, for such extremely seldom case, usually you will enconter only by reading sys.argv or os.environ).

In any case, I think you are doing thing wrong. Search in this site for the general question (e.g. "remove non-ascii characters"). It is often better to decompose (with K, compatibility), and then remove accent, and then remove non-ascii characters, so that you will get more characters translated. There are various function to create slug, which do a better job, or there is also a library which translate more characters in "nearly equivalent" ascii characters (Unicode has various representation of LETTER A, and you may want to translate also Alpha and Aleph and ... into A (better then discarding, especially if you have a foreign language, which possibly you will discard everything).

Body:
I'm using Python 3.7 and Django 2.0.  I want to strip out non-UTF-8 characters from a string, that I'm obtaining by reading this CSV file.  I tried this ...

web_site = row['website'].strip().encode("utf-8", 'ignore').decode("utf-8")

but this doesn't seem to be doing the job, since I have a resulting string that looks like ...

web_site: "wbez.org<200e>"

Whatever this "<200e>" thing is, is evidently non-UTF-8 string, because when I try and insert this into a MySQL database (deployed as a docker image), I get the following error ...

web_1     | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/seed_data.yaml': Could not load maps.Coop(pk=191): (1366, "Incorrect string value: '\\xE2\\x80\\x8E' for column 'web_site' at row 1")


问:
Executing DB2 commands '' db2start: command not found ''
I have one virtual server running on centos7. I configure it for the Nagios monitoring tool. I created the config file etc. I have 9 DB instances. When I migrated the DB config file with Nagios(adding to the Nagios )

I saw this error code on http://mysiteipaddr/nagios

CRITICAL - cannot connect to db.ipaddress.com. install_driver(DB2) failed: Can't locate DBD/DB2.pm in @INC (@INC contains: /usr/local/nagios/libexec /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 10) line 3.

After this error, I realize the DB2 is not installed on my machine. I've installed the DB2 drivers and when I execute this command I'm facing this output.

```<code> db2ls
-------------------------------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7                11.1.1.1        1                            Fri Jan 31 11:33:28 2020 +03             0
[root@backup ~]#
</code>```

But when I want to execute DB2 command like db2start, db2stop, db2status, it won't execute and I got this error code.

```<code>bash: db2stop: command not found
bash: db2start:command not found
</code>```

答: Please check the folder /home/tobe/sqllib/adm for db2start and db2stop commands. You can also define an alias if you want to call them directly.</p>

Body:
I have one virtual server running on centos7. I configure it for the Nagios monitoring tool. I created the config file etc. I have 9 DB instances. When I migrated the DB config file with Nagios(adding to the Nagios )

I saw this error code on http://mysiteipaddr/nagios

CRITICAL - cannot connect to db.ipaddress.com. install_driver(DB2) failed: Can't locate DBD/DB2.pm in @INC (@INC contains: /usr/local/nagios/libexec /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 10) line 3.

After this error, I realize the DB2 is not installed on my machine. I've installed the DB2 drivers and when I execute this command I'm facing this output.

 db2ls
-------------------------------------------------------------------------------------------------------------------
/opt/ibm/db2/V9.7                11.1.1.1        1                            Fri Jan 31 11:33:28 2020 +03             0
[root@backup ~]#

But when I want to execute DB2 command like db2start, db2stop, db2status, it won't execute and I got this error code.

bash: db2stop: command not found
bash: db2start:command not found


问:
Set default value with type Union
I want to use type checking using mypy. One input argument to a function accepts either a single int or a List[int].

I could use x: Union[int, List[int]], however, what is the correct syntax to set a default value of 10, if the input argument is a single int?

x: Union[int = 10, List[int]] is not working.

答:
The default value is not part of the type hint. It goes after the type hint, same as for a non-union type:

```<code>x: Union[int, List[int]] = 10
</code>```

Note the divergence in formatting from PEP-8 convention: whereas default values are usually given without spaces surrounding the = (i.e. as x=10), this is no longer true when they go after type hints according to PEP-484.

Title: Set default value with type Union

Body:
The default value is not part of the type hint. It goes after the type hint, same as for a non-union type:

x: Union[int, List[int]] = 10

Note the divergence in formatting from PEP-8 convention: whereas default values are usually given without spaces surrounding the = (i.e. as x=10), this is no longer true when they go after type hints according to PEP-484.


问:
How to filter rows containing a similar pattern
i have this dataframe in pandas:

```<code>               Value    Date
ISIN
TRT010213A15    10    2019-11-15
TRT010213T23    100   2019-11-15
TRT010213T23    70    2019-12-20
TRT080328T15    150   2018-10-12
TRT080420T12    175   2018-05-11
TRT150120T16    150   2019-08-29
TRT150120A05    15    2019-11-18
TRT150120T16    300   2019-10-15
TRT150120T16    275   2019-11-18
</code>```

How to get the difference (subtraction) between "Values" columns if both the first 9 characters of the indixes ("ISIN") and the values in the "Date" column are same. Subtraction will be held between indexes that have "T" on the 10th character and "A" on the 10th character.

e.g. first 9 characters of first and second indexes are "TR010213" and "Date" values are "2019-11-15". In this case new value of "Value" for second row (cause 10th char of index is "T") should be 90(100-10) and "Value" for first row (10th char of index is "A") will not be changed.

I wanna get this dataframe:

```<code>                Value   Date
ISIN
TRT010213A15    10  2019-11-15
TRT010213T23    90  2019-11-15
TRT010213T23    70  2019-12-20
TRT080328T15    150 2018-10-12
TRT080420T12    175 2018-05-11
TRT150120T16    150 2019-08-29
TRT150120A05    15  2019-11-18
TRT150120T16    300 2019-10-15
TRT150120T16    260 2019-11-18
</code>```

Body:
i have this dataframe in pandas:

               Value    Date
ISIN
TRT010213A15    10    2019-11-15
TRT010213T23    100   2019-11-15
TRT010213T23    70    2019-12-20
TRT080328T15    150   2018-10-12
TRT080420T12    175   2018-05-11
TRT150120T16    150   2019-08-29
TRT150120A05    15    2019-11-18
TRT150120T16    300   2019-10-15
TRT150120T16    275   2019-11-18

How to get the difference (subtraction) between "Values" columns if both the first 9 characters of the indixes ("ISIN") and the values in the "Date" column are same. Subtraction will be held between indexes that have "T" on the 10th character and "A" on the 10th character.

e.g. first 9 characters of first and second indexes are "TR010213" and "Date" values are "2019-11-15". In this case new value of "Value" for second row (cause 10th char of index is "T") should be 90(100-10) and "Value" for first row (10th char of index is "A") will not be changed.

I wanna get this dataframe:

                Value   Date
ISIN
TRT010213A15    10  2019-11-15
TRT010213T23    90  2019-11-15
TRT010213T23    70  2019-12-20
TRT080328T15    150 2018-10-12
TRT080420T12    175 2018-05-11
TRT150120T16    150 2019-08-29
TRT150120A05    15  2019-11-18
TRT150120T16    300 2019-10-15
TRT150120T16    260 2019-11-18

Body:
IIUC, you can use df.index.str[:9] to get the first 9 characters, and groupby().shift():

df['Value'] -= df.groupby([df.index.str[:9], df['Date']]).Value.shift().fillna(0)

Output:

              Value        Date
ISIN
TRT010213A15   10.0  2019-11-15
TRT010213T23   90.0  2019-11-15
TRT010213T23   70.0  2019-12-20
TRT080328T15  150.0  2018-10-12
TRT080420T12  175.0  2018-05-11
TRT150120T16  150.0  2019-08-29
TRT150120A05   15.0  2019-11-18
TRT150120T16  300.0  2019-10-15
TRT150120T16  260.0  2019-11-18

Note: for some reason, groupby().diff() doesn't work for me.


问:
Storing large numbers of images in a database? A good experience?
I'm writing an app which will store a large number of image (and possibly video) files. After they're uploaded they will be immediately pushed out to some cloud serving CDN for actual serving to the public. The idea is to have the images stored in a reliable, back-uppable store. I would anticipate of the order of 200,000 objects of up to 10KB each and possibly fewer video files of a few MB.

By default I would go to Postgres which the documentation suggests would be ok.

Is this is a sensible idea?

Will it make backing up the database a complete nightmare. Experiences?

Any reliability issues?

Will this affect the performance for other parts of the db? Bear in mind that the db will only be hit once or twice for each image.

答: I've got experience with storing images in a database this way in Oracle and MySQL. Performance and reliability are not an issue. Backing up is. Your backup will get very large. Since backing up is time consuming and expensive, it might be a good idea to save space. If that means you can shrink your database by 80% by just removing the images from the database, it might be a good idea to store them elsewhere. Backing up separate files is more efficient, because you can easily create incremental backups containing only new and modified images.</p>


问:
Date in response is different than from MongoDB
I am using Mongoose as MongoDB client, with Node and I am getting the date in respnse with -5:30 time.

Date in DB

```<code>"createdAt" : ISODate("2020-02-18T05:17:43.368+05:30"),
</code>```

Date in Response

```<code>"createdAt": "2020-02-17T23:47:43.368Z"
</code>```

It is affecting my applications data. is there any way to get the date as it is in the
DataBase.
Thanks.
Please write if more information required.

Mongoose Schema

```<code>const price = Schema({

}, {
  timestamps: true
})
</code>```

Query

```<code>  return Price.find(obj)
  .sort({
    _id: -1
  })
  .limit(parseInt(query.size) || 100)
  .skip((parseInt(query.size) || 100) * (parseInt(query.page) || 0))
  .populate('item')
  .lean()
</code>```

Server timedatectl

```<code>Local time: Wed 2020-02-19 12:47:29 IST
Universal time: Wed 2020-02-19 07:17:29 UTC
RTC time: Wed 2020-02-19 07:17:29
Time zone: Asia/Kolkata (IST, +0530)
System clock synchronized: yes
ystemd-timesyncd.service active: yes
RTC in local TZ: no
</code>```

答:
MongoDB stores dates as 64-bit integers, which means that Mongoose does not store timezone information by default,so when you query the collection with server then the JavaScript runtime will convert your collection tag to your OS timezone (default local timezone)

You can check with

```<code>console.log(process.env.TZ)
</code>```

So if you want your response same like database just set timezone to utc

Body:
I am using Mongoose as MongoDB client, with Node and I am getting the date in respnse with -5:30 time.

Date in DB

"createdAt" : ISODate("2020-02-18T05:17:43.368+05:30"),

Date in Response

"createdAt": "2020-02-17T23:47:43.368Z"

It is affecting my applications data. is there any way to get the date as it is in the
DataBase.
Thanks.
Please write if more information required.

Mongoose Schema

const price = Schema({

}, {
  timestamps: true
})

Query

  return Price.find(obj)
  .sort({
    _id: -1
  })
  .limit(parseInt(query.size) || 100)
  .skip((parseInt(query.size) || 100) * (parseInt(query.page) || 0))
  .populate('item')
  .lean()

Server timedatectl

Local time: Wed 2020-02-19 12:47:29 IST
Universal time: Wed 2020-02-19 07:17:29 UTC
RTC time: Wed 2020-02-19 07:17:29
Time zone: Asia/Kolkata (IST, +0530)
System clock synchronized: yes
ystemd-timesyncd.service active: yes
RTC in local TZ: no

Body:
MongoDB stores dates as 64-bit integers, which means that Mongoose does not store timezone information by default,so when you query the collection with server then the JavaScript runtime will convert your collection tag to your OS timezone (default local timezone)

You can check with

console.log(process.env.TZ)

So if you want your response same like database just set timezone to utc


问:
Metrics for spring boot rest api
I have a spring boot app with some REST APIs. I would like to collect usage metrics on these APIs. Metrics would be like how many times did a user hit the service in a time period. The user id is available in request header. Is there any framework that will help me with this reducing the boiler plate? Will splunk help?</p>

答:
Spring Boot Actuator seems what you need to have these metrics available. Here are some resources to get you started:

https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-enabling

https://www.baeldung.com/spring-boot-actuators

On top of the pre-defined metrics, you also have the ability to define custom metrics. Here's an answer to that: Spring boot actuator - Implement custom metrics

Title: Metrics for spring boot rest api