问:
How can I turn an Arc<Result<T, E>> into an Arc<Option<T>>?
Is it possible to implement this function correctly?

```<code>        fn ok<T, E>(arc: Arc<Result<T, E>>) -> Arc<Result<T, ()>> {
            // ?
        }
</code>```

My use case is that I want to pass the Result into a function that doesn't know or care about the error type for the result. Which seems like a main use case for result.ok() but I can't get it to work for Arc. Any attempt to dereference the arc and repackage its T leads (understandably) to a cannot move out of Arc compiler error.

UPDATE: hoping to do this without cloning the underlying data.

答:
An Arc provides "shared ownership", i.e. it allows multiple places to hold onto some data without being tied to the lifetime of any particular stack frame.

So in short, yes, it's possible to do this, but you will need to clone the underlying data, so something like:

fn convert<T: Clone, E: Clone>(arc: Arc<Result<T, E>>) -> Arc<Option<T>> {
    // explicit types added for clarity
    let result: &Result<T, E> = arc.as_ref();
    let cloned_result: Result<T, E> = Result::clone(result);
    Arc::new(cloned_result.ok())
}
```

But this might not be what you want, since these Arcs are now pointing to different underlying data; changes to the Arc<Result<T, E>> instances will not be reflected in Arc<Option<T>> instances.

If you are the author of the function you're passing it into, perhaps that function could be made be generic over its error parameter? If it truly doesn't care about the type of the error, this shouldn't cause any issues, otherwise you might need to add some trait bounds.

Body:
Is it possible to implement this function correctly?

        fn ok<T, E>(arc: Arc<Result<T, E>>) -> Arc<Result<T, ()>> {
            // ?
        }

My use case is that I want to pass the Result into a function that doesn't know or care about the error type for the result. Which seems like a main use case for result.ok() but I can't get it to work for Arc. Any attempt to dereference the arc and repackage its T leads (understandably) to a cannot move out of Arc compiler error.

UPDATE: hoping to do this without cloning the underlying data.

Body:
An Arc provides "shared ownership", i.e. it allows multiple places to hold onto some data without being tied to the lifetime of any particular stack frame.

So in short, yes, it's possible to do this, but you will need to clone the underlying data, so something like:

fn convert<T: Clone, E: Clone>(arc: Arc<Result<T, E>>) -> Arc<Option<T>> {
    // explicit types added for clarity
    let result: &Result<T, E> = arc.as_ref();
    let cloned_result: Result<T, E> = Result::clone(result);
    Arc::new(cloned_result.ok())
}

But this might not be what you want, since these Arcs are now pointing to different underlying data; changes to the Arc<Result<T, E>> instances will not be reflected in Arc<Option<T>> instances.

If you are the author of the function you're passing it into, perhaps that function could be made be generic over its error parameter? If it truly doesn't care about the type of the error, this shouldn't cause any issues, otherwise you might need to add some trait bounds.


来源: stackexchange

问:
Blocking calls with Gevent and WSGI
I've just started working with coroutines and have read up on gevent and greenlets. For a test I served this code through gevents pywsgi module:

```<code>from gevent.pywsgi import WSGIServer
import gevent

def hello_world(env, start_response):
    gevent.sleep(5)
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["<b>hello world</b>"]

print 'Serving on 8088...'
WSGIServer(('127.0.0.1', 8888), hello_world).serve_forever()
</code>```

I expected a result where every request would get a 5 second delay before the text is displayed. However, what happens is that every request gets queued up with the call to gevent.sleep() which makes a second request take almost 10 seconds if it was initiated immediately after the first one.

Isn't the serve_forever function spawning new greenlets for every request?

答:
The browsers are known to queue requests to the same domain.

Try opening different browsers (not different browser windows, actually different applications, e.g. FF and Chrome) for different connections.

ContentLicense: CC BY-SA 3.0

Title: Blocking calls with Gevent and WSGI

Body:
I've just started working with coroutines and have read up on gevent and greenlets. For a test I served this code through gevents pywsgi module:

from gevent.pywsgi import WSGIServer
import gevent

def hello_world(env, start_response):
    gevent.sleep(5)
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ["hello world"]

print 'Serving on 8088...'
WSGIServer(('127.0.0.1', 8888), hello_world).serve_forever()

I expected a result where every request would get a 5 second delay before the text is displayed. However, what happens is that every request gets queued up with the call to gevent.sleep() which makes a second request take almost 10 seconds if it was initiated immediately after the first one.

Isn't the serve_forever function spawning new greenlets for every request?


问:
Dynamic variable declaration. Is this even the right method?
A little new to JS so be gentle :)

I'm trying to create a program that holds 5000+ boolean values that dynamically change based on other vars.

const chars = "abcdefghijklmnopqrstuvwxyz0";
const charsC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
const maxNum = 48;
const maxTile = 6;
var tile1, tile2, tile3, tile4, tile5, tile6
// test vars
var tile4 = "A27"
var t4a27 = false

// this snippet will be in an interval loop
for (let i = 1; i <= maxTile; ++i) {
    for (let n = 0; n < chars.length; ++n) {
        for (let j = 1; j <= maxNum; ++j) {
            // this obviously doesnt work
            var t[i][`${chars[n]}`][j];
            // ^ ^ ^
            if (tile[i] == `${charsC[n]}${j}`) {
                t[i][h][j] = true;
                console.log(t4a27)
            } else {
                t[i][h][j] = false;
            }
        }
    }
}```

For clarification a better word than "tile" for the vars could be "sprite" rather because its a point on the sprite.

The basic concept is the tile vars are designed to output their current position as a string value e.g. "A27". Then this loop will take that information and scan each tile subset to be true/false. So if the sprite lower right quadrant is inside "A27" the output would be t4a27 = true

In practice I can do this with just a lot of code (over 20,000 lines) but I figured their has to be an easier way that requires far less code.

答:
Javascript doesn't have this kind of ability to reflect local variables.

What you can do is attach all those variables to a global object, and proceed with: Object.keys(your_object) and your_object[key_name_here] = ...

ContentLicense: CC BY-SA 4.0

Body:
A little new to JS so be gentle :)

I'm trying to create a program that holds 5000+ boolean values that dynamically change based on other vars.

const chars = "abcdefghijklmnopqrstuvwxyz0";
const charsC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
const maxNum = 48;
const maxTile = 6;
var tile1, tile2, tile3, tile4, tile5, tile6
// test vars
var tile4 = "A27"
var t4a27 = false

// this snippet will be in an interval loop
for (let i = 1; i <= maxTile; ++i) {
    for (let n = 0; n < chars.length; ++n) {
        for (let j = 1; j <= maxNum; ++j) {
            // this obviously doesnt work
            var t[i][`${chars[n]}`][j];
            // ^ ^ ^
            if (tile[i] == `${charsC[n]}${j}`) {
                t[i][h][j] = true;
                console.log(t4a27)
            } else {
                t[i][h][j] = false;
            }
        }
    }
}

For clarification a better word than "tile" for the vars could be "sprite" rather because its a point on the sprite.

The basic concept is the tile vars are designed to output their current position as a string value e.g. "A27". Then this loop will take that information and scan each tile subset to be true/false. So if the sprite lower right quadrant is inside "A27" the output would be t4a27 = true

In practice I can do this with just a lot of code (over 20,000 lines) but I figured their has to be an easier way that requires far less code.


问:
Scala 3 : Finding functions with the given annotation
For Scala 3 macros, does anyone know of a way to find all functions with a given annotation?

For instance:

@fruit
def apple(): Int = ???

@fruit
def banana(): Int = ???

@fruit
def coconut(): Int = ???

@fruit
def durian(): Int = ???

def elephant(): Int = ???

@fruit
def fig(): Int = ???
```

I would want to find a list of apple, banana, coconut, durian, fig. They could be defined anywhere, but in my case they will all be in a single package.

答:
This solution will extract all the definitions with some annotation from a given package. I will leverage also the compile-time reflection.

This solution will extract all the definitions with some annotations from a given package. I will also leverage the compile-time reflection.
So, To solve your problem, we need to divide it in:

methods gathering from a package;

filter only methods with a given annotation;

transform symbols in function application.
I suppose that you can pass the package and the annotation (and also the return type) as a type argument. So the macro signature is something like that:

inline def findAllFunction[P, A <: ConstantAnnotation, R]: List[() => R] =
    ${Implementation.myMacroImpl[P, A, R]()}
```
<p>The first point is straightforward. we could extract all the methods defined as:</p>
<pre class="lang-scala prettyprint-override"><code>def methodsFromPackage(packageSymbol: Symbol): List[Symbol] =
  packageSymbol.declaredTypes
    .filter(_.isClassDef)
    .flatMap(_.declaredMethods)
</code>```

The second point is also quite easy. Symbol class has the method hasAnnotation that could be used in this case:

```<code>def methodsAnnotatatedWith(
    methods: List[Symbol],
    annotation: Symbol
): List[Symbol] =
  methods.filter(_.hasAnnotation(annotation))
</code>```

The last point is a little bit challenging. Here we should construct the method call. So we need to create the AST that correspond to the method call. Inspired by this example, we can call definition using Apply. Select and This serve to select the correct method that will be called:

```<code>def transformToFunctionApplication(methods: List[Symbol]): Expr[List[() => R]] =
  val appliedDef = methods
    .map(definition => Select(This(definition.owner), definition))
    .map(select => Apply(select, List.empty))
    .map(apply => '{ () => ${ apply.asExprOf[R] } })
  Expr.ofList(appliedDef)
</code>```

Here I used lamba call, if you want to return directly the value you should change the last two instructions:

```<code>def transformToFunctionApplication(methods: List[Symbol]): Expr[List[R]] =
  val appliedDef = methods
    .map(definition => Select(This(definition.owner), definition))
    .map(select => Apply(select, List.empty))
    .map(apply => apply.asExprOf[R])

  Expr.ofList(appliedDef)
</code>```

To sum up, the all methods could be defined as:

```<code>def myMacroImpl[P: Type, A: Type, R: Type]()(using
    Quotes
): Expr[List[() => R]] = {
  import quotes.reflect.*
  val annotation = TypeRepr.of[A].typeSymbol
  val moduleTarget = TypeRepr.of[P].typeSymbol

  def methodsFromPackage(packageSymbol: Symbol): List[Symbol] =
    packageSymbol.declaredTypes
      .filter(_.isClassDef)
      .flatMap(_.declaredMethods)

  def methodsAnnotatatedWith(
      methods: List[Symbol],
      annotation: Symbol
  ): List[Symbol] =
    methods.filter(_.hasAnnotation(annotation))

  def transformToFunctionApplication(
      methods: List[Symbol]
  ): Expr[List[() => R]] =
    val appliedDef = methods
      .map(definition => Select(This(definition.owner), definition))
      .map(select => Apply(select, List.empty))
      .map(apply => '{ () => ${ apply.asExprOf[R] } })
    Expr.ofList(appliedDef)

  val methods = methodsFromPackage(moduleTarget)
  val annotatedMethod = methodsAnnotatatedWith(methods, annotation)
  transformToFunctionApplication(annotatedMethod)
}

</code>```

Finally, you can use the macro as:

```<code>package org.tests
import org.tests.Macros.fruit

package foo {
  @fruit
  def check(): Int = 10
  @fruit
  def other(): Int = 11
}

@main def hello: Unit =
  println("Hello world!")
  println(Macros.findAllFunction[org.tests.foo, fruit, Int].map(_.apply())) /// List(10, 11)
</code>```

Scastie

Body:
For Scala 3 macros, does anyone know of a way to find all functions with a given annotation?

For instance:

@fruit
def apple(): Int = ???

@fruit
def banana(): Int = ???

@fruit
def coconut(): Int = ???

@fruit
def durian(): Int = ???

def elephant(): Int = ???

@fruit
def fig(): Int = ???

I would want to find a list of apple, banana, coconut, durian, fig. They could be defined anywhere, but in my case they will all be in a single package.

Body:
This solution will extract all the definitions with some annotation from a given package. I will leverage also the compile-time reflection.

This solution will extract all the definitions with some annotations from a given package. I will also leverage the compile-time reflection.
So, To solve your problem, we need to divide it in:

methods gathering from a package;

filter only methods with a given annotation;

transform symbols in function application.
I suppose that you can pass the package and the annotation (and also the return type) as a type argument. So the macro signature is something like that:

inline def findAllFunction[P, A <: ConstantAnnotation, R]: List[() => R] =
    ${Implementation.myMacroImpl[P, A, R]()}

The first point is straightforward. we could extract all the methods defined as:

def methodsFromPackage(packageSymbol: Symbol): List[Symbol] =
  packageSymbol.declaredTypes
    .filter(_.isClassDef)
    .flatMap(_.declaredMethods)

The second point is also quite easy. Symbol class has the method hasAnnotation that could be used in this case:

def methodsAnnotatatedWith(
    methods: List[Symbol],
    annotation: Symbol
): List[Symbol] =
  methods.filter(_.hasAnnotation(annotation))

The last point is a little bit challenging. Here we should construct the method call. So we need to create the AST that correspond to the method call. Inspired by this example, we can call definition using Apply. Select and This serve to select the correct method that will be called:

def transformToFunctionApplication(methods: List[Symbol]): Expr[List[() => R]] =
  val appliedDef = methods
    .map(definition => Select(This(definition.owner), definition))
    .map(select => Apply(select, List.empty))
    .map(apply => '{ () => ${ apply.asExprOf[R] } })
  Expr.ofList(appliedDef)

Here I used lamba call, if you want to return directly the value you should change the last two instructions:

def transformToFunctionApplication(methods: List[Symbol]): Expr[List[R]] =
  val appliedDef = methods
    .map(definition => Select(This(definition.owner), definition))
    .map(select => Apply(select, List.empty))
    .map(apply => apply.asExprOf[R])

  Expr.ofList(appliedDef)

To sum up, the all methods could be defined as:

def myMacroImpl[P: Type, A: Type, R: Type]()(using
    Quotes
): Expr[List[() => R]] = {
  import quotes.reflect.*
  val annotation = TypeRepr.of[A].typeSymbol
  val moduleTarget = TypeRepr.of[P].typeSymbol

  def methodsFromPackage(packageSymbol: Symbol): List[Symbol] =
    packageSymbol.declaredTypes
      .filter(_.isClassDef)
      .flatMap(_.declaredMethods)

  def methodsAnnotatatedWith(
      methods: List[Symbol],
      annotation: Symbol
  ): List[Symbol] =
    methods.filter(_.hasAnnotation(annotation))

  def transformToFunctionApplication(
      methods: List[Symbol]
  ): Expr[List[() => R]] =
    val appliedDef = methods
      .map(definition => Select(This(definition.owner), definition))
      .map(select => Apply(select, List.empty))
      .map(apply => '{ () => ${ apply.asExprOf[R] } })
    Expr.ofList(appliedDef)

  val methods = methodsFromPackage(moduleTarget)
  val annotatedMethod = methodsAnnotatatedWith(methods, annotation)
  transformToFunctionApplication(annotatedMethod)
}

Finally, you can use the macro as:

package org.tests
import org.tests.Macros.fruit

package foo {
  @fruit
  def check(): Int = 10
  @fruit
  def other(): Int = 11
}

@main def hello: Unit =
  println("Hello world!")
  println(Macros.findAllFunction[org.tests.foo, fruit, Int].map(_.apply())) /// List(10, 11)

Scastie


问:
Programmatically set android:layout_centerHorizontal
In xml you can do the following:

```<code><TextView
    ...
    android:layout_centerHorizontal="true"
    ...
/>
</code>```

How would I, when I have the instance of TextView, do this programmatically?

答:
Assume that txtPhone is the textview that we are trying to place it center in horizontal.

If you are using Java then use the following code,

```<code>RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txtPhone.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
txtPhone.setLayoutParams(layoutParams);
</code>```

If you are using Kotlin then use the following code,

```<code>val layoutParams = txtPhone.getLayoutParams() as RelativeLayout.LayoutParams
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
txtPhone.setLayoutParams(layoutParams)
</code>```

Body:
In xml you can do the following:

<TextView
    ...
    android:layout_centerHorizontal="true"
    ...
/>

How would I, when I have the instance of TextView, do this programmatically?

Body:
Assume that txtPhone is the textview that we are trying to place it center in horizontal.

If you are using Java then use the following code,

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txtPhone.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
txtPhone.setLayoutParams(layoutParams);

If you are using Kotlin then use the following code,

val layoutParams = txtPhone.getLayoutParams() as RelativeLayout.LayoutParams
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL)
txtPhone.setLayoutParams(layoutParams)


问:
What is the best way to compare a value against 'undefined'?
Is there any differences between

```<code>var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")
</code>```

Which one should we use?

答:
If you declare var a, then it won't be undefined any more - it will be null instead.  I usually use typeof a == undefined - and it works fine.  This is especially useful in this situation:

```<code>function myfunc(myvar)
{
    if(typeof myvar == "undefined")
    {
        //the function was called without an argument, simply as myfunc()
    }
}
</code>```

Body:
Is there any differences between

var a;
(a == undefined)
(a === undefined)
((typeof a) == "undefined")
((typeof a) === "undefined")

Which one should we use?

Body:
If you declare var a, then it won't be undefined any more - it will be null instead.  I usually use typeof a == undefined - and it works fine.  This is especially useful in this situation:

function myfunc(myvar)
{
    if(typeof myvar == "undefined")
    {
        //the function was called without an argument, simply as myfunc()
    }
}


问:
Teradata: UPDATE failed. 7547: Target row updated by multiple source rows
Table1 contains id, date, flag.
Table2 contains id, date_from, date_to + some other attributes

Attribute flag from Table1 has to be updated with the following logic:

```<code>UPDATE t1 from Table1 t1, Table2 t2
SET flag = 1
WHERE t1.id = t2.id and t1.date between t2.date_from and t2.date_to
</code>```

The result is error 7547: Target row updated by multiple source rows.
Obviously, the problem is that Table2 contains intersecting intervals.
How to rewrite query to update the flag in this case?

答:
Switch to a Correlated Subquery

```<code>UPDATE t1
SET flag = 1
WHERE EXISTS
 ( SELECT 1
   FROM Table2 as t2
   where t1.id = t2.id
     and t1.date between t2.date_from and t2.date_to
 )
</code>```

Or fix your bad source data :-)

Body:
Table1 contains id, date, flag.
Table2 contains id, date_from, date_to + some other attributes

Attribute flag from Table1 has to be updated with the following logic:

UPDATE t1 from Table1 t1, Table2 t2
SET flag = 1
WHERE t1.id = t2.id and t1.date between t2.date_from and t2.date_to

The result is error 7547: Target row updated by multiple source rows.
Obviously, the problem is that Table2 contains intersecting intervals.
How to rewrite query to update the flag in this case?

Body:
Switch to a Correlated Subquery

UPDATE t1
SET flag = 1
WHERE EXISTS
 ( SELECT 1
   FROM Table2 as t2
   where t1.id = t2.id
     and t1.date between t2.date_from and t2.date_to
 )

Or fix your bad source data :-)


问:
ValidateForm class in Struts 1.X
Using the ValidateForm from Struts 1, we will be able to validate the FORM used in the Struts,
I went through number of links (https://cwe.mitre.org/data/definitions/103.html) still not able to figure the functionality of super.validate() method in Struts

Default Validation  (using super.validate() in Struts):

```<code>public class RegistrationForm extends org.apache.struts.validator.ValidatorForm {
// private variables for registration form
private String name;
private String email;
...

public RegistrationForm() {
super();
}

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = super.validate(mapping, request);
if (errors == null) {
    errors = new ActionErrors();
}
return errors;
}
// getter and setter methods for private variables
}
</code>```

In the above code what is the significance of super.validate() method, What is the validation does it perform? Could someone explain this please!

答:
It performs validation of request parameters according to the rules defined in validation.xml. It provides the basic validation and if you want to use a custom validation then you should override its validate() method.  Here's the description of the method:

Validate the properties that have been set from this HTTP request, and return an ActionErrors object that encapsulates any validation errors that have been found.  If no errors are found, return null or an ActionErrors object with no recorded error messages.

What happens if you override validate() and not calling super.validate():

It will cancel the Struts validation if you override the validate method and not call the super.validate(mapping, request). Do it in your code to coexist the custom validation through validate() method and framework validation via validation.xml.

Title: ValidateForm class in Struts 1.X

Body:
Using the ValidateForm from Struts 1, we will be able to validate the FORM used in the Struts,
I went through number of links (https://cwe.mitre.org/data/definitions/103.html) still not able to figure the functionality of super.validate() method in Struts

Default Validation  (using super.validate() in Struts):

public class RegistrationForm extends org.apache.struts.validator.ValidatorForm {
// private variables for registration form
private String name;
private String email;
...

public RegistrationForm() {
super();
}

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = super.validate(mapping, request);
if (errors == null) {
    errors = new ActionErrors();
}
return errors;
}
// getter and setter methods for private variables
}

In the above code what is the significance of super.validate() method, What is the validation does it perform? Could someone explain this please!


问:
Create the same Blazor app with both WASM and Server-Side
I would like create a blazor app (two apps actually) that supports both Hosted WASM and Server-Side. They do not need to be a single app that dynamically switch. Actually, I would prefer two separate apps like wasm.myapp.com and server.myapp.com. Users can pick which flavor they prefer to use based on their network environment. Also based on business needs, I could pick one flavor over the other for different scenarios (like browser limitations).

Anyway, is it possible to create two apps that are sharing the same components? Either one app is a shell that references the other app (or vice versa), or two shell apps that reference a third project? Basically the goal is to create one set of UI components/pages that will be shared by both apps.

How do you set it up?

Thanks for any tips.

答:
You need to split your code out into a set of library projects and end point Web projects. Providing a comprehensive answer to this question is beyond the scope of a StackOverflow answer. I'll show the basics here with some project screen shots to show project structure and content, and provide a link to the detailed code in a GitHub Repo at the bottom.

Libraries

Blazor.App contains all the shared code.  I split this out into three projects to apply Clean Design principles so I have:

Blazor.Core - standard Library project

Blazor.Data - standard Library project - dependency to Core

Blazor.UI - Razor Library project - dependency to Core

Blazor Server

The Blazor.Server.Web project is the end point project to run the Blazor Server application.  Dependencies to Core, Data and UI.

Blazor WASM

Blazor.WASM is a Blazor WebAssembly project to build out the WASM code base - dependency on Core, Data and UI.

Blazor.WASM.Web is a AspNetCore web server to host the API and service point for the WASM application - dependency on Core, Data and Controllers.

Blazor.Controllers contains the controllers -  - dependency on Core and Data.

The principle differences between the two applications is in the data pipeline.  Interfaces are used to define the Data Brokers to provide abstraction.  The Server project uses the Server data brokers.  The WASM Server API Controllers use the Server data brokers while the WASM application uses the API data brokers.  The different projects load the relevant data broker as the IDataBroker service.

Here's a set of screen shots of the different projects:

Controllers

Core

Data

UI

Server.Web

WASM

WASM.Web

Link to the Repo - https://github.com/ShaunCurtis/Blazr.Demo


问:
How to join multiple data frames using dplyr?
I want to left_join multiple data frames:

```<code>dfs <- list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, b = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)
Reduce(left_join, dfs)
#   a b  c  d
# 1 1 a  4 NA
# 2 2 b NA  7
# 3 3 c  5  8
</code>```

This works because they all have the same b column, but Reduce doesn't let me specify additional arguments that I can pass to left_join. Is there a work around for something like this?

```<code>dfs <- list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, d = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)
</code>```

Update

This kind of works: Reduce(function(...) left_join(..., by = c("b" = "d")), dfs) but when by is more than one element it gives this error: Error: cannot join on columns 'b' x 'd': index out of bounds

答:
Yet another solution:</p>
```<code>library(purrr)
library(dplyr)

dfs = list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, b = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)

purrr::reduce(dfs, dplyr::left_join, by = 'b')

</code>```

Body:
I want to left_join multiple data frames:

dfs <- list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, b = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)
Reduce(left_join, dfs)
#   a b  c  d
# 1 1 a  4 NA
# 2 2 b NA  7
# 3 3 c  5  8

This works because they all have the same b column, but Reduce doesn't let me specify additional arguments that I can pass to left_join. Is there a work around for something like this?

dfs <- list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, d = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)

Update

This kind of works: Reduce(function(...) left_join(..., by = c("b" = "d")), dfs) but when by is more than one element it gives this error: Error: cannot join on columns 'b' x 'd': index out of bounds

Body:
Yet another solution:

library(purrr)
library(dplyr)

dfs = list(
  df1 = data.frame(a = 1:3, b = c("a", "b", "c")),
  df2 = data.frame(c = 4:6, b = c("a", "c", "d")),
  df3 = data.frame(d = 7:9, b = c("b", "c", "e"))
)

purrr::reduce(dfs, dplyr::left_join, by = 'b')


问:
push first commit on develop branch and main branch clean
I would like to push my first commit on develop branch and then create a clean main or master branch.

Before push my first commit I use this command to create my develop branch from HEAD

```<code>git symbolic-ref HEAD refs/heads/develop
</code>```

When I push my commit on Github only develop branch exists. It is exactly what I want.

But if I create a main branch, the branch is not empty, they are the same files than my develop branch. It is not what I want.

Below a representation of what I want.

```<code>main    ======> Clean
develop ======> myFirstCommit
</code>```

Thanks a lot for your help.

答: Branches are a file under .git/refs/heads/ that contain a reference to a commit. The branch that .git/HEAD points to moves along if you add new commits. There is nothing like an empty branch. As long as both refs point to the root of the repo, the two branches will always be the same.</p>

Body:
I would like to push my first commit on develop branch and then create a clean main or master branch.

Before push my first commit I use this command to create my develop branch from HEAD

git symbolic-ref HEAD refs/heads/develop

When I push my commit on Github only develop branch exists. It is exactly what I want.

But if I create a main branch, the branch is not empty, they are the same files than my develop branch. It is not what I want.

Below a representation of what I want.

main    ======> Clean
develop ======> myFirstCommit

Thanks a lot for your help.


问:
create an int column after dividing a column by a number in pandas
Assume that I have a panda data frame with a column that holds seconds.

I want to create a new column that holds minutes. so I divide the sec column by 60. The problem that I have is that min column is not an integer anymore. How can I make it an integer?

I have this code:

```<code>alldata['min']=alldata['sec']/60
</code>```

I tried this, but it did not work:

```<code>alldata['min']=int(alldata['sec']/60)
</code>```

I am getting this error:

```<code>TypeError: cannot convert the series to <class 'int'>
</code>```

I tried this:

```<code>alldata["min"] = pd.to_numeric(alldata["min"], downcast='integer')
</code>```

but I still have float values in min column.

How can have integer values for min? (Just drop the value to its floor value)

答:
You should just use whole integer division:</p>
```<code>alldata['min']=alldata['sec']//60
</code>```

Body:
Assume that I have a panda data frame with a column that holds seconds.

I want to create a new column that holds minutes. so I divide the sec column by 60. The problem that I have is that min column is not an integer anymore. How can I make it an integer?

I have this code:

alldata['min']=alldata['sec']/60

I tried this, but it did not work:

alldata['min']=int(alldata['sec']/60)

I am getting this error:

TypeError: cannot convert the series to <class 'int'>

I tried this:

alldata["min"] = pd.to_numeric(alldata["min"], downcast='integer')

but I still have float values in min column.

How can have integer values for min? (Just drop the value to its floor value)

Body:
You should just use whole integer division:

alldata['min']=alldata['sec']//60


问:
App Engine: Static Files Not Updating on Deploy
I pushed an HTML static file containing an Angular SPA as catch-all handler for my custom domain with this settings:

```<code>- url: /(api|activate|associate|c|close_fb|combine|import|password|sitemap)($|/.*)
  script: gae.php

- url: /.*
  static_files: public/static/app/v248/es/app.html
  upload: public/static/app/v248/es/app.html
  expiration: "1h"
</code>```

That worked fine, but if I push a new app.html it doesn't update. I've tried to change the local path, deploy a new app version, even replacing the catch-all handler with a custom php endpoint, but it doesn't work, the response still is the first version of app.html I uploaded.

Other people has had the same problem (CSS File Not Updating on Deploy (Google AppEngine)), and it looks like is related to Google CDN cache but, as far as I know, there isn't any way to flush it.

答:
Another problem that could be causing this is caching in Google's frontend, which depends on the cache header returned by your application. In my case, I opened Firefox's inspector on the Network tab, and saw that the stale file had a cache-control setting of 43200 seconds, i.e. 12 hours:

This was for a file returned from Flask, so I fixed this by explicitly specifying max-age in the Flask response from my GAE code:

return flask.send_from_directory(directory, filename, max_age=600)
```

This causes intermediate caches such as Google's frontend to only cache the file for a period of 600 seconds (10 minutes).

Unfortunately, once a file has been caches there is no way to flush it, so you will have to wait out the 12 hours. But it will solve the problem for the next time.

Body:
I pushed an HTML static file containing an Angular SPA as catch-all handler for my custom domain with this settings:

- url: /(api|activate|associate|c|close_fb|combine|import|password|sitemap)($|/.*)
  script: gae.php

- url: /.*
  static_files: public/static/app/v248/es/app.html
  upload: public/static/app/v248/es/app.html
  expiration: "1h"

That worked fine, but if I push a new app.html it doesn't update. I've tried to change the local path, deploy a new app version, even replacing the catch-all handler with a custom php endpoint, but it doesn't work, the response still is the first version of app.html I uploaded.

Other people has had the same problem (CSS File Not Updating on Deploy (Google AppEngine)), and it looks like is related to Google CDN cache but, as far as I know, there isn't any way to flush it.

Body:
Another problem that could be causing this is caching in Google's frontend, which depends on the cache header returned by your application. In my case, I opened Firefox's inspector on the Network tab, and saw that the stale file had a cache-control setting of 43200 seconds, i.e. 12 hours:

This was for a file returned from Flask, so I fixed this by explicitly specifying max-age in the Flask response from my GAE code:

return flask.send_from_directory(directory, filename, max_age=600)

This causes intermediate caches such as Google's frontend to only cache the file for a period of 600 seconds (10 minutes).

Unfortunately, once a file has been caches there is no way to flush it, so you will have to wait out the 12 hours. But it will solve the problem for the next time.


问:
How to show/hide @foreach statement
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

```
<p>I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).</p>
<p>I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?</p>
<p>-- EDIT --</p>
<p>I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

        <slot />

</template>

<script>
export default {
    name: "Dropdownitems",
    setup() {
        const showLinks = false;

        return {
            showLinks,
        };
    },
};
</script>

<style></style></code>```

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

```

答:
It's impossible to load Vue before PHP because your webpage only displays when full PHP code is received from the server. Therefore, we're never able to stop PHP or HTML from flashing if we're using them inside a reusable Vue component.

The solution I made is simply passing the value of the foreach loop as a prop to the Vue component in order for it to be displayed from there, not from my blade file.

Here's my code in blade after passing the value of the category name as a prop to my Vue component.

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/" category="All"></Dropdownitems>

        @foreach ($categories as $category)
            <Dropdownitems
                category="{{ $category->name }}"
                href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
            </Dropdownitems>
        @endforeach

    </Dropdowncontent>

</Dropdown>```
</div>
</div>
</p>
<p>Here is me displaying it from there the Vue dropdown items component:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><template>

        <slot>{{ category }}</slot>

</template>

<script>
export default {
    name: "Dropdownitems",
    props: ["category"],
};
</script>

<style></style></code>```

Title: How to show/hide @foreach statement

Body:
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).

I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?

-- EDIT --

I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:

<template>

        <slot />

</template>

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

Body:
It's impossible to load Vue before PHP because your webpage only displays when full PHP code is received from the server. Therefore, we're never able to stop PHP or HTML from flashing if we're using them inside a reusable Vue component.

The solution I made is simply passing the value of the foreach loop as a prop to the Vue component in order for it to be displayed from there, not from my blade file.

Here's my code in blade after passing the value of the category name as a prop to my Vue component.

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/" category="All"></Dropdownitems>

        @foreach ($categories as $category)
            <Dropdownitems
                category="{{ $category->name }}"
                href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
            </Dropdownitems>
        @endforeach

    </Dropdowncontent>

</Dropdown>

Here is me displaying it from there the Vue dropdown items component:

<template>
    <a href="" class="demogard categoryItems">
        <slot>{{ category }}</slot>
    </a>
</template>

<script>
export default {
    name: "Dropdownitems",
    props: ["category"],
};
</script>

<style></style>


问:
Rails / MYSQL QUERY returns value even with no record?
I have a bit of code to check if a record exists in the database, but my problem is that the variable keeps returning a result even with no records ..</p>

```<code>@page_of_book = Page.where({:number => @page, :parent_id => @book_id.id}).limit(1)

if !@page_of_book
# if no page, create a new page

end
</code>```

答:
Use .empty?, as where would always return an array. An empty array if no records exist.

```<code>if @page_of_book.empty?
# if no page, create a new page

end
</code>```

Body:
I have a bit of code to check if a record exists in the database, but my problem is that the variable keeps returning a result even with no records ..

@page_of_book = Page.where({:number => @page, :parent_id => @book_id.id}).limit(1)

if !@page_of_book
# if no page, create a new page

end

Body:
Use .empty?, as where would always return an array. An empty array if no records exist.

if @page_of_book.empty?
# if no page, create a new page

end


问:
Generate dictionary by template in inventory
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113
```
<p>Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):</p>
<pre class="lang-yaml prettyprint-override"><code>children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113
</code>```

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

答:
Q: "Need a thousand hosts (.e.g. 'child-1111' param: 'some-data-1111')"

A: Use ranges and constructed plugin. For example

shell> cat inventory/01-hosts
child-[1111:1113]
```
<pre class="lang-yaml prettyprint-override"><code>shell> cat inventory/02-constructed.yml
plugin: constructed
strict: True
groups:
  group_children: inventory_hostname.startswith('child-')
compose:
  param: "'some-data-' ~ inventory_hostname|split('-')|last"
</code>```

Test it

shell> ansible-inventory -i inventory --list --yaml
all:
  children:
    group_children:
      hosts:
        child-1111:
          param: some-data-1111
        child-1112:
          param: some-data-1112
        child-1113:
          param: some-data-1113
    ungrouped: {}
```
<p>and use it in a playbook</p>
<pre class="lang-yaml prettyprint-override"><code>- hosts: all
  tasks:
    - debug:
        var: param
</code>```

gives

ok: [child-1111] =>
  param: some-data-1111
ok: [child-1112] =>
  param: some-data-1112
ok: [child-1113] =>
  param: some-data-1113
```

Body:
At the moment I have the following inventory (simplified):

children:
    child-1111:
        param: some-data-1111
    child-1112:
        param: some-data-1112
    child-1113:
        param: some-data-1113

Of course, it's not good when you need a thousand hosts instead of just three and many parameters with substitutions. I would like to write something like this (which doesn't work):

children:
    "child-{{item}}":
        param: "some-data-{{item}}"
        loop:
            - 1111
            - 1112
            - 1113

All the examples I see always produce lists, not dictionaries.

Also, loop seems to work only for tasks, not inventories.

How do I achieve this?

Body:
Q: "Need a thousand hosts (.e.g. 'child-1111' param: 'some-data-1111')"

A: Use ranges and constructed plugin. For example

shell> cat inventory/01-hosts
child-[1111:1113]

shell> cat inventory/02-constructed.yml
plugin: constructed
strict: True
groups:
  group_children: inventory_hostname.startswith('child-')
compose:
  param: "'some-data-' ~ inventory_hostname|split('-')|last"

Test it

shell> ansible-inventory -i inventory --list --yaml
all:
  children:
    group_children:
      hosts:
        child-1111:
          param: some-data-1111
        child-1112:
          param: some-data-1112
        child-1113:
          param: some-data-1113
    ungrouped: {}

and use it in a playbook

- hosts: all
  tasks:
    - debug:
        var: param

gives

ok: [child-1111] =>
  param: some-data-1111
ok: [child-1112] =>
  param: some-data-1112
ok: [child-1113] =>
  param: some-data-1113


问:
NextJs + Material UI, manually refreshing causes "Warning: Prop `className` did not match. Server: "MuiTypography-root MuiLink"
I have a Next.js project that uses Material UI, if I run the server and make changes, hot reloading works fine but if I manually refresh the page all the styles mess up and I get the Warning: Prop className did not match. Server: "MuiTypography-root MuiLink...

This issue has been mentioned in Next.js issues on Github, and none of the proposed solutions work for me.

答:
It's a problem with Next.js and @material-ui.
The problem has something to do with SSR (Server Side Rendering) so you have to cancel it and remove the server side files.

step 1:
create _document.js under pages folder

step 2:
add this to the documents file

```<code>import { ServerStyleSheets } from '@material-ui/core';
import Document, { Head, Html, NextScript, Main } from 'next/document';
import React from 'react';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head></Head>
        <body>
          <Main></Main>
          <NextScript></NextScript>
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;
  ctx.renderPage = () => {
    return originalRenderPage({
      enchanceApp: (App) => (props) => sheets.collect(<App {...props} />),
    });
  };
  const initialProps = await Document.getInitialProps(ctx);
  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement(),
    ],
  };
};
</code>```

step 3:
inside the _app.js
add this inside the main function component

```<code>  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) jssStyles.parentElement.removeChild(jssStyles);
  }, []);
</code>```

restart the Next.js app
and you're done

Body:
It's a problem with Next.js and @material-ui.
The problem has something to do with SSR (Server Side Rendering) so you have to cancel it and remove the server side files.

step 1:
create _document.js under pages folder

step 2:
add this to the documents file

import { ServerStyleSheets } from '@material-ui/core';
import Document, { Head, Html, NextScript, Main } from 'next/document';
import React from 'react';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head></Head>
        <body>
          <Main></Main>
          <NextScript></NextScript>
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;
  ctx.renderPage = () => {
    return originalRenderPage({
      enchanceApp: (App) => (props) => sheets.collect(<App {...props} />),
    });
  };
  const initialProps = await Document.getInitialProps(ctx);
  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      sheets.getStyleElement(),
    ],
  };
};

step 3:
inside the _app.js
add this inside the main function component

  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) jssStyles.parentElement.removeChild(jssStyles);
  }, []);

restart the Next.js app
and you're done


问:
Retrofit GET Query with api key:
Hello I am trying to use Retrofit to access a URL : https://my.api.mockaroo.com/products?key=57b501f0

here is my interface:

```<code>interface ProductInterface {
    @GET("products?")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}
</code>```

here is my Retrofit Object

```<code>object RetrofitInstance {
    val api: ProductInterface by lazy<ProductInterface> {
        Log.e("Request", "Sent")
        Retrofit.Builder()
            .baseUrl("https://my.api.mockaroo.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ProductInterface::class.java)
    }
}
</code>```

and here it is how i am accessing it:

```<code>RetrofitInstance.api.getTodos("57b501f0")
</code>```

But When i logged its working, It says following URL: https://my.api.mockaroo.com/products?&key=57b501f0

was accessed instead of : https://my.api.mockaroo.com/products?key=57b501f0

How can i resolve this?

答:
Try this way maybe:

```<code>interface ProductInterface {
    @GET("products?key=57b501f0")
    suspend fun getTodos(): Response<List<product>>
}
</code>```

AND instead of RetrofitInstance.api.getTodos("57b501f0") write

```<code>RetrofitInstance.api.getTodos()
</code>```

-----OR-----

Just remove the question mark after products.

```<code>interface ProductInterface {
    @GET("products")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}
</code>```

Title: Retrofit GET Query with api key:

Body:
Hello I am trying to use Retrofit to access a URL : https://my.api.mockaroo.com/products?key=57b501f0

here is my interface:

interface ProductInterface {
    @GET("products?")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}

here is my Retrofit Object

object RetrofitInstance {
    val api: ProductInterface by lazy<ProductInterface> {
        Log.e("Request", "Sent")
        Retrofit.Builder()
            .baseUrl("https://my.api.mockaroo.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ProductInterface::class.java)
    }
}

and here it is how i am accessing it:

RetrofitInstance.api.getTodos("57b501f0")

But When i logged its working, It says following URL: https://my.api.mockaroo.com/products?&key=57b501f0

was accessed instead of : https://my.api.mockaroo.com/products?key=57b501f0

How can i resolve this?

Body:
Try this way maybe:

interface ProductInterface {
    @GET("products?key=57b501f0")
    suspend fun getTodos(): Response<List<product>>
}

AND instead of RetrofitInstance.api.getTodos("57b501f0") write

RetrofitInstance.api.getTodos()

-----OR-----

Just remove the question mark after products.

interface ProductInterface {
    @GET("products")
    suspend fun getTodos(@Query("key") key: String): Response<List<product>>
}


问:
Laravel (Lumen) connect to database on another server on same network
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();
```
<p>And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:</p>
<h3>Attempt 1</h3>
```DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] No route to host</p>
</blockquote>
<h3>Attempt 2</h3>
```DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```
<blockquote>
<p>PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'</p>
</blockquote>
<h3>Attempt 3</h3>
```DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass
```

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.

答:
I've found the cause. Was missing the square brackets at the beginning and end of DB_HOST e.g:

```<code>DB_HOST=[my ipv6]
</code>```

Body:
I've got a Laravel project on a server, and a Laravel Lumen 8 project on another server, they're both virtual machines and are clones of one another so have the same hardware and OS.

I have a domain, which for the purposes of this Stackoverflow we'll call foo.com, it goes through Cloudflare, both servers are ipv6 servers and when pinging each other via ssh they can see each other just fine.

The problem I have is with connecting to the MySQL (Maria DB) database from my Lumen project on the other server.

I've tried using:

The domain of the server where the DB exists

The ipv6 domain

The VM's local ipv4 address since both servers exist on the same network this is how they can see each other

I'm testing the connection using Tinker and running:

DB::connection()->getPdo();

And I'm unable to connect for some reason, these are the combinations and errors I've encountered and would like to know what I'm missing:

Attempt 1

DB_CONNECTION=mysql
DB_HOST=local ipv4
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] No route to host

Attempt 2

DB_CONNECTION=mysql
DB_HOST=ipv6 address
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Invalid argument'

Attempt 3

DB_CONNECTION=mysql
DB_HOST=api.foo.com
DB_PORT=3306
DB_DATABASE=my_db
DB_USERNAME=user
DB_PASSWORD=pass

PDOException with message 'SQLSTATE[HY000] [2002] Connection timed out'

How can I get my Lumen project to connect to my Laravel database on another server, I'm pretty sure I've tried every combination here.

Body:
I've found the cause. Was missing the square brackets at the beginning and end of DB_HOST e.g:

DB_HOST=[my ipv6]


问:
How to make swagger examples component with allOf

components:
 examples:
    J:
      value:
        name: my name

    J2:
      value:
        allOf:
          - $ref: '#/components/examples/J'
          - id: 123
```
<p>Use J2 in response body examples:</p>
<pre class="lang-yaml prettyprint-override"><code>responses:
  200:
    content:
      application/json:
        examples:
          test:
            $ref: '#/components/examples/J2'
</code>```

Current result:

{
  "$ref": "#/components/examples/J",
  "id": 123
}
```
<p>Expected result</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "my name",
  "id": 123
}
</code>```

Related:
https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/

Swagger schema properties ignored when using $ref - why?

答:
This is not supported.

The value is meant to be the literal value of the example. As a result, value does not support allOf and $ref. OpenAPI does not have a way to merge the values of multiple example components.

Body:
components:
 examples:
    J:
      value:
        name: my name

    J2:
      value:
        allOf:
          - $ref: '#/components/examples/J'
          - id: 123

Use J2 in response body examples:

responses:
  200:
    content:
      application/json:
        examples:
          test:
            $ref: '#/components/examples/J2'

Current result:

{
  "$ref": "#/components/examples/J",
  "id": 123
}

Expected result

{
  "name": "my name",
  "id": 123
}

Related:
https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/

Swagger schema properties ignored when using $ref - why?


问:
Change value Array of Objects in mulesoft
I am beginner for mulesoft I have output payload transform message as below but I have to replace inside promotions array planChangeRequired attribute value as true always, can some one help me how can we replace it.

output Payload

```<code>{
  "content": {
    "data": {
      "sharedDataGroups": [
        {
          "empId": 100,
          "empName": "Ram"
        },
        {
          "empId": 200,
          "empName": "Santhosh"
        }
      ],
      "promotions": [
        {
          "id": "14400007",
          "discount": 10.0,
          "planChangeRequired": false
        }
      ]
    }
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}
</code>```

Expected Result

```<code>{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": **true**
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}
</code>```

答:
try the below code</p>
```<code>%dw 2.0
output application/json
---
payload update {
  case .info -> $ update {
    case promo at .promotions -> promo map ((item, index) -> item update {
        case .planChangeRequired -> "true"
      }
    )
  }

}

</code>```

Body:
I am beginner for mulesoft I have output payload transform message as below but I have to replace inside promotions array planChangeRequired attribute value as true always, can some one help me how can we replace it.

output Payload

{
  "content": {
    "data": {
      "sharedDataGroups": [
        {
          "empId": 100,
          "empName": "Ram"
        },
        {
          "empId": 200,
          "empName": "Santhosh"
        }
      ],
      "promotions": [
        {
          "id": "14400007",
          "discount": 10.0,
          "planChangeRequired": false
        }
      ]
    }
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

Expected Result

{
  "info": {
    "sharedDataGroups": [
      {
        "empId": 100,
        "empName": "Ram"
      },
      {
        "empId": 200,
        "empName": "Santhosh"
      }
    ],
    "promotions": [
      {
        "id": "14400007",
        "discount": 10.0,
        "planChangeRequired": **true**
      }
    ]
  },
  "meta-info": {
    "version": "V1",
    "timestamp": "2022-02-11T12:48:27.679"
  }
}

Body:
try the below code

%dw 2.0
output application/json
---
payload update {
  case .info -> $ update {
    case promo at .promotions -> promo map ((item, index) -> item update {
        case .planChangeRequired -> "true"
      }
    )
  }

}


问:
Grafana prometheus with fastapi
I'm curious about this Prometheus, can I develop a Grafana with Prometheus as a data source with fastapi URL? Right now I'm developing on Grafana monitoring dashboard and I have an API using fastapi and I'm using this API as a data source with SimpleJSON plugin on Grafana. But now I'm a little curious about this Prometheus, is it possible to use my API as a Prometheus data source? If so, what endpoint that I should provide? For now for SimpleJSON Plugin it required /, /search and /query. How about Prometheus data sources?

Many Thanks

答:
"Data source" means something specific in Grafana. Prometheus data source has a well defined path for its queries; you can't modify that. There is an HTTP JSON+API datasource for Grafana if you search its plugins - https://marcus.se.net/grafana-json-datasource/

However, that's completely bypassing Prometheus longer-term storage. Prometheus reads scrape targets, then collects and aggregates that.

To do so, your API would need to expose any route that returns Prometheus "exposition format", not JSON. This route is put in the Prometheus config file, not into Grafana anywhere.

While Prometheus can load random data, it's better to use Counter, Guage, etc types it expects

The OpenTelemetry project should be able to be used in any framework, and there are examples in their documentation for the Python module.

If your goal is to just get any data, not metrics, into Grafana, using an RDBMS or Mongodb, or other supported data sources might be better

Title: Grafana prometheus with fastapi


问:
azure pipeline New-AzVM : Cannot process command because of one or more missing mandatory
Im using the script below to deploy a new vm from an existing image using a pipeline:

```<code>New-AzVm
-Credential $(credential)
-ResourceGroupName "RG"
-Name "Dev-VM"
-ImageName "Image"
-Location "West Europe"
-VirtualNetworkName "*****"
-SubnetName "*****"
-SecurityGroupName "**************"
-PublicIpAddressName "myImagePIP"
</code>```

but I got this error

(##[error]Cannot process command because of one or more missing mandatory parameters: Name Credential.)

Even if the parameter is already set. I don't know why it keeps asking for an Credential parameter.

could you please help me? do you have any idea?

答:
So I've achieved the solution by doing this code below. In my case I'm creating based on an image, but should work the same way.

Basically, the credential, is the localadmin user you want to create while deploying the VM. Use something that looks like this:

```<code>$user = "theUserYouWant"
$pw = ConvertTo-SecureString "Apassword" -AsPlainText -Force
$cred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pw

 New-AzVm -ResourceGroupName $(AzureVMResourceGroup) -Name $(AzureVMName) -ImageName $(AzureImageName) -VirtualNetworkName $(VNetName) -SubnetName $(SubnetName) -Credential $cred
</code>```

Body:
Im using the script below to deploy a new vm from an existing image using a pipeline:

New-AzVm
-Credential $(credential)
-ResourceGroupName "RG"
-Name "Dev-VM"
-ImageName "Image"
-Location "West Europe"
-VirtualNetworkName "*****"
-SubnetName "*****"
-SecurityGroupName "**************"
-PublicIpAddressName "myImagePIP"

but I got this error

(##[error]Cannot process command because of one or more missing mandatory parameters: Name Credential.)

Even if the parameter is already set. I don't know why it keeps asking for an Credential parameter.

could you please help me? do you have any idea?

Body:
So I've achieved the solution by doing this code below. In my case I'm creating based on an image, but should work the same way.

Basically, the credential, is the localadmin user you want to create while deploying the VM. Use something that looks like this:

$user = "theUserYouWant"
$pw = ConvertTo-SecureString "Apassword" -AsPlainText -Force
$cred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $user, $pw

 New-AzVm -ResourceGroupName $(AzureVMResourceGroup) -Name $(AzureVMName) -ImageName $(AzureImageName) -VirtualNetworkName $(VNetName) -SubnetName $(SubnetName) -Credential $cred


问:
Delete state from redux using createSlice
I have a reducer 'setOrder' that sets the initial state of 'order', however, I now want to create a reducer that deletes 'order' from the initial state. How would I go about doing this?</p>
```<code>    const checkoutSlice = createSlice({
      name: 'checkout',
      initialState: {
        customer: {
          firstName: '',
          lastName: ''
        },
        order: {
          wardrobeSize: ''
        }
      },

      reducers: {
        setCustomer(state, { payload }) {
          state.customer = payload;
        },

        setOrder(state, { payload }) {
          state.order = payload;
        }
      },
      extraReducers: hydrateServerToClient('checkout')
    });

    export const { setCustomer, setOrder } = checkoutSlice.actions;

    export default checkoutSlice.reducer;
</code>```

答:
I'd suggest just assigning an empty object to it as:</p>
```<code>emptyOrder(state) {
  state.order = {};
}
</code>```

Body:
I have a reducer 'setOrder' that sets the initial state of 'order', however, I now want to create a reducer that deletes 'order' from the initial state. How would I go about doing this?

    const checkoutSlice = createSlice({
      name: 'checkout',
      initialState: {
        customer: {
          firstName: '',
          lastName: ''
        },
        order: {
          wardrobeSize: ''
        }
      },

      reducers: {
        setCustomer(state, { payload }) {
          state.customer = payload;
        },

        setOrder(state, { payload }) {
          state.order = payload;
        }
      },
      extraReducers: hydrateServerToClient('checkout')
    });

    export const { setCustomer, setOrder } = checkoutSlice.actions;

    export default checkoutSlice.reducer;

Body:
I'd suggest just assigning an empty object to it as:

emptyOrder(state) {
  state.order = {};
}


答:
shouldn't

```<code> @page_of_book = Page.where({:number => @page, :parent_id => @book_id.id}).limit(1)
</code>```

be

```<code> @page_of_book = Page.where({:number => @page, :parent_id => @book.book_id}).limit(1)
</code>```

or something like this?

Title: Rails / MYSQL QUERY returns value even with no record?

Body:
shouldn't

 @page_of_book = Page.where({:number => @page, :parent_id => @book_id.id}).limit(1)

be

 @page_of_book = Page.where({:number => @page, :parent_id => @book.book_id}).limit(1)

or something like this?


问:
Why does python print memory location rather than class.name in some cases but not others in my code?
My code has a mathematical function that iterates over a list of county class objects and returns the county with the max voter turnout along with that turnout in a tuple.

Code here:

```<code>class County:
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].voters / data[i].population) > max_turnout:
      max_turnout_county = data[i].name
      max_turnout = (data[i].voters / data[i].population)

  return (max_turnout_county, max_turnout)

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function
</code>```

In its current state, it will return the desired output.
('chester', 0.7215045058280377)

However, if I change the county with the highest output, for example, if I change Allegheny voters from 645469 to 1000480 so that Allegheny is now the max turnout county the output will no longer return the county name in the tuple as expected, but rather the memory location.

Output here:
(<submission.County object at 0x7f8e37d3cc18>, 0.9999900048976001)

Why is my code outputting memory location in the second case but not the first case and how would I fix this?

答:
What controls how objects of a class will display themseleves when printed is the existense of a __repr__ (or, if you want to distinguish an internal representation for debugging from actually being printed-out, the __str__) method.

The default __repr__, howver, if you don't write one in your class, is the class name and memory position.

In your snippet above, when certain conditions are met, max_turnout_county is assigned with data[i].name- i.e. the name of your instance, which is a tring. If that condition is not met, the same variable remains assigned with the object itself data[0].

Depending on what you want to do with these objetcts, the best thing is to write a proper __repr__ method for them, and do not use only the .name, but rather, the actual object in any assignments. The object repr can even take care of outputting any other attributes you care about as well, so no need to keep two state variables in your function,and returning a tuple:

```<code>class County :
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

  # Bonus: yoru object can have a calculated property:
  @property
  def turnout(self):
      return self.voters/self.population

  def __repr__(self):
    return f"{self.name}, turnout: {(self.turnout * 100):.02f}"

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].turnout) > max_turnout:
      max_turnout_county = data[i]    # <- this would change
      max_turnout = (data[i].voters / data[i].population)

  return max_turnout_county

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function

# as part of the bonus - you don't even need a function for that,
# as each object now "knows" its turnout, Python's built-in
# "max" function can find your optimal county:
print(max(data, key=lambda c: c.turnout))
</code>```

Body:
My code has a mathematical function that iterates over a list of county class objects and returns the county with the max voter turnout along with that turnout in a tuple.

Code here:

class County:
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].voters / data[i].population) > max_turnout:
      max_turnout_county = data[i].name
      max_turnout = (data[i].voters / data[i].population)

  return (max_turnout_county, max_turnout)

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function

In its current state, it will return the desired output.
('chester', 0.7215045058280377)

However, if I change the county with the highest output, for example, if I change Allegheny voters from 645469 to 1000480 so that Allegheny is now the max turnout county the output will no longer return the county name in the tuple as expected, but rather the memory location.

Output here:
(<submission.County object at 0x7f8e37d3cc18>, 0.9999900048976001)

Why is my code outputting memory location in the second case but not the first case and how would I fix this?

Body:
What controls how objects of a class will display themseleves when printed is the existense of a __repr__ (or, if you want to distinguish an internal representation for debugging from actually being printed-out, the __str__) method.

The default __repr__, howver, if you don't write one in your class, is the class name and memory position.

In your snippet above, when certain conditions are met, max_turnout_county is assigned with data[i].name- i.e. the name of your instance, which is a tring. If that condition is not met, the same variable remains assigned with the object itself data[0].

Depending on what you want to do with these objetcts, the best thing is to write a proper __repr__ method for them, and do not use only the .name, but rather, the actual object in any assignments. The object repr can even take care of outputting any other attributes you care about as well, so no need to keep two state variables in your function,and returning a tuple:

class County :
  def __init__(self, init_name, init_population, init_voters):
    self.name = init_name
    self.population = init_population
    self.voters = init_voters

  # Bonus: yoru object can have a calculated property:
  @property
  def turnout(self):
      return self.voters/self.population

  def __repr__(self):
    return f"{self.name}, turnout: {(self.turnout * 100):.02f}"

def highest_turnout(data) :
  max_turnout_county = data[0]
  max_turnout = (data[0].voters / data[0].population)
  for i in range(0,6):
    if (data[i].turnout) > max_turnout:
      max_turnout_county = data[i]    # <- this would change
      max_turnout = (data[i].voters / data[i].population)

  return max_turnout_county

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]

result = highest_turnout(data)
print(result) # prints the output of the function

# as part of the bonus - you don't even need a function for that,
# as each object now "knows" its turnout, Python's built-in
# "max" function can find your optimal county:
print(max(data, key=lambda c: c.turnout))


问:
The keydown function isn’t working for me
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.</p>
```<code> Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub
</code>```

答:
Well... If you cant get it to work, then you should be able to override the ProcessCmdKey and It should capture all the keys pressed by the user. I do not necessarily recommend this, however it will fire when any key is pressed. What you currently have technically "should" work as it did in my tests.

```<code>Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  Debug.WriteLine("KeyData is: " & keyData.ToString())
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function
</code>```

Body:
I have KeyPreview on true. Also, I tried making keydown print something with console.writeline and adding a breaking point, but it didn’t even run that. So basically, the function just isn’t running at all.  Also, keyup isn’t working either.

 Private Sub Form1_KeyUp(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyUp
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = 0
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = 0
    ElseIf Input.KeyCode = Keys.E Then

    End If
End Sub

Private Sub Form1_KeyDown(sender As Object, Input As KeyEventArgs) Handles MyBase.KeyDown
    If Input.KeyCode = Keys.Up Then
        FedexMobile.Speed.Y = Speed * -1
    ElseIf Input.KeyCode = Keys.Down Then
        FedexMobile.Speed.Y = Speed
    ElseIf Input.KeyCode = Keys.Left Then
        FedexMobile.Speed.X = Speed * -1
    ElseIf Input.KeyCode = Keys.Right Then
        FedexMobile.Speed.X = Speed
    ElseIf Input.KeyCode = Keys.O Then
        If Speed > 0 Then
            Speed = Speed - 1
        End If
    ElseIf Input.KeyCode = Keys.P Then
        If Speed < 10 Then
            Speed = Speed + 1
        End If
    ElseIf Input.KeyCode = Keys.E Then

    End If

End Sub

Body:
Well... If you cant get it to work, then you should be able to override the ProcessCmdKey and It should capture all the keys pressed by the user. I do not necessarily recommend this, however it will fire when any key is pressed. What you currently have technically "should" work as it did in my tests.

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
  Debug.WriteLine("KeyData is: " & keyData.ToString())
  Return MyBase.ProcessCmdKey(msg, keyData)
End Function


问:
How do I send a POST request to a PHP file?
I am trying to send a POST request in Python to a forum. I want it to update the signature from Python using requests. My code isn't working. Anyone know how to do this better, or know what I am missing?

```<code>import requests, json
url = "https://forum.com/usercp.php?action=editsig"

payload = {
    "my_post_key=HIDDEN&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Dbbbbbb+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+TESTING%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%hidden.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature"
}

headers = {
    'Host': 'forum.com'
    'Cookie': 'REDACTED'
    'Content-Length': 395
    'Cache-Control': 'max-age=0'
    'Sec-Ch-Ua': '"(Not(A:Brand";v="8", "Chromium";v="98"'
    'Sec-Ch-Ua-Mobile': '?0'
    'Sec-Ch-Ua-Platform': '"Windows"'
    'Upgrade-Insecure-Requests': 1
    'Origin': 'https://forum.com'
    'Content-Type': 'application/x-www-form-urlencoded'
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36'
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
    'Sec-Fetch-Site': 'same-origin'
    'Sec-Fetch-Mode': 'navigate'
    'Sec-Fetch-User': '?1'
    'Sec-Fetch-Dest': 'document'
    'Referer': 'https://forum.com/usercp.php?action=editsig'
    'Accept-Encoding': 'gzip, deflate'
    'Accept-Language': 'en-US,en;q=0.9'
}

response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text , response.status_code)
</code>```

The original request which is sent to the server is this, not sure how I should format it to work like this.

```<code>POST /usercp.php HTTP/2
Host: forum.com
Cookie: test=test
Content-Length: 395
Cache-Control: max-age=0
Sec-Ch-Ua: "(Not(A:Brand";v="8", "Chromium";v="98"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
Origin: https://forum.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://forum.com/usercp.php?action=editsig
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

my_post_key=REMOVED&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Daaaaaa+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+aaaaaa%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%test.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature
</code>```

答:
I believe you've incorrectly formatted a few things:
Firstly, the headers are meant to be a python dictionary, you need to separate each header with a comma. Also, headers are always strings so you need to change the Content-Length and Upgrad-Insecure-Requests to strings.

Lastly, your payload isn't a dictionary. You've got one long string in that "dictionary" not key-value pairs. You can send a string but you need to specify it in the request, you aren't sending JSON you are sending a string so you should format your code like this:

```<code>import requests

url = "https://forum.com/usercp.php?action=editsig"

payload = {
    "my_post_key=HIDDEN&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Dbbbbbb+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+TESTING%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%hidden.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature"
}

headers = {
    'Host': 'forum.com',
    'Cookie': 'REDACTED',
    'Content-Length': '395',
    'Cache-Control': 'max-age=0',
    'Sec-Ch-Ua': '"(Not(A:Brand";v="8", "Chromium";v="98"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'Origin': 'https://forum.com',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Referer': 'https://forum.com/usercp.php?action=editsig',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
}

response = requests.post(url, headers=headers, data=payload)
print(response.text , response.status_code)
</code>```

Body:
I am trying to send a POST request in Python to a forum. I want it to update the signature from Python using requests. My code isn't working. Anyone know how to do this better, or know what I am missing?

import requests, json
url = "https://forum.com/usercp.php?action=editsig"

payload = {
    "my_post_key=HIDDEN&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Dbbbbbb+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+TESTING%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%hidden.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature"
}

headers = {
    'Host': 'forum.com'
    'Cookie': 'REDACTED'
    'Content-Length': 395
    'Cache-Control': 'max-age=0'
    'Sec-Ch-Ua': '"(Not(A:Brand";v="8", "Chromium";v="98"'
    'Sec-Ch-Ua-Mobile': '?0'
    'Sec-Ch-Ua-Platform': '"Windows"'
    'Upgrade-Insecure-Requests': 1
    'Origin': 'https://forum.com'
    'Content-Type': 'application/x-www-form-urlencoded'
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36'
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
    'Sec-Fetch-Site': 'same-origin'
    'Sec-Fetch-Mode': 'navigate'
    'Sec-Fetch-User': '?1'
    'Sec-Fetch-Dest': 'document'
    'Referer': 'https://forum.com/usercp.php?action=editsig'
    'Accept-Encoding': 'gzip, deflate'
    'Accept-Language': 'en-US,en;q=0.9'
}

response = requests.post(url, headers=headers, data=json.dumps(payload))
print(response.text , response.status_code)

The original request which is sent to the server is this, not sure how I should format it to work like this.

POST /usercp.php HTTP/2
Host: forum.com
Cookie: test=test
Content-Length: 395
Cache-Control: max-age=0
Sec-Ch-Ua: "(Not(A:Brand";v="8", "Chromium";v="98"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
Origin: https://forum.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://forum.com/usercp.php?action=editsig
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

my_post_key=REMOVED&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Daaaaaa+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+aaaaaa%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%test.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature

Body:
I believe you've incorrectly formatted a few things:
Firstly, the headers are meant to be a python dictionary, you need to separate each header with a comma. Also, headers are always strings so you need to change the Content-Length and Upgrad-Insecure-Requests to strings.

Lastly, your payload isn't a dictionary. You've got one long string in that "dictionary" not key-value pairs. You can send a string but you need to specify it in the request, you aren't sending JSON you are sending a string so you should format your code like this:

import requests

url = "https://forum.com/usercp.php?action=editsig"

payload = {
    "my_post_key=HIDDEN&signature=%5Bfont%3DLucida+Sans+Unicode%2CLucida+Grande%2Csans-serif%5D%5Bsize%3Dx-large%5D%5Bb%5D%5Bcolor%3D%23c0392b%5Dbbbbbb+%3D%C2%A0%5B%2Fcolor%5D%5B%2Fb%5D%5B%2Fsize%5D%5B%2Ffont%5D+%3Aaaa2%3A%C2%A0MOTD%3A+TESTING%0D%0A%5Bimg%5Dhttps%3A%2F%2Ftinyimg.io%2Fi%hidden.jpeg%5B%2Fimg%5D&updateposts=enable&action=do_editsig&submit=Update+Signature"
}

headers = {
    'Host': 'forum.com',
    'Cookie': 'REDACTED',
    'Content-Length': '395',
    'Cache-Control': 'max-age=0',
    'Sec-Ch-Ua': '"(Not(A:Brand";v="8", "Chromium";v="98"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'Origin': 'https://forum.com',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Referer': 'https://forum.com/usercp.php?action=editsig',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
}

response = requests.post(url, headers=headers, data=payload)
print(response.text , response.status_code)


问:
How can I color Python logging output?
Some time ago, I saw a Mono application with colored output, presumably because of its log system (because all the messages were standardized).

Now, Python has the logging module, which lets you specify a lot of options to customize output. So, I'm imagining something similar would be possible with Python, but I can’t find out how to do this anywhere.

Is there any way to make the Python logging module output in color?

What I want (for instance) errors in red, debug messages in blue or yellow, and so on.

Of course this would probably require a compatible terminal (most modern terminals are); but I could fallback to the original logging output if color isn't supported.

Any ideas how I can get colored output with the logging module?

答:
This is a slight variation on @Sergey Pleshakov's excellent answer which applies color only to the levels and uses basicConfig as expected:

```<code>class CustomFormatter(logging.Formatter):

    white = "\x1b[97;20m"
    grey = "\x1b[38;20m"
    green = "\x1b[32;20m"
    cyan = "\x1b[36;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    fmt = "%(asctime)s - {}%(levelname)-8s{} - %(name)s.%(funcName)s - %(message)s"

    FORMATS = {
        logging.DEBUG: fmt.format(grey, reset),
        logging.INFO: fmt.format(green, reset),
        logging.WARNING: fmt.format(yellow, reset),
        logging.ERROR: fmt.format(red, reset),
        logging.CRITICAL: fmt.format(bold_red, reset),
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt, datefmt="%H:%M:%S")
        return formatter.format(record)

handler = logging.StreamHandler()
handler.setFormatter(CustomFormatter())
logging.basicConfig(
    level=logging.DEBUG,
    handlers=[handler]
)
</code>```

OwnerDisplayName: airmind

Title: How can I color Python logging output?

Body:
This is a slight variation on @Sergey Pleshakov's excellent answer which applies color only to the levels and uses basicConfig as expected:

class CustomFormatter(logging.Formatter):

    white = "\x1b[97;20m"
    grey = "\x1b[38;20m"
    green = "\x1b[32;20m"
    cyan = "\x1b[36;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    fmt = "%(asctime)s - {}%(levelname)-8s{} - %(name)s.%(funcName)s - %(message)s"

    FORMATS = {
        logging.DEBUG: fmt.format(grey, reset),
        logging.INFO: fmt.format(green, reset),
        logging.WARNING: fmt.format(yellow, reset),
        logging.ERROR: fmt.format(red, reset),
        logging.CRITICAL: fmt.format(bold_red, reset),
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt, datefmt="%H:%M:%S")
        return formatter.format(record)

handler = logging.StreamHandler()
handler.setFormatter(CustomFormatter())
logging.basicConfig(
    level=logging.DEBUG,
    handlers=[handler]
)


问:
Javascript in ASP.NET is not working
I'm back at coding som .NET stuff and I thought I'd play with Javascripts / jQuery.

I've added my /js/myscript.js file and it loads when the pages has loaded.

In my js file I only have one call alert('TEST').

Why isn't the alert triggered?

I'm on ASP.NET 4.0  - but I don' think that has anything to do with it.

Is there a way to detect if there is any conflict with other scripts?

This goes in the header:

```<code><script type="text/javascript" src="js/myscript.js" ></script>
</code>```

After page is loaded, I can use Firebug and exapnd the script and see it's content. So the script is loaded.

Embarrassing update

```<code>jQuery(document).ready(function() {
    // Alert if jQuery is loaded
    alert('Test1');
}

alert('Test 2');
</code>```

As you can see in the above code, I'd forgotten to add the ); and the end of the  jQuery(document).ready() function.

After a long day, even the simplest things can go unnoticed.

答:
Always check for Javascript Errors on something like this.
All modern browser have built in HTML/Javascript inspectors which you can use to check for these errors.</p>

Title: Javascript in ASP.NET is not working

Body:
I'm back at coding som .NET stuff and I thought I'd play with Javascripts / jQuery.

I've added my /js/myscript.js file and it loads when the pages has loaded.

In my js file I only have one call alert('TEST').

Why isn't the alert triggered?

I'm on ASP.NET 4.0  - but I don' think that has anything to do with it.

Is there a way to detect if there is any conflict with other scripts?

This goes in the header:

After page is loaded, I can use Firebug and exapnd the script and see it's content. So the script is loaded.

Embarrassing update

jQuery(document).ready(function() {
    // Alert if jQuery is loaded
    alert('Test1');
}

alert('Test 2');

As you can see in the above code, I'd forgotten to add the ); and the end of the  jQuery(document).ready() function.

After a long day, even the simplest things can go unnoticed.


问:
Android Studio Project Build Output Error: Task :app:mergeDebugResources FAILED
Build Output Details:

Task :app:mergeDebugResources
C:\Users\userName.gradle\caches\transforms-3\ee0550e8848c5279ef1306690d07508f\transformed\fragment-1.3.6\res\values\values.xml:2:4:>item> inner element must either be a resource reference or empty.

Task :app:createDebugCompatibleScreenManifests
Task :app:extractDeepLinksDebug
Task :app:mergeDebugResources FAILED

Failed to compile values file.

values.xml Original file

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="fragment_container_view_tag" type="id"/>
<item name="special_effects_controller_view_tag" type="id"/>
<item name="visible_removing_fragment_view_tag" type="id"/>
<declare-styleable name="Fragment">
    <attr name="android:name"/>
    <attr name="android:id"/>
    <attr name="android:tag"/>
</declare-styleable>
<declare-styleable name="FragmentContainerView">
    <attr name="android:name"/>
    <attr name="android:tag"/>
</declare-styleable>
</code>```

I get the same error when I do following changes in values.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="fragment_container_view_tag" type="id"/>
    <item name="special_effects_controller_view_tag" type="id"/>
    <item name="visible_removing_fragment_view_tag" type="id"/>
</resources>
</code>```

答:
You cannot write items directly under sources here. I prepared an example for you.</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="your_array_list_name">
        <item name="fragment_container_view_tag" type="id"/>
        <item name="special_effects_controller_view_tag" type="id"/>
        <item name="visible_removing_fragment_view_tag" type="id"/>
    </array>
</resources>
</code>```

Body:
Build Output Details:

Task :app:mergeDebugResources
C:\Users\userName.gradle\caches\transforms-3\ee0550e8848c5279ef1306690d07508f\transformed\fragment-1.3.6\res\values\values.xml:2:4:>item> inner element must either be a resource reference or empty.

Task :app:createDebugCompatibleScreenManifests
Task :app:extractDeepLinksDebug
Task :app:mergeDebugResources FAILED

Failed to compile values file.

values.xml Original file

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="fragment_container_view_tag" type="id"/>
<item name="special_effects_controller_view_tag" type="id"/>
<item name="visible_removing_fragment_view_tag" type="id"/>
<declare-styleable name="Fragment">
    <attr name="android:name"/>
    <attr name="android:id"/>
    <attr name="android:tag"/>
</declare-styleable>
<declare-styleable name="FragmentContainerView">
    <attr name="android:name"/>
    <attr name="android:tag"/>
</declare-styleable>

I get the same error when I do following changes in values.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="fragment_container_view_tag" type="id"/>
    <item name="special_effects_controller_view_tag" type="id"/>
    <item name="visible_removing_fragment_view_tag" type="id"/>
</resources>

Body:
You cannot write items directly under sources here. I prepared an example for you.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="your_array_list_name">
        <item name="fragment_container_view_tag" type="id"/>
        <item name="special_effects_controller_view_tag" type="id"/>
        <item name="visible_removing_fragment_view_tag" type="id"/>
    </array>
</resources>


问:
How can I return data from a .json file with Discord.py
I want to store data in a .json file, and I want to also be able to fetch this data by using a discord bot using discord.py</p>

答:
```<code>import json

data = {
"foo": "bar"
}

#write json to file
file = open('json.json', "w")
json.dump(data, file);

#read json from file
file = open('json.json', 'r')
jstring = json.load(file)

#output: bar
print(jstring['foo'])
</code>```

A simple google trick would of done it.

Body:
import json

data = {
"foo": "bar"
}

#write json to file
file = open('json.json', "w")
json.dump(data, file);

#read json from file
file = open('json.json', 'r')
jstring = json.load(file)

#output: bar
print(jstring['foo'])

A simple google trick would of done it.