问:
ggplot2 adding an extra legend for the bar colours (when having another legend for background colours)
I have a plot with a legend for how to interpret the background color - but I would also like a legend for the bar colours, something like:

Title: Type

[blue square] A-type

[black square] B-type

This is the plot:

Code to make the plot:

```<code># Example data
data <- data.frame(
  Type = c("A1","A2", "B1", "B2") ,
  Value = c(5, 6, 3, 2)
)

background_area_name <- as_factor(c("very weak", "weak", "moderate",  "strong", "very strong"))
levels(background_area_name)

background_data <- tibble(xmin = -Inf, xmax = Inf,
                          ymin = c(0, 2, 4, 6, 8),
                          ymax = c(   2, 4, 6, 8, Inf),
                          "Value strength" = factor(background_area_name,
                                                          background_area_name
                          ))

# Plot (with missing legend for the bars)
ggplot(data, aes(x=Type, y=Value,
                 width = 0.4)) +

  geom_rect(data = background_data,
            aes(ymin = ymin,
                ymax = ymax,
                xmin = xmin,
                xmax = xmax,
                fill = `Value strength`),
            inherit.aes = FALSE,
            alpha = 0.8) +

  geom_bar(stat = "identity",
           fill = c(rep("blue", 2), rep("black", 2))) +

  scale_fill_manual(values = alpha(c("#f0f5f5",
                                     "#e0ebeb",
                                     "#d1e0e0",
                                     "#c2d6d6",
                                     "#b3cccc"),
                                   0.99),
                    guide = guide_legend(reverse = TRUE)) +

  ylab("Value") +

  scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10),
                     expand = c(0, 0.00)) +
  #                 expand = expansion(add = 0.06)) +

  guides(colour = guide_legend(reverse=T))
</code>```

答:
You can achieve this using the ggnewscale package:

library(ggnewscale)

ggplot(data, aes(x = Type, y = Value, width = 0.4)) +
  geom_rect(data = background_data,
            aes(ymin = ymin,
                ymax = ymax,
                xmin = xmin,
                xmax = xmax,
                fill = `Value strength`),
            inherit.aes = FALSE,
            alpha = 0.8) +
  scale_fill_manual(values = alpha(c("#f0f5f5",
                                     "#e0ebeb",
                                     "#d1e0e0",
                                     "#c2d6d6",
                                     "#b3cccc"),
                                   0.99),
                    guide = guide_legend(reverse = TRUE)) +
  new_scale_fill() +
  geom_bar(stat = "identity", aes(fill = paste0(substr(Type, 1, 1), "-type"))) +
  scale_fill_manual(values = c("blue", "black"), name = "Type") +
  ylab("Value") +
  scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10),
                     expand = c(0, 0.00)) +
  guides(colour = guide_legend(reverse = TRUE))
```

Body:
I have a plot with a legend for how to interpret the background color - but I would also like a legend for the bar colours, something like:

Title: Type

[blue square] A-type

[black square] B-type

This is the plot:

Code to make the plot:

# Example data
data <- data.frame(
  Type = c("A1","A2", "B1", "B2") ,
  Value = c(5, 6, 3, 2)
)

background_area_name <- as_factor(c("very weak", "weak", "moderate",  "strong", "very strong"))
levels(background_area_name)

background_data <- tibble(xmin = -Inf, xmax = Inf,
                          ymin = c(0, 2, 4, 6, 8),
                          ymax = c(   2, 4, 6, 8, Inf),
                          "Value strength" = factor(background_area_name,
                                                          background_area_name
                          ))

# Plot (with missing legend for the bars)
ggplot(data, aes(x=Type, y=Value,
                 width = 0.4)) +

  geom_rect(data = background_data,
            aes(ymin = ymin,
                ymax = ymax,
                xmin = xmin,
                xmax = xmax,
                fill = `Value strength`),
            inherit.aes = FALSE,
            alpha = 0.8) +

  geom_bar(stat = "identity",
           fill = c(rep("blue", 2), rep("black", 2))) +

  scale_fill_manual(values = alpha(c("#f0f5f5",
                                     "#e0ebeb",
                                     "#d1e0e0",
                                     "#c2d6d6",
                                     "#b3cccc"),
                                   0.99),
                    guide = guide_legend(reverse = TRUE)) +

  ylab("Value") +

  scale_y_continuous(breaks = c(0, 2, 4, 6, 8, 10),
                     expand = c(0, 0.00)) +
  #                 expand = expansion(add = 0.06)) +

  guides(colour = guide_legend(reverse=T))


来源: stackexchange

问:
How do I query the content of the addStringOption in the interactions in discord v13?
Good day,

I would like to save the content that you type in addStringOption, I just don't know how to query that, can someone explain it to me?

```<code>   const { SlashCommandBuilder } = require("@discordjs/builders");

    module.exports = {
        data: new SlashCommandBuilder()
        .setName('announce')
        .setDescription('test')
        .addSubcommand(subcommand =>subcommand.setName('normal').setDescription('TEST')
        .addStringOption(option => option.setName('message').setDescription('TEST').setRequired(true))),

        async execute(interaction) {
            interaction.reply("test")
        }
    }
</code>```

答:
I am not 100% what you mean by query but I assume you want to get the value of the option they user has entered. For this you want to use the getString function on the options property.

async execute(interaction) {
  // Get the string option
  const value = interaction.options.getString('message');
  // Return the value
  await interaction.reply(value);
}
```

Read More Here:
https://discord.js.org/#/docs/discord.js/stable/class/CommandInteractionOptionResolver?scrollTo=getString

ContentLicense: CC BY-SA 4.0

Body:
Good day,

I would like to save the content that you type in addStringOption, I just don't know how to query that, can someone explain it to me?

   const { SlashCommandBuilder } = require("@discordjs/builders");

    module.exports = {
        data: new SlashCommandBuilder()
        .setName('announce')
        .setDescription('test')
        .addSubcommand(subcommand =>subcommand.setName('normal').setDescription('TEST')
        .addStringOption(option => option.setName('message').setDescription('TEST').setRequired(true))),

        async execute(interaction) {
            interaction.reply("test")
        }
    }

Body:
I am not 100% what you mean by query but I assume you want to get the value of the option they user has entered. For this you want to use the getString function on the options property.

async execute(interaction) {
  // Get the string option
  const value = interaction.options.getString('message');
  // Return the value
  await interaction.reply(value);
}

Read More Here:
https://discord.js.org/#/docs/discord.js/stable/class/CommandInteractionOptionResolver?scrollTo=getString


问:
How to fix calculation error in go math operations with floats?
I need to normalise a value (degrees) to have it in some range. I need to get a reminder of division by 360.

func testFunc(t *testing.T) {

    v := -1050.6
    n := int(v / 360)
    f := v - float64(n)*360

    fmt.Printf("f: %v\n", f)
}
```

The value I expect is -330.6 the value I get is -330.5999999999999. This happens when I do v - float64(n)*360. Is there any way to get rid of this error?

答:
You can try this (2 digits after comma):</p>
```<code>fmt.Println(math.Round(f * 100) / 100)
</code>```

Body:
I need to normalise a value (degrees) to have it in some range. I need to get a reminder of division by 360.

func testFunc(t *testing.T) {

    v := -1050.6
    n := int(v / 360)
    f := v - float64(n)*360

    fmt.Printf("f: %v\n", f)
}

The value I expect is -330.6 the value I get is -330.5999999999999. This happens when I do v - float64(n)*360. Is there any way to get rid of this error?

Body:
You can try this (2 digits after comma):

fmt.Println(math.Round(f * 100) / 100)


问:
How to prevent stack wind-up operator overloads
I am getting stack overflow in this apparently benign code:

```<code>    public static bool operator == (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return true;

        if (al1 == null || al2 == null)
            return false;

        if (al1._Value == al2._Value)
            return true;
        else
            return false;
    }
    public static bool operator != (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return false;

        if (al1 == null || al2 == null)
            return true;

        if (al1._Value != al2._Value)
            return true;
        else
            return false;
    }
</code>```

What appears to be happening is that in the test for null in operator overload, the == overload is called again, and again, and again until the stack wind up.
Possible solutions here is to use the "Equals" override, which would look like Equals(null) returning true... but how to code that without using the == overload ? Is this the correct implementation:

```<code>        public override bool Equals(object o)
        {
            if (o == null)
                return true;
            if ((AccessLevel)o == this)
                return true;
            return false;
        }
</code>```

Or could one say something like this:

```<code>        public static bool operator == (AccessLevel al1, AccessLevel al2)
        {
            if (al1 is null && al2 is null)
                return true;

            if (al1 is null || al2 is null)
                return false;

            if (al1._Value == al2._Value)
                return true;
            else
                return false;
        }
</code>```

Any insight on how to correctly handle this?

答:
To implement equality tests "properly", use:</p>
```<code>public class AccessLevel : IEquatable<AccessLevel>
{
    ...

    public override int GetHashCode() => _Value.GetHashCode();

    public override bool Equals(object obj)
        => obj is AccessLevel other
        && Equals(other);

    public bool Equals(AccessLevel other)
    {
        if (other is null) return false;
        if (ReferenceEquals(this, other)) return true;
        return _Value == other._Value;
    }

    public static bool operator ==(AccessLevel left, AccessLevel right)
        => Equals(left, right);

    public static bool operator !=(AccessLevel left, AccessLevel right)
        => !Equals(left, right);
}
</code>```

Body:
I am getting stack overflow in this apparently benign code:

    public static bool operator == (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return true;

        if (al1 == null || al2 == null)
            return false;

        if (al1._Value == al2._Value)
            return true;
        else
            return false;
    }
    public static bool operator != (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return false;

        if (al1 == null || al2 == null)
            return true;

        if (al1._Value != al2._Value)
            return true;
        else
            return false;
    }

What appears to be happening is that in the test for null in operator overload, the == overload is called again, and again, and again until the stack wind up.
Possible solutions here is to use the "Equals" override, which would look like Equals(null) returning true... but how to code that without using the == overload ? Is this the correct implementation:

        public override bool Equals(object o)
        {
            if (o == null)
                return true;
            if ((AccessLevel)o == this)
                return true;
            return false;
        }

Or could one say something like this:

        public static bool operator == (AccessLevel al1, AccessLevel al2)
        {
            if (al1 is null && al2 is null)
                return true;

            if (al1 is null || al2 is null)
                return false;

            if (al1._Value == al2._Value)
                return true;
            else
                return false;
        }

Any insight on how to correctly handle this?

Body:
To implement equality tests "properly", use:

public class AccessLevel : IEquatable<AccessLevel>
{
    ...

    public override int GetHashCode() => _Value.GetHashCode();

    public override bool Equals(object obj)
        => obj is AccessLevel other
        && Equals(other);

    public bool Equals(AccessLevel other)
    {
        if (other is null) return false;
        if (ReferenceEquals(this, other)) return true;
        return _Value == other._Value;
    }

    public static bool operator ==(AccessLevel left, AccessLevel right)
        => Equals(left, right);

    public static bool operator !=(AccessLevel left, AccessLevel right)
        => !Equals(left, right);
}


问:
It's possible to create another organization or create sub-organization in GCP?
I have a problem when create organization in GCP. I have a secondary domain and want to use it to set an organization in GCP but I can't see how to get it. So, It's possible to create another organization or create sub-organization?</p>

答:
There is no sub-organizations in GCP Resources hierarchy.

Yes, you can create another organization by creating a Google Workspace (formerly G-Suite) or Cloud Identity account and associate it with a domain.

As quoted from docs:

Once you have created your Google Workspace or Cloud Identity account
and associated it with a domain, your organization resource will be
automatically created for you. The resource will be provisioned at
different times depending on your account status:

If you are new to Google Cloud and have not created a project yet, the organization resource will be created for you when you log in to the Google Cloud console and accept the terms and conditions.

If you are an existing Google Cloud user, the organization resource    will be created for you when you create a new project or billing account. Any projects you created previously will be listed under "No organization", and this is normal. The organization resource will appear and the new project you created will be linked to it automatically.

You will need to move any projects you created under "No organization" into your new organization resource. For instructions on how to move your projects, see Migrating projects into an organization.


问:
AttributeError: module 'selenium.webdriver.support' has no attribute 'wait'
When I try to wait for an element to pop up in selenium it says that it doesn't exist. Even though it says it in the documentation of selenium..

My code : webdriver.support.wait.WebDriverWait(driver, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))

答:
Its somewhat incorrectly used I guess -

import should look like this -

```<code>from selenium.webdriver.support.ui import WebDriverWait
</code>```

and your code should look like this -

```<code>WebDriverWait(driver, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))
</code>```

or

```<code>wait = WebDriverWait(driver, 120)
wait.until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))
</code>```

Body:
Its somewhat incorrectly used I guess -

import should look like this -

from selenium.webdriver.support.ui import WebDriverWait

and your code should look like this -

WebDriverWait(driver, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))

or

wait = WebDriverWait(driver, 120)
wait.until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))


问:
Combining enum values and checking if another value is in that enum
Consider the following code:

```<code>enum myEnum {
    a = 1,
    b = 2
}

enum mySecondEnum {
    c = 3,
    d = 4
}

enum myThirdEnum {
    e = 5,
    f = 6
}

/** This is an array, that should contain numbers from 1 to 4 - instead, it also contains the string keys of the enums - is there a way to limit this array to only */
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];
console.log(enumValuesArray);

/** Here, b can be a number from 1 to 6 */
const b: myEnum | mySecondEnum | myThirdEnum = 5;

/** Why is typescript complaining here? I understand, that b CAN be 5 or 6 (as it is), but that is exactly the thing I want to check */
if (enumValuesArray.includes(b)) {
    console.log("Included");
} else console.log("Not included");
</code>```

While this code compiles and runs as expected, TypeScript complains when I am trying to check if the output array includes the value of "b". The error message I am getting is as follows:

Argument of type 'myEnum | mySecondEnum | myThirdEnum' is not assignable to parameter of type 'string | myEnum | mySecondEnum'.
Type 'myThirdEnum.e' is not assignable to type 'string | myEnum | mySecondEnum'.(2345)

How should I resolve this error?

As a second note, is it possible somehow, to retrieve an array of enum values only, instead of enum values and properties?

答:
First of all, it worth using immutable object instead of numerical enums.
See example:

const myEnum = {
    a: 1,
    b: 2
} as const

const mySecondEnum = {
    c: 3,
    d: 4
} as const

const myThirdEnum = {
    e: 5,
    f: 6
} as const
```
<p>Now, <code>enumValuesArray</code> has an expected type:</p>
<pre class="lang-js prettyprint-override"><code>// (1 | 2 | 3 | 4)[]
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];
</code>```

As for the error with Array.prototype.includes. It is known issue. TS only allows you to use numbers which are exists in enumValuesArray.

There is a generic and a little bit verbose workaround.
Pros: no need type assertion
Cons: verbose and requires you to curry.

Full example:

const myEnum = {
    a: 1,
    b: 2
} as const

const mySecondEnum = {
    c: 3,
    d: 4
} as const

const myThirdEnum = {
    e: 5,
    f: 6
} as const

type Values<T> = T[keyof T]

type Primitives =
    | string
    | number
    | bigint
    | boolean
    | symbol
    | null
    | undefined

type InferPrimitive<T, P> = P extends any ? T extends P ? P : never : never;

type Inference<T> = InferPrimitive<T, Primitives>

const withTuple = <
    List extends Primitives[]
>(list: readonly [...List]) =>
    (prop: Inference<List[number]>):
        prop is Inference<List[number]> & List[number] =>
        list.includes(prop)

// (1 | 2 | 3 | 4)[]
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];

const includes = withTuple(enumValuesArray);

type DistributeValues<T> = T extends any ? Values<T> : never

// 1 | 2 | 3 | 4 | 5 | 6
type AllowedValues = DistributeValues<typeof myEnum | typeof mySecondEnum | typeof myThirdEnum>

/** Here, b can be a number from 1 to 6 */
const b: AllowedValues = 5; // ok

/** Why is typescript complaining here? I understand, that b CAN be 5 or 6 (as it is), but that is exactly the thing I want to check */
if (includes(b)) {
    console.log("Included");
} else console.log("Not included");

includes('a') // expected error
```

Playground

More explanation regarding includes you will find in my article

InferPrimitive - will unnnarow literal type to much wider type. For instance InferPrimitive<42> will return number.

Body:
Consider the following code:

enum myEnum {
    a = 1,
    b = 2
}

enum mySecondEnum {
    c = 3,
    d = 4
}

enum myThirdEnum {
    e = 5,
    f = 6
}

/** This is an array, that should contain numbers from 1 to 4 - instead, it also contains the string keys of the enums - is there a way to limit this array to only */
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];
console.log(enumValuesArray);

/** Here, b can be a number from 1 to 6 */
const b: myEnum | mySecondEnum | myThirdEnum = 5;

/** Why is typescript complaining here? I understand, that b CAN be 5 or 6 (as it is), but that is exactly the thing I want to check */
if (enumValuesArray.includes(b)) {
    console.log("Included");
} else console.log("Not included");

While this code compiles and runs as expected, TypeScript complains when I am trying to check if the output array includes the value of "b". The error message I am getting is as follows:

Argument of type 'myEnum | mySecondEnum | myThirdEnum' is not assignable to parameter of type 'string | myEnum | mySecondEnum'.
Type 'myThirdEnum.e' is not assignable to type 'string | myEnum | mySecondEnum'.(2345)

How should I resolve this error?

As a second note, is it possible somehow, to retrieve an array of enum values only, instead of enum values and properties?

Body:
First of all, it worth using immutable object instead of numerical enums.
See example:

const myEnum = {
    a: 1,
    b: 2
} as const

const mySecondEnum = {
    c: 3,
    d: 4
} as const

const myThirdEnum = {
    e: 5,
    f: 6
} as const

Now, enumValuesArray has an expected type:

// (1 | 2 | 3 | 4)[]
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];

As for the error with Array.prototype.includes. It is known issue. TS only allows you to use numbers which are exists in enumValuesArray.

There is a generic and a little bit verbose workaround.
Pros: no need type assertion
Cons: verbose and requires you to curry.

Full example:

const myEnum = {
    a: 1,
    b: 2
} as const

const mySecondEnum = {
    c: 3,
    d: 4
} as const

const myThirdEnum = {
    e: 5,
    f: 6
} as const

type Values<T> = T[keyof T]

type Primitives =
    | string
    | number
    | bigint
    | boolean
    | symbol
    | null
    | undefined

type InferPrimitive<T, P> = P extends any ? T extends P ? P : never : never;

type Inference<T> = InferPrimitive<T, Primitives>

const withTuple = <
    List extends Primitives[]
>(list: readonly [...List]) =>
    (prop: Inference<List[number]>):
        prop is Inference<List[number]> & List[number] =>
        list.includes(prop)

// (1 | 2 | 3 | 4)[]
const enumValuesArray = [...Object.values(myEnum), ...Object.values(mySecondEnum)];

const includes = withTuple(enumValuesArray);

type DistributeValues<T> = T extends any ? Values<T> : never

// 1 | 2 | 3 | 4 | 5 | 6
type AllowedValues = DistributeValues<typeof myEnum | typeof mySecondEnum | typeof myThirdEnum>

/** Here, b can be a number from 1 to 6 */
const b: AllowedValues = 5; // ok

/** Why is typescript complaining here? I understand, that b CAN be 5 or 6 (as it is), but that is exactly the thing I want to check */
if (includes(b)) {
    console.log("Included");
} else console.log("Not included");

includes('a') // expected error

Playground

More explanation regarding includes you will find in my article

InferPrimitive - will unnnarow literal type to much wider type. For instance InferPrimitive<42> will return number.


问:
Error while using CASE in WHERE clause in Oracle Database
This is my query and when I am running it, I am getting error "missing Keyword".
can anyone please help with it</p>
```<code>SELECT COUNT(1)
FROM ar_invoice_master,proposal,proposal_to_opportunity
WHERE proposal.PROPOSAL_ID=proposal_to_opportunity.FK_PROPOSAL_ID
AND proposal_to_opportunity.FK_AR_INVOICE_ID=ar_invoice_master.AR_INVOICE_ID
AND  CASE
        WHEN ar_invoice_master.FK_INVOICE_TYPE_CODE NOT IN ('REN','TRS') THEN ar_invoice_master.AR_INVOICE_OS_AMOUNT>0
        WHEN ar_invoice_master.FK_INVOICE_TYPE_CODE  IN ('REN','TRS') THEN (AR_INVOICE_OS_AMOUNT/AR_INVOICE_TOTAL_AMOUNT * 100)<100
      END
AND proposal.FK_GLUSR_USR_ID=: glid
</code>```

答:
You can use AND..OR instead of a CASE EXPRESSION:

```<code>AND ((ar_invoice_master.FK_INVOICE_TYPE_CODE NOT IN ('REN','TRS')
      AND ar_invoice_master.AR_INVOICE_OS_AMOUNT>0)
  OR (ar_invoice_master.FK_INVOICE_TYPE_CODE  IN ('REN','TRS')
      AND (AR_INVOICE_OS_AMOUNT/AR_INVOICE_TOTAL_AMOUNT * 100)<100))

</code>```

The reason it doesn't work is that CASE is not a statement but an expression, it can't return a condition.

Body:
This is my query and when I am running it, I am getting error "missing Keyword".
can anyone please help with it

SELECT COUNT(1)
FROM ar_invoice_master,proposal,proposal_to_opportunity
WHERE proposal.PROPOSAL_ID=proposal_to_opportunity.FK_PROPOSAL_ID
AND proposal_to_opportunity.FK_AR_INVOICE_ID=ar_invoice_master.AR_INVOICE_ID
AND  CASE
        WHEN ar_invoice_master.FK_INVOICE_TYPE_CODE NOT IN ('REN','TRS') THEN ar_invoice_master.AR_INVOICE_OS_AMOUNT>0
        WHEN ar_invoice_master.FK_INVOICE_TYPE_CODE  IN ('REN','TRS') THEN (AR_INVOICE_OS_AMOUNT/AR_INVOICE_TOTAL_AMOUNT * 100)<100
      END
AND proposal.FK_GLUSR_USR_ID=: glid

Body:
You can use AND..OR instead of a CASE EXPRESSION:

AND ((ar_invoice_master.FK_INVOICE_TYPE_CODE NOT IN ('REN','TRS')
      AND ar_invoice_master.AR_INVOICE_OS_AMOUNT>0)
  OR (ar_invoice_master.FK_INVOICE_TYPE_CODE  IN ('REN','TRS')
      AND (AR_INVOICE_OS_AMOUNT/AR_INVOICE_TOTAL_AMOUNT * 100)<100))

The reason it doesn't work is that CASE is not a statement but an expression, it can't return a condition.


问:
R : How to extract the factor levels as numeric from a column and assign it to a new column using tydyverse?
Suppose I have a data frame, df

```<code>df = data.frame(name = rep(c("A", "B", "C"), each = 4))
</code>```

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

```<code>df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3
</code>```

Body:
Suppose I have a data frame, df

df = data.frame(name = rep(c("A", "B", "C"), each = 4))

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3

Body:
data.table

df = data.frame(name = rep(c("A", "B", "C"), each = 4))

library(data.table)
setDT(df)[, grp := .GRP, by = name][]
#>     name grp
#>  1:    A   1
#>  2:    A   1
#>  3:    A   1
#>  4:    A   1
#>  5:    B   2
#>  6:    B   2
#>  7:    B   2
#>  8:    B   2
#>  9:    C   3
#> 10:    C   3
#> 11:    C   3
#> 12:    C   3

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
connecting yml to html.slim
There are two html.slim files as:

client view:

```<code>= f.input :name,
        required: true,
        :wrapper => :input_wrapper
</code>```

company view:

```<code>= f.input :name,
        required: true,
        :wrapper => :input_wrapper
</code>```

there is shared yml file that defines the displayed values as:

```<code> simple_form:
        labels:
            defaults:
                name: some value
</code>```

How can I define different name values for the company and the client, ideally without chenging the view? Moreover, how is the yml file linked to the slim file? For example in the routes files it is specified the url and the corresponding view file, how does that work between yml and html.slim files?

答:
In the documentation you will find the following:

simple_form_for @admin_user, as: :some_user will look into the yml file under some_user instead of admin_user so the yml file will look like this:

en:
  simple_form:
    labels:
        admin_user:
            name: Admin Name
        some_user:
            name: Some user name
```

So in your simple_form you can add as: :client and as: :company and add those 2 to the yml file.

Title: connecting yml to html.slim

Body:
There are two html.slim files as:

client view:

= f.input :name,
        required: true,
        :wrapper => :input_wrapper

company view:

= f.input :name,
        required: true,
        :wrapper => :input_wrapper

there is shared yml file that defines the displayed values as:

 simple_form:
        labels:
            defaults:
                name: some value

How can I define different name values for the company and the client, ideally without chenging the view? Moreover, how is the yml file linked to the slim file? For example in the routes files it is specified the url and the corresponding view file, how does that work between yml and html.slim files?

Body:
In the documentation you will find the following:

simple_form_for @admin_user, as: :some_user will look into the yml file under some_user instead of admin_user so the yml file will look like this:

en:
  simple_form:
    labels:
        admin_user:
            name: Admin Name
        some_user:
            name: Some user name

So in your simple_form you can add as: :client and as: :company and add those 2 to the yml file.


问:
Lefthook error: flutter command not found
I switched from GitHub Desktop to Sourcetree due to some missing feature.

On my flutter project, I installed LeftHook to execute a linter when someone commits something.
On GitHub Desktop, Lefthook works well, but when I try to commit from SourceTree, the  error sh: flutter: command not found

I can't understand why. The flutter SDK path is set globally correctly (i can use flutter commands in every terminal)

答:
Problem solved!

Seems like that Sourcetree isn't capable to access to the PATH in witch flutter is contained (the one added in the file .zshrc).
So the solution is to add the export in every hook that lefthook uses,
something like this:

```<code>#!/bin/sh

export PATH="$PATH:/Users/.../flutter/bin"

if [ "$LEFTHOOK" = "0" ]; then
...
</code>```

Body:
Problem solved!

Seems like that Sourcetree isn't capable to access to the PATH in witch flutter is contained (the one added in the file .zshrc).
So the solution is to add the export in every hook that lefthook uses,
something like this:

#!/bin/sh

export PATH="$PATH:/Users/.../flutter/bin"

if [ "$LEFTHOOK" = "0" ]; then
...


答:
You can assign simple form labels like this:

```<code>en:
  simple_form:
    labels:
      client:
        name: Client name
      company:
        name: Company name
</code>```

Or you can assign attributes like this:

```<code>en:
  activerecord:
    attributes:
      client:
        name: Client name
      company:
        name: Company name
</code>```

Title: connecting yml to html.slim

Body:
You can assign simple form labels like this:

en:
  simple_form:
    labels:
      client:
        name: Client name
      company:
        name: Company name

Or you can assign attributes like this:

en:
  activerecord:
    attributes:
      client:
        name: Client name
      company:
        name: Company name


问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
This is a very bad singleton implementation. You should use an implementation which is already here. There are a lot of them.. and your error will disappear.

For example, someone can set instance = NULL;. Doing that you can instantiate more than one instance.

ContentLicense: CC BY-SA 3.0

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?


问:
How to manipulate API results in JavaScript?
I am learning to use an API and I need some help.

I chose yahoo finance API and I'm trying to interpret the results. For this, I want to just access some of the data and display it on screen. I don't really know how I should do this. What is the correct method?

var configuration = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "yh-finance.p.rapidapi.com",
    "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
  },
};
var url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

var name = document.querySelector("stock-name");
var price = document.querySelector("stock-price");
var high = document.querySelector("stock-high");
var currency = document.querySelector("stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  name.innerHTML = "Stock name:" + Object.keys(stockData.meta.symbol);
  price.innetHTML = "Stock's price:" + stockData.priceHint;
  high.innerHTML = "Stock's high:" + stockData.indicators.quote[0].high[0];
  currency.innerHTML = "Stock's currecy:" + stockData.meta.currency;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> </div>
      <div><h3 id = "stock-name"></h3>
        <h3 id = "stock-price"></h3>
        <h3  id = "stock-high"></h3>
        <h3 id = "stock-currency"></h3>
      </div></code>```

I am not a fan of Jquery.

I tried accessing the data from API in the console with:

```<code>console.log(Object.keys(stockData.chart.result[0].meta));

console.log(Object.values(stockData.chart.result[0].meta));
</code>```

to see if I can access it like this, but I can't access one element, like meta[x], only the whole array.

Does anyone know where can I learn more about manipulating data from API? I couldn't find any good information...

Body:
I am learning to use an API and I need some help.

I chose yahoo finance API and I'm trying to interpret the results. For this, I want to just access some of the data and display it on screen. I don't really know how I should do this. What is the correct method?

var configuration = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "yh-finance.p.rapidapi.com",
    "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
  },
};
var url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

var name = document.querySelector("stock-name");
var price = document.querySelector("stock-price");
var high = document.querySelector("stock-high");
var currency = document.querySelector("stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  name.innerHTML = "Stock name:" + Object.keys(stockData.meta.symbol);
  price.innetHTML = "Stock's price:" + stockData.priceHint;
  high.innerHTML = "Stock's high:" + stockData.indicators.quote[0].high[0];
  currency.innerHTML = "Stock's currecy:" + stockData.meta.currency;
}

I am not a fan of Jquery.

I tried accessing the data from API in the console with:

console.log(Object.keys(stockData.chart.result[0].meta));

console.log(Object.values(stockData.chart.result[0].meta));

to see if I can access it like this, but I can't access one element, like meta[x], only the whole array.

Does anyone know where can I learn more about manipulating data from API? I couldn't find any good information...

Body:
{
  "chart": {
    "result": [
      {
        "meta": {
          "currency": "USD",
          "symbol": "AMRN",
          "exchangeName": "NGM",
          "instrumentType": "EQUITY",
          "firstTradeDate": 733674600,
          "regularMarketTime": 1644440402,
          "gmtoffset": -18000,
          "timezone": "EST",
          "exchangeTimezoneName": "America/New_York",
          "regularMarketPrice": 3.69,
          "chartPreviousClose": 3.53,
          "priceHint": 4,
          "currentTradingPeriod": {
            "pre": {
              "timezone": "EST",
              "end": 1644503400,
              "start": 1644483600,
              "gmtoffset": -18000
            },
            "regular": {
              "timezone": "EST",
              "end": 1644526800,
              "start": 1644503400,
              "gmtoffset": -18000
            },
            "post": {
              "timezone": "EST",
              "end": 1644541200,
              "start": 1644526800,
              "gmtoffset": -18000
            }
          },
          "dataGranularity": "1d",
          "range": "1d",
          "validRanges": [
            "1d",
            "5d",
            "1mo",
            "3mo",
            "6mo",
            "1y",
            "2y",
            "5y",
            "10y",
            "ytd",
            "max"
          ]
        },
        "timestamp": [
          1644417000,
          1644440402
        ],
        "indicators": {
          "quote": [
            {
              "open": [
                3.559999942779541,
                3.559999942779541
              ],
              "close": [
                3.690000057220459,
                3.690000057220459
              ],
              "high": [
                3.740000009536743,
                3.740000009536743
              ],
              "volume": [
                2084300,
                2089304
              ],
              "low": [
                3.559999942779541,
                3.559999942779541
              ]
            }
          ],
          "adjclose": [
            {
              "adjclose": [
                3.690000057220459,
                3.690000057220459
              ]
            }
          ]
        }
      }
    ],
    "error": null
  }
}

Sample response I got running your code

const metaData = stockData.chart.result[0].meta

metaData.currency //'USD'
metaData.regularMarketPrice //3.69

If you know the key you can directly get the value from it.


问:
Difference between r2_score and score() in linear regression
I found the results of score() in LinearRegression is different from r2_score(). I expected them to return the same results.The codes are as below:</p>
```<code>r2_train = np.empty(shape=[10, 0])
r2_train_n = np.empty(shape=[10, 0])

for set_degree in range (0,10):
    pf = PolynomialFeatures(degree= set_degree)
    X_train_tf = pf.fit_transform(X_train.reshape(11,1))
    X_test_tf = pf.transform(X_test.reshape(4,1))
    lr = LinearRegression().fit(X_train_tf, y_train)

    r2_train = np.append(r2_train, r2_score(lr.predict(X_train_tf), y_train))
    r2_train_n = np.append(r2_train_n, lr.score(X_train_tf, y_train))
</code>```

答:
In using r2_score, you made it:

```<code>r2_score(lr.predict(X_train_tf), y_train)
</code>```

According to the documentation, the first argument should be the true values, i.e. it should be:

```<code>r2_score(y_train, lr.predict(X_train_tf))
</code>```

This will give similar result with the score method in LinearRegression()

Same question here

Body:
I found the results of score() in LinearRegression is different from r2_score(). I expected them to return the same results.The codes are as below:

r2_train = np.empty(shape=[10, 0])
r2_train_n = np.empty(shape=[10, 0])

for set_degree in range (0,10):
    pf = PolynomialFeatures(degree= set_degree)
    X_train_tf = pf.fit_transform(X_train.reshape(11,1))
    X_test_tf = pf.transform(X_test.reshape(4,1))
    lr = LinearRegression().fit(X_train_tf, y_train)

    r2_train = np.append(r2_train, r2_score(lr.predict(X_train_tf), y_train))
    r2_train_n = np.append(r2_train_n, lr.score(X_train_tf, y_train))

Body:
In using r2_score, you made it:

r2_score(lr.predict(X_train_tf), y_train)

According to the documentation, the first argument should be the true values, i.e. it should be:

r2_score(y_train, lr.predict(X_train_tf))

This will give similar result with the score method in LinearRegression()

Same question here


问:
Google Cloud Storage Public Access
I have a question about public bucket sharing on my google platform. These are the details:

1 - I applied the public settings (adding AllUsers and AllAuthenticatedUsers to my bucket).
2 - I added some users with ObjectAdmin option so they can upload files.

When I access the bucket with my Google admin user, I can see the "Copy URL" option in the "Public Access" column in the bucket files (shortcut).

public access shrotcut ok for admin

This is not the case for public (authenticated or unauthenticated) internet users. For these users, the value "Access granted to public principals" or "Value hidden" appears in the "Public Access" column.

value hidden but click on file shows public url

For the users I added as ObjectAdmin, when opening the file in Public URL, the value "Access granted to public principals" appears

click on file Public URL Not applicable

If the access is through any user without ObjectAdmin, I can see the public url when opening the file.

In all scenarios, I can collect the Public URL by clicking the "..." in the file.

Do you know what options I would need to edit or apply (or what roles are needed) in order for the public URL to be displayed as it currently is in the admin user?

This was working last month and I believe it has something to do with Google role updates.

Thanks!

答:
I had a similar problem with disappearing of "Copy URL" link in a list of files on a storage bucket.

After some time of playing with permissions I've figured out that users having "Storage Object Admin" role on a bucket level need also the "Storage Legacy Bucket Owner" role additionally. Then such users can see the link "Copy URL" again.

It looks like Google changed the set of available roles/permissions for cloud storage and automatically granted "Storage Legacy Bucket Owner" role to Owners and Editors of the project. But when users added on a bucket level (not via project's IAM) they don't fit to those project roles, even if they are Admins for the bucket.

Title: Google Cloud Storage Public Access


问:
Composer Require 'package' throws OpenSSL error
This problem seems to be common, and i've been through a lot of SO posts related to it and nothing works, and i'm going crazy. Whats weird is that it was working perfectly few weeks ago, and i didnt install anything new since months...

Setup :

PHP 7.1.9

WAMPSERVER 3.1.0

APACHE 2.4.27

Composer 1.6.5 (latest)

I'm not behind a proxy & no firewall

Windows 10

What Works :

composer self-update

What does not work :

Installing a package

I cannot reach https://packagist.org/ with firefox 61.0.1 (64bits) (unsecure connection : MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT)

The error i get with composer require :

```<code>[Composer\Downloader\TransportException]
The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
</code>```

php -r "var_dump(openssl_get_cert_locations());" Returns this :

```<code>array(8) {
  ["default_cert_file"]=>
  string(25) "c:/usr/local/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(22) "c:/usr/local/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(24) "c:/usr/local/ssl/private"
  ["default_default_cert_area"]=>
  string(16) "c:/usr/local/ssl"
  ["ini_cafile"]=>
  string(51) "C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt"
  ["ini_capath"]=>
  string(0) ""
}
</code>```

I've downloaded the ca-bundle.crt and added it to my php.ini file :

```<code>curl.cainfo=C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt
openssl.cafile=C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt
</code>```

Composer diagnose returns this :

```<code>Checking composer.json: OK
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: WARNING
[Composer\Downloader\TransportException] The "http://packagist.org/packages.json" file could not be downloaded (HTTP/1.1 404 Not Found)
Checking https connectivity to packagist: WARNING
[Composer\Downloader\TransportException] The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
Checking github.com rate limit: OK
Checking disk free space: OK
Checking pubkeys: OK
Checking composer version: OK
Composer version: 1.6.5
PHP version: 7.1.9
PHP binary path: C:\wamp64\bin\php\php7.1.9\php.exe
</code>```

composer show -p -vvv | grep ssl returns this :

```<code>Reading ./composer.json
Loading config file ./composer.json
Checked CA file C:\wamp64\bin\php\php7.1.9\extras\ssl\ca-bundle.crt: valid
Executing command (C:\wamp64\www\projectName): git branch --no-color --no-abbrev -v
Failed to initialize global composer: Composer could not find the config file: C:/Users/********/AppData/Roaming/Composer/composer.json
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
Reading C:\wamp64\www\projectName/vendor/composer/installed.json
Loading plugin PackageVersions\Installer
Loading plugin Symfony\Flex\Flex
Composer >=1.7 not found, downloads will happen in sequence
Running 1.6.5 (2018-05-04 11:44:59) with PHP 7.1.9 on Windows NT / 10.0
ext-openssl         7.1.9    The openssl PHP extension
lib-openssl         1.0.2.11 OpenSSL 1.0.2k  26 Jan 2017
</code>```

php --ini :

```<code>Configuration File (php.ini) Path: C:\WINDOWS
Loaded Configuration File:         C:\wamp64\bin\php\php7.1.9\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
</code>```

EDIT 1

- Tried emptying cache

- Other web browser (chrome, edge) and it didnt work

- Another computer on same network --> it works

EDIT 2

- Created a new windows user, didnt work

EDIT 3

- I can reach https://repo.packagist.org/ as suggested by @kallosz

- Curl gives me this :

```<code>curl -vvv https://packagist.org/
*   Trying 144.217.203.53...
* TCP_NODELAY set
* Connected to packagist.org (144.217.203.53) port 443 (#0)
* schannel: SSL/TLS connection with packagist.org port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 178 bytes...
* schannel: sent initial handshake data: sent 178 bytes
* schannel: SSL/TLS connection with packagist.org port 443 (step 2/3)
* schannel: failed to receive handshake, need more data
* schannel: SSL/TLS connection with packagist.org port 443 (step 2/3)
* schannel: encrypted data got 1462
* schannel: encrypted data buffer: offset 1462 length 4096
* schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325) - La chaîne de certificats a été fournie par une autorité qui n'est pas approuvée.
* Closing connection 0
* schannel: shutting down SSL/TLS connection with packagist.org port 443
* schannel: clear security context handle
curl: (77) schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325)
</code>```

答:
I had to change the global config file

C:\Users\USERNAME\AppData\Roaming\Composer\config.json

to this:

```<code>{
    "config": {
        "disable-tls": true,
        "secure-http": false
    },
    "repositories": [
        {
            "type": "composer",
            "url": "http://repo.packagist.org"
        }
    ]
}
</code>```

Body:
This problem seems to be common, and i've been through a lot of SO posts related to it and nothing works, and i'm going crazy. Whats weird is that it was working perfectly few weeks ago, and i didnt install anything new since months...

Setup :

PHP 7.1.9

WAMPSERVER 3.1.0

APACHE 2.4.27

Composer 1.6.5 (latest)

I'm not behind a proxy & no firewall

Windows 10

What Works :

composer self-update

What does not work :

Installing a package

I cannot reach https://packagist.org/ with firefox 61.0.1 (64bits) (unsecure connection : MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT)

The error i get with composer require :

[Composer\Downloader\TransportException]
The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed

php -r "var_dump(openssl_get_cert_locations());" Returns this :

array(8) {
  ["default_cert_file"]=>
  string(25) "c:/usr/local/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(22) "c:/usr/local/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(24) "c:/usr/local/ssl/private"
  ["default_default_cert_area"]=>
  string(16) "c:/usr/local/ssl"
  ["ini_cafile"]=>
  string(51) "C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt"
  ["ini_capath"]=>
  string(0) ""
}

I've downloaded the ca-bundle.crt and added it to my php.ini file :

curl.cainfo=C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt
openssl.cafile=C:/wamp64/bin/php/php7.1.9/extras/ssl/ca-bundle.crt

Composer diagnose returns this :

Checking composer.json: OK
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: WARNING
[Composer\Downloader\TransportException] The "http://packagist.org/packages.json" file could not be downloaded (HTTP/1.1 404 Not Found)
Checking https connectivity to packagist: WARNING
[Composer\Downloader\TransportException] The "https://packagist.org/packages.json" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
Failed to enable crypto
failed to open stream: operation failed
Checking github.com rate limit: OK
Checking disk free space: OK
Checking pubkeys: OK
Checking composer version: OK
Composer version: 1.6.5
PHP version: 7.1.9
PHP binary path: C:\wamp64\bin\php\php7.1.9\php.exe

composer show -p -vvv | grep ssl returns this :

Reading ./composer.json
Loading config file ./composer.json
Checked CA file C:\wamp64\bin\php\php7.1.9\extras\ssl\ca-bundle.crt: valid
Executing command (C:\wamp64\www\projectName): git branch --no-color --no-abbrev -v
Failed to initialize global composer: Composer could not find the config file: C:/Users/********/AppData/Roaming/Composer/composer.json
To initialize a project, please create a composer.json file as described in the https://getcomposer.org/ "Getting Started" section
Reading C:\wamp64\www\projectName/vendor/composer/installed.json
Loading plugin PackageVersions\Installer
Loading plugin Symfony\Flex\Flex
Composer >=1.7 not found, downloads will happen in sequence
Running 1.6.5 (2018-05-04 11:44:59) with PHP 7.1.9 on Windows NT / 10.0
ext-openssl         7.1.9    The openssl PHP extension
lib-openssl         1.0.2.11 OpenSSL 1.0.2k  26 Jan 2017

php --ini :

Configuration File (php.ini) Path: C:\WINDOWS
Loaded Configuration File:         C:\wamp64\bin\php\php7.1.9\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

EDIT 1

- Tried emptying cache

- Other web browser (chrome, edge) and it didnt work

- Another computer on same network --> it works

EDIT 2

- Created a new windows user, didnt work

EDIT 3

- I can reach https://repo.packagist.org/ as suggested by @kallosz

- Curl gives me this :

curl -vvv https://packagist.org/
*   Trying 144.217.203.53...
* TCP_NODELAY set
* Connected to packagist.org (144.217.203.53) port 443 (#0)
* schannel: SSL/TLS connection with packagist.org port 443 (step 1/3)
* schannel: checking server certificate revocation
* schannel: sending initial handshake data: sending 178 bytes...
* schannel: sent initial handshake data: sent 178 bytes
* schannel: SSL/TLS connection with packagist.org port 443 (step 2/3)
* schannel: failed to receive handshake, need more data
* schannel: SSL/TLS connection with packagist.org port 443 (step 2/3)
* schannel: encrypted data got 1462
* schannel: encrypted data buffer: offset 1462 length 4096
* schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325) - La chaîne de certificats a été fournie par une autorité qui n'est pas approuvée.
* Closing connection 0
* schannel: shutting down SSL/TLS connection with packagist.org port 443
* schannel: clear security context handle
curl: (77) schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325)

Body:
I had to change the global config file

C:\Users\USERNAME\AppData\Roaming\Composer\config.json

to this:

{
    "config": {
        "disable-tls": true,
        "secure-http": false
    },
    "repositories": [
        {
            "type": "composer",
            "url": "http://repo.packagist.org"
        }
    ]
}


问:
Download a sub stream with youtube_explode_dart
I'm developing a Flutter app, using the package youtube_explode_dart.
Currently I download all the audio stream, then crop it using ffmpeg. Quickly this looks like :

var id = "aboZctrHfK8";
var file = File("mySong.mp4");
var start = "2000ms";
var end = "5000ms";

// Downloading audio only
var manifest = await yt.videos.streamsClient.getManifest(id);
var audio = manifest.audioOnly.first;
var audioStream = yt.videos.streamsClient.get(audio);
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
for (final data in audioStream) {
    output.add(data);
}

// Croping audio
FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();
await _flutterFFmpeg.executeWithArguments([
      "-v", "error",
      "-ss", start,
      "-to", end,
      "-i", file.path,
      "-acodec", "copy", "myCroppedSong.mp4"]);
```
<p>Now I'm facing another issue: Some videos are really heavy and take a while to download. This is not acceptable for my end users, especially since I only want part of the original audio.</p>
<p><strong>Is there a way to download only a subset of the audio stream?</strong></p>
<p>Something like:</p>
<pre class="lang-dart prettyprint-override"><code>for (final data in audioStream.subset(start, end)) {
    output.add(data);
}
</code>```

It would be anwsome!

答:
```<code>    import 'package:youtube_explode_dart/youtube_explode_dart.dart';

// Initialize the YoutubeExplode instance.
final yt = YoutubeExplode();

Future<void> ExplodeDown() async {
  stdout.writeln('Type the video id or url: ');

  var url = stdin.readLineSync()!.trim();

  // Save the video to the download directory.
  Directory('downloads').createSync();

  // Download the video.
  await download(url);

  yt.close();
  exit(0);
}

Future<void> download(String id) async {
  // Get video metadata.
  var video = await yt.videos.get(id);

  // Get the video manifest.
  var manifest = await yt.videos.streamsClient.getManifest(id);
  var streams = manifest.videoOnly;

  // Get the audio track with the highest bitrate.
  var audio = streams.first;
  var audioStream = yt.videos.streamsClient.get(audio);

  // Compose the file name removing the unallowed characters in windows.
  var fileName = '${video.title}.${audio.container.name}'
      .replaceAll(r'\', '')
      .replaceAll('/', '')
      .replaceAll('*', '')
      .replaceAll('?', '')
      .replaceAll('"', '')
      .replaceAll('<', '')
      .replaceAll('>', '')
      .replaceAll('|', '');
  var file = File('downloads/$fileName');

  // Delete the file if exists.
  if (file.existsSync()) {
    file.deleteSync();
  }

  // Open the file in writeAppend.
  var output = file.openWrite(mode: FileMode.writeOnlyAppend);

  // Track the file download status.
  var len = audio.size.totalBytes;
  var count = 0;

  // Create the message and set the cursor position.
  var msg = 'Downloading ${video.title}.${audio.container.name}';
  stdout.writeln(msg);

  // Listen for data received.
  //  var progressBar = ProgressBar();
  await for (final data in audioStream) {
    // Keep track of the current downloaded data.
    count += data.length;

    // Calculate the current progress.
    var progress = ((count / len) * 100).ceil();
    print (progress);

    // Update the progressbar.
    // progressBar.update(progress);

    // Write to file.
    output.add(data);
  }
  await output.close();
}
</code>```
<blockquote>
```<code>  **How to download load youtube video & audio & play stream audio **
</code>```
</blockquote>

Body:
I'm developing a Flutter app, using the package youtube_explode_dart.
Currently I download all the audio stream, then crop it using ffmpeg. Quickly this looks like :

var id = "aboZctrHfK8";
var file = File("mySong.mp4");
var start = "2000ms";
var end = "5000ms";

// Downloading audio only
var manifest = await yt.videos.streamsClient.getManifest(id);
var audio = manifest.audioOnly.first;
var audioStream = yt.videos.streamsClient.get(audio);
var output = file.openWrite(mode: FileMode.writeOnlyAppend);
for (final data in audioStream) {
    output.add(data);
}

// Croping audio
FlutterFFmpeg _flutterFFmpeg = new FlutterFFmpeg();
await _flutterFFmpeg.executeWithArguments([
      "-v", "error",
      "-ss", start,
      "-to", end,
      "-i", file.path,
      "-acodec", "copy", "myCroppedSong.mp4"]);

Now I'm facing another issue: Some videos are really heavy and take a while to download. This is not acceptable for my end users, especially since I only want part of the original audio.

Is there a way to download only a subset of the audio stream?

Something like:

for (final data in audioStream.subset(start, end)) {
    output.add(data);
}

It would be anwsome!

Body:
    import 'package:youtube_explode_dart/youtube_explode_dart.dart';

// Initialize the YoutubeExplode instance.
final yt = YoutubeExplode();

Future<void> ExplodeDown() async {
  stdout.writeln('Type the video id or url: ');

  var url = stdin.readLineSync()!.trim();

  // Save the video to the download directory.
  Directory('downloads').createSync();

  // Download the video.
  await download(url);

  yt.close();
  exit(0);
}

Future<void> download(String id) async {
  // Get video metadata.
  var video = await yt.videos.get(id);

  // Get the video manifest.
  var manifest = await yt.videos.streamsClient.getManifest(id);
  var streams = manifest.videoOnly;

  // Get the audio track with the highest bitrate.
  var audio = streams.first;
  var audioStream = yt.videos.streamsClient.get(audio);

  // Compose the file name removing the unallowed characters in windows.
  var fileName = '${video.title}.${audio.container.name}'
      .replaceAll(r'\', '')
      .replaceAll('/', '')
      .replaceAll('*', '')
      .replaceAll('?', '')
      .replaceAll('"', '')
      .replaceAll('<', '')
      .replaceAll('>', '')
      .replaceAll('|', '');
  var file = File('downloads/$fileName');

  // Delete the file if exists.
  if (file.existsSync()) {
    file.deleteSync();
  }

  // Open the file in writeAppend.
  var output = file.openWrite(mode: FileMode.writeOnlyAppend);

  // Track the file download status.
  var len = audio.size.totalBytes;
  var count = 0;

  // Create the message and set the cursor position.
  var msg = 'Downloading ${video.title}.${audio.container.name}';
  stdout.writeln(msg);

  // Listen for data received.
  //  var progressBar = ProgressBar();
  await for (final data in audioStream) {
    // Keep track of the current downloaded data.
    count += data.length;

    // Calculate the current progress.
    var progress = ((count / len) * 100).ceil();
    print (progress);

    // Update the progressbar.
    // progressBar.update(progress);

    // Write to file.
    output.add(data);
  }
  await output.close();
}

  **How to download load youtube video & audio & play stream audio **


问:
How to use the __import__ function to import a name from a submodule?
I'm trying to replicate from foo.bar import object using the __import__ function and I seem to have hit a wall.

A simpler case from glob import glob is easy: glob = __import__("glob").glob

The problem I'm having is that I am importing a name from a subpackage (i.e. from foo.bar):

So what I'd like is something like

```<code>string_to_import = "bar"
object = __import__("foo." + string_to_import).object
</code>```

But this just imported the top-level foo package, not the foo.bar subpackage:

```<code>__import__("foo.bar")
<module 'foo' from 'foo/__init__.pyc'>
</code>```

答:
In addition to these excellent answers, I use __import__ for convenience, to call an one-liner on the fly. Examples like the following can also be saved as auto-triggered snippets at your IDE.

Plant an ipdb break-point (triggered with "ipdb")

__import__("ipdb").set_trace(context=9)
```
<ul>
<li>Print prettily (triggered with "pp")</li>
</ul>
<pre class="lang-py prettyprint-override"><code>__import__("pprint").pprint(<cursor-position>)
</code>```

This way, you get a temporary object, that is not referenced by anything, and call an attribute on the spot. Also, you can easily comment, uncomment or delete a single line.

Body:
I'm trying to replicate from foo.bar import object using the __import__ function and I seem to have hit a wall.

A simpler case from glob import glob is easy: glob = __import__("glob").glob

The problem I'm having is that I am importing a name from a subpackage (i.e. from foo.bar):

So what I'd like is something like

string_to_import = "bar"
object = __import__("foo." + string_to_import).object

But this just imported the top-level foo package, not the foo.bar subpackage:

__import__("foo.bar")
<module 'foo' from 'foo/__init__.pyc'>

Body:
In addition to these excellent answers, I use __import__ for convenience, to call an one-liner on the fly. Examples like the following can also be saved as auto-triggered snippets at your IDE.

Plant an ipdb break-point (triggered with "ipdb")

__import__("ipdb").set_trace(context=9)

Print prettily (triggered with "pp")

__import__("pprint").pprint(<cursor-position>)

This way, you get a temporary object, that is not referenced by anything, and call an attribute on the spot. Also, you can easily comment, uncomment or delete a single line.


问:
Scala alternative cases match syntax with different type of extracted value
```<code>object NoSense {
   def main(args: Array[String]) {
      val value = "true" match {
         case value @ (IntValue(_) | BooleanValue(_)) => value
      }
      require(value == true)
   }
}

class Value[T](val regex: Regex, convent: String => T) {
   def unapply(value: String): Option[T] = value match {
      case regex(value, _*) => Some(convent(value))
      case _ => None
   }
}
object IntValue extends Value[Int]("[0-9]+".r, _.toInt)
object BooleanValue extends Value[Boolean]("((true)|(false))".r, _.toBoolean)
</code>```

The require in the main method will fail.

but this one is ok

```<code>def main(args: Array[String]) {
      val value = "true" match {
         case IntValue(value) => value
         case BooleanValue(value) => value
      }
      require(value == true)
   }
</code>```

Is that the limitation of scala language itself or i am doing in a wrong way

答:
It's... both.

You may take a look how at how the pattern binder behave in the Scala specification §8.1.3. It says that in pattern x@p:

The type of the variable x is the static type T of the pattern p.

In your case, the pattern p is IntValue(_) | BooleanValue(_). As IntValue and BooleanValue unapply-methods both require a String, the static type of your pattern is String, thus, the type of xis String.

In the second case, value is extracted from BooleanValue and have the right type.

Unfortunately, scala does not support alternatives of extractors patterns, thus you must stick to your second version.

Body:
object NoSense {
   def main(args: Array[String]) {
      val value = "true" match {
         case value @ (IntValue(_) | BooleanValue(_)) => value
      }
      require(value == true)
   }
}

class Value[T](val regex: Regex, convent: String => T) {
   def unapply(value: String): Option[T] = value match {
      case regex(value, _*) => Some(convent(value))
      case _ => None
   }
}
object IntValue extends Value[Int]("[0-9]+".r, _.toInt)
object BooleanValue extends Value[Boolean]("((true)|(false))".r, _.toBoolean)

The require in the main method will fail.

but this one is ok

def main(args: Array[String]) {
      val value = "true" match {
         case IntValue(value) => value
         case BooleanValue(value) => value
      }
      require(value == true)
   }

Is that the limitation of scala language itself or i am doing in a wrong way


问:
Cypress - user defined function returns the wrong value
I have two user defined functions in Cypress to use for login.

Here's the code:

```<code>static GetUserGUID(clientId: string): string {

    const headers = {
        'Content-Type': 'application/json'
    };

    cy
        .request({ method: 'GET', url: `api/v1/Administration/User?UserTypeId=1&ClientId=` + clientId, headers })
        .then((resp) => {

            const userObject: UserObject = resp.body;
            const userData = userObject.users[0]
            return userData.id

        })

    return "User not found"

}
</code>```

This always returns user not found.
I've been reading about cypress promises, commands and it really is a mess.

How would I get userdata.id from here?
Thanks

答:
As cypress commands are asynchronous, you cannot return a user id string directly. It's possible to return a Chainable with that string instead:

static GetUserGUID(clientId: string): Chainable<string> {

    const headers = {
        'Content-Type': 'application/json'
    };

    return cy
        .request({ method: 'GET', url: `api/v1/Administration/User?UserTypeId=1&ClientId=` + clientId, headers })
        .then((resp) => {

            const userObject: UserObject = resp.body;
            const userData = userObject.users[0]
            return userData.id

        })
}
```
<p>Use it in your test as follows:</p>
<pre class="lang-js prettyprint-override"><code>GetUserGUID("myId").then(userId => {
   // you get the 'userId' as a string here.
})
</code>```

Body:
I have two user defined functions in Cypress to use for login.

Here's the code:

static GetUserGUID(clientId: string): string {

    const headers = {
        'Content-Type': 'application/json'
    };

    cy
        .request({ method: 'GET', url: `api/v1/Administration/User?UserTypeId=1&ClientId=` + clientId, headers })
        .then((resp) => {

            const userObject: UserObject = resp.body;
            const userData = userObject.users[0]
            return userData.id

        })

    return "User not found"

}

This always returns user not found.
I've been reading about cypress promises, commands and it really is a mess.

How would I get userdata.id from here?
Thanks

Body:
As cypress commands are asynchronous, you cannot return a user id string directly. It's possible to return a Chainable with that string instead:

static GetUserGUID(clientId: string): Chainable<string> {

    const headers = {
        'Content-Type': 'application/json'
    };

    return cy
        .request({ method: 'GET', url: `api/v1/Administration/User?UserTypeId=1&ClientId=` + clientId, headers })
        .then((resp) => {

            const userObject: UserObject = resp.body;
            const userData = userObject.users[0]
            return userData.id

        })
}

Use it in your test as follows:

GetUserGUID("myId").then(userId => {
   // you get the 'userId' as a string here.
})


问:
How to force a Airflow Task to restart at the new scheduling date?
I have this simple Airflow DAG:

```<code>from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash import BashOperator
with DAG("Second Dag",
        start_date=datetime(2022,1,1),
        schedule_interval="0 5 * * *",
        catchup=False,
        max_active_runs=1
        ) as dag:

    task_a = BashOperator(
        task_id="ToRepeat",
        bash_command="cd /home/xdf/local/ && (env/bin/python workflow/test1.py)",
        retries =1,
    )
</code>```

The task takes a variable amount of time between one run and the other, and I don't have any guarantee that it will be finished within the 5 A.M of the next day.
If the task is still running when a new task is scheduled to start, I need to kill the old one before it starts running.

How can I design Airflow DAG to automatically kill the old task if it's still running when a new task is scheduled to start?

More details:
I am looking for something dynamic. The old DAG should be killed only when the new DAG is starting. If, for any reason, the new DAG does not start for one week, then old DAG should be able to run for an entire week. That's why using a timeout is sub-optimal

答:
You should set dagrun_timeout for your DAG.

```<code>dagrun_timeout: specify how long a DagRun should be up before
timing out / failing, so that new DagRuns can be created. The timeout
is only enforced for scheduled DagRuns.
</code>```

Since your DAG runs daily you can set 24 hours for timeout.

```<code>with DAG("Second Dag",
        start_date=datetime(2022,1,1),
        schedule_interval="0 5 * * *",
        catchup=False,
        max_active_runs=1
        dagrun_timeout=timedelta(hours=24)
        ) as dag:
</code>```

If you want to set timeout on a specific task in your DAG you should use execution_timeout on your operator.

execution_timeout: max time allowed for the execution of this task instance, if it goes beyond it will raise and fail

Example:

```<code>MyOperator(task_id='task', execution_timeout=timedelta(hours=24))
</code>```

Body:
I have this simple Airflow DAG:

from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash import BashOperator
with DAG("Second Dag",
        start_date=datetime(2022,1,1),
        schedule_interval="0 5 * * *",
        catchup=False,
        max_active_runs=1
        ) as dag:

    task_a = BashOperator(
        task_id="ToRepeat",
        bash_command="cd /home/xdf/local/ && (env/bin/python workflow/test1.py)",
        retries =1,
    )

The task takes a variable amount of time between one run and the other, and I don't have any guarantee that it will be finished within the 5 A.M of the next day.
If the task is still running when a new task is scheduled to start, I need to kill the old one before it starts running.

How can I design Airflow DAG to automatically kill the old task if it's still running when a new task is scheduled to start?

More details:
I am looking for something dynamic. The old DAG should be killed only when the new DAG is starting. If, for any reason, the new DAG does not start for one week, then old DAG should be able to run for an entire week. That's why using a timeout is sub-optimal

Body:
You should set dagrun_timeout for your DAG.

dagrun_timeout: specify how long a DagRun should be up before
timing out / failing, so that new DagRuns can be created. The timeout
is only enforced for scheduled DagRuns.

Since your DAG runs daily you can set 24 hours for timeout.

with DAG("Second Dag",
        start_date=datetime(2022,1,1),
        schedule_interval="0 5 * * *",
        catchup=False,
        max_active_runs=1
        dagrun_timeout=timedelta(hours=24)
        ) as dag:

If you want to set timeout on a specific task in your DAG you should use execution_timeout on your operator.

execution_timeout: max time allowed for the execution of this task instance, if it goes beyond it will raise and fail

Example:

MyOperator(task_id='task', execution_timeout=timedelta(hours=24))


问:
Align single item left when Column crossAxisAlignment is center
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

```<code>return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);
</code>```

答:
try this way</p>
```<code>Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text('Left'),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
      ],
    )
</code>```

Body:
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);

Body:
try this way

Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text('Left'),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
        Align(alignment: Alignment.center, child: Text('Center')),
      ],
    )


问:
Docker Moodle localhost not working (CentOS)
I have to work with Moodle, so I installed Moodle from here: https://hub.docker.com/r/jauer/moodle

I created the docker containers.

MySQL container:

```<code>docker run -d --name DB -p 3306:3306 -e MYSQL_DATABASE=moodle -e MYSQL_ROOT_PASSWORD=moodle -e MYSQL_USER=moodle -e MYSQL_PASSWORD=moodle mysql
</code>```

Moodle container:

```<code>docker run -d -P --name moodle --link DB:DB -e MOODLE_URL=http://localhost:8081 -p 8081:80 jhardison/moodle
</code>```

Result after docker ps -a:

```<code>CONTAINER ID   IMAGE              COMMAND                  CREATED         STATUS                     PORTS                                                                              NAMES
647128e9d155   jhardison/moodle   "/etc/apache2/foregr…"   7 minutes ago   Up 7 minutes               0.0.0.0:8081->80/tcp, :::8081->80/tcp, 0.0.0.0:49157->443/tcp, :::49157->443/tcp   moodle

e83ad7433905   mysql              "docker-entrypoint.s…"   7 minutes ago   Up 7 minutes               0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp                               DB
</code>```

I open http://localhost:8081 but nothing is showing. Message: Can't connect.
Also http://localhost:8080 is a white webpage. It loads but without content.

My Apache version:

```<code>httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Nov 16 2020 16:18:20
</code>```

I have a Windows host machine and I am connecting via ssh to a CentOS VM. I have also installed SimpleSAMLphp in the VM, and I can access to it from Windows at https://localhost:8443/simplesaml/module.php

I need to make Moodle work. I have read forum topics, tried different ways to install Moodle but still can't achieve what I want. It must be installed in CentOS.

Thanks in advance and I hope you could help me.

答:
I think you should go with bitnami moodle image as they have all the latest release and they have also documented the installation process pretty well

https://hub.docker.com/r/bitnami/moodle/

Body:
I have to work with Moodle, so I installed Moodle from here: https://hub.docker.com/r/jauer/moodle

I created the docker containers.

MySQL container:

docker run -d --name DB -p 3306:3306 -e MYSQL_DATABASE=moodle -e MYSQL_ROOT_PASSWORD=moodle -e MYSQL_USER=moodle -e MYSQL_PASSWORD=moodle mysql

Moodle container:

docker run -d -P --name moodle --link DB:DB -e MOODLE_URL=http://localhost:8081 -p 8081:80 jhardison/moodle

Result after docker ps -a:

CONTAINER ID   IMAGE              COMMAND                  CREATED         STATUS                     PORTS                                                                              NAMES
647128e9d155   jhardison/moodle   "/etc/apache2/foregr…"   7 minutes ago   Up 7 minutes               0.0.0.0:8081->80/tcp, :::8081->80/tcp, 0.0.0.0:49157->443/tcp, :::49157->443/tcp   moodle

e83ad7433905   mysql              "docker-entrypoint.s…"   7 minutes ago   Up 7 minutes               0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp                               DB

I open http://localhost:8081 but nothing is showing. Message: Can't connect.
Also http://localhost:8080 is a white webpage. It loads but without content.

My Apache version:

httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Nov 16 2020 16:18:20

I have a Windows host machine and I am connecting via ssh to a CentOS VM. I have also installed SimpleSAMLphp in the VM, and I can access to it from Windows at https://localhost:8443/simplesaml/module.php

I need to make Moodle work. I have read forum topics, tried different ways to install Moodle but still can't achieve what I want. It must be installed in CentOS.

Thanks in advance and I hope you could help me.


问:
Executing a timeout prior to the defined delay
Say I have the following JavaScript code (in global context):

```<code>var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout
</code>```

One can now cancel the set timeout:

```<code>clearTimeout(t);
</code>```

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

```<code>var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();
</code>```

or

```<code>executeAndClearTimeout(t); // Does this one?
</code>```

答: I don't think such a function exists... but you're allready saving t, why not save f as well?

Body:
Say I have the following JavaScript code (in global context):

var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout

One can now cancel the set timeout:

clearTimeout(t);

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();

or

executeAndClearTimeout(t); // Does this one?


问:
How to register custom field that is based on existing value in REST route
Iam registering a rest route (see Code 1) whereby the content of the route  will be equal to results from the wpso_messages database.

The resultant JSON of the get request to the custom route is below. (see #Resultant Json)

I would like to register 2 additional custom fields in the rest route which are:  <username_from> and <username_to> that are based on the login names of the userids currently defined in the  <user_from> and <user_to> (see Resultant JSON).

I understand that I may have to use register rest field function (see sample code 2), however it doesnt seem to be getting hooked to the registered custom rest route, also, I would need to access the user_from column in the existing api callback.

Any advise?

#Code 1: Register Rest Route

```<code><?php

 function get_wp_query() {
    global $wpdb;
      $row = $wpdb->get_results("SELECT * FROM wpso_messages");
      return $row;
      };
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );
</code>```

#Resultant JSON

{
"id": "1",
"user_from": "82",
"user_to": "1",
"created_at": "2022-01-07 10:25:56",
"message": "Iam interest to bid",
"listing_id": "22775",
"seen": "1"
}

Code 2:

```<code>function get_custom_fields() {
    return 'our awesome endpoint';
}
add_action( 'rest_api_init', 'add_custom_fields' );

function add_custom_fields() {
    register_rest_field(
        'messages',
        'custom_fields', //New Field Name in JSON RESPONSEs
        array(
            'get_callback'    => 'get_custom_fields', // custom function name
            'update_callback' => null,
            'schema'          => null,
            )
        );
    }
</code>```

答:
In your get_wp_query() function, don't return the results immediately. First, loop through them and add required fields from there.

In your case:

```<code>function get_wp_query() {
   global $wpdb;
   $rows = $wpdb->get_results("SELECT * FROM wpso_messages");

   foreach( $rows as $index => $row ) {
        $rows[$index]->username_from = get_user_by('id', $row.user_from)->display_name;
        $rows[$index]->username_to = get_user_by('id', $row.user_to)->display_name;
   }
   return $rows;
};
</code>```

get_user_by() function reference

Body:
Iam registering a rest route (see Code 1) whereby the content of the route  will be equal to results from the wpso_messages database.

The resultant JSON of the get request to the custom route is below. (see #Resultant Json)

I would like to register 2 additional custom fields in the rest route which are:  <username_from> and <username_to> that are based on the login names of the userids currently defined in the  <user_from> and <user_to> (see Resultant JSON).

I understand that I may have to use register rest field function (see sample code 2), however it doesnt seem to be getting hooked to the registered custom rest route, also, I would need to access the user_from column in the existing api callback.

Any advise?

#Code 1: Register Rest Route

<?php

 function get_wp_query() {
    global $wpdb;
      $row = $wpdb->get_results("SELECT * FROM wpso_messages");
      return $row;
      };
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );

#Resultant JSON

{
"id": "1",
"user_from": "82",
"user_to": "1",
"created_at": "2022-01-07 10:25:56",
"message": "Iam interest to bid",
"listing_id": "22775",
"seen": "1"
}

Code 2:

function get_custom_fields() {
    return 'our awesome endpoint';
}
add_action( 'rest_api_init', 'add_custom_fields' );

function add_custom_fields() {
    register_rest_field(
        'messages',
        'custom_fields', //New Field Name in JSON RESPONSEs
        array(
            'get_callback'    => 'get_custom_fields', // custom function name
            'update_callback' => null,
            'schema'          => null,
            )
        );
    }

Body:
In your get_wp_query() function, don't return the results immediately. First, loop through them and add required fields from there.

In your case:

function get_wp_query() {
   global $wpdb;
   $rows = $wpdb->get_results("SELECT * FROM wpso_messages");

   foreach( $rows as $index => $row ) {
        $rows[$index]->username_from = get_user_by('id', $row.user_from)->display_name;
        $rows[$index]->username_to = get_user_by('id', $row.user_to)->display_name;
   }
   return $rows;
};

get_user_by() function reference


问:
Sampling an element from a list in R
I have a list called MyList that looks like this:

```<code>[[1]]
[1] 5

[[2]]
integer(0)

[[3]]
[1]  5 16

[[4]]
[1] 9

[[5]]
integer(0)
</code>```

I want to sample one of the numbers 5,5,16,9 along with which list element it has come from. E.g. if the first 5 is picked out I would like the sample result to be c(1,5) but if the second 5 is chosen I want the result to be c(3,5). I also don't want to include empty values integer(0) in the sampling.

答:
One way would be to bring this list in a more manageable data structure (like matrix or a dataframe) dropping the empty values.

```<code>mat <- unname(do.call(rbind, Map(function(x, y)
               if(length(y)) cbind(x, y), seq_along(MyList), MyList)))
mat
#      [,1] [,2]
#[1,]    1    5
#[2,]    3    5
#[3,]    3   16
#[4,]    4    9
</code>```

then select any one row from the matrix.

```<code>mat[sample(nrow(mat), 1),]
</code>```

data

```<code>MyList <- list(5, integer(0), c(5, 16), 9, integer(0))
</code>```

Title: Sampling an element from a list in R

Body:
I have a list called MyList that looks like this:

[[1]]
[1] 5

[[2]]
integer(0)

[[3]]
[1]  5 16

[[4]]
[1] 9

[[5]]
integer(0)

I want to sample one of the numbers 5,5,16,9 along with which list element it has come from. E.g. if the first 5 is picked out I would like the sample result to be c(1,5) but if the second 5 is chosen I want the result to be c(3,5). I also don't want to include empty values integer(0) in the sampling.

Body:
One way would be to bring this list in a more manageable data structure (like matrix or a dataframe) dropping the empty values.

mat <- unname(do.call(rbind, Map(function(x, y)
               if(length(y)) cbind(x, y), seq_along(MyList), MyList)))
mat
#      [,1] [,2]
#[1,]    1    5
#[2,]    3    5
#[3,]    3   16
#[4,]    4    9

then select any one row from the matrix.

mat[sample(nrow(mat), 1),]

data

MyList <- list(5, integer(0), c(5, 16), 9, integer(0))


问:
Python flask script not executing as expected
I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.

I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.

python code:

```<code>from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve

app = Flask(__name__)

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

if __name__ == "__main__":
    app.debug = True

serve(app, host='0.0.0.0', port=8080) #WAITRESS!
</code>```

html code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
    <script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
    <script type=text/javascript>
            (function() {
                ('a#test').on('click', function(e) {
                    e.preventDefault()
                    $.getJSON('/background_process_test', function(data) {
                    //do nothing
                    })
                    return false;
                })
            })
    </script>
</head>

<body>
    <div class='container'>
        <h3>Test</h3>
            <form>
                <a href=# id=test><button class='btn btn-default'>Test</button></a>
            </form>

    </div>
</body>
</html>
</code>```

Update:
Network tab

答:
There is a typo in the following code:

```<code>('a#test').on('click', function(e) {
  ...
})
</code>```

Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:

```<code>$('a#test').on('click', function(e) {
  ...
})
</code>```

Body:
I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.

I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.

python code:

from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve

app = Flask(__name__)

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

if __name__ == "__main__":
    app.debug = True

serve(app, host='0.0.0.0', port=8080) #WAITRESS!

html code:

<!DOCTYPE html>

Test

            <form>
                <button class='btn btn-default'>Test</button>
            </form>

Update:
Network tab

Body:
There is a typo in the following code:

('a#test').on('click', function(e) {
  ...
})

Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:

$('a#test').on('click', function(e) {
  ...
})


问:
when would I use create-react-app and when would I use Webpack
Which is top performance giver and Is there any specific advantage of webpack over react-scripts build?</p>

答:
To start with, CRA (create-react-app) uses Webpack under the hood. What it does is it provides ready-to-use configuration supporting tree-shaking, code splitting, static resource importing (ie. JSON files or images). It also includes several additional testing/code quality tools like jest and eslint. Those are also preconfigured and ready to be used.

On the other hand, when you decide to use Webpack directly you must prepare this configuration by hand and, what's worse, maintain it to preserve compatibility with newer versions of React and other libraries. It may seem easy, but it's not. There are multiple factors, which must be taken into consideration.

Now, in terms of performance, as we all know Webpack isn't blazing fast. There are alternatives available, but many of them aren't production ready yet. To mention few: SWC (spack), ESBuild, Vite, Snowpack. However, if you have access to Webpack's configuration you may replace babel-loader with swc-loader or similar and gain some performance. See this article for details.

Let's say you use CRA - does it mean there is no way to modify Webpack's configuration? Fortunately, there is! One can use craco and apply desired modifications through it.

To sum up:

CRA - preconfigured, production-ready Webpack, jest, eslint etc.

Webpack - must be configured by hand and maintained to stay compatible with newer React versions. No additional toolset included (jest, eslint).