问:
Selecting from four tables and grouping some results into one column
sports_games Table

```<code>==========================================================================
| game_id | team_id | game_type | time_started | time_ended | planned_by |
|========================================================================|
|   1     |    1    |     1     | 1640799417   | 1641146196 |     1      |
|   2     |    2    |     1     | 1640971535   | 1641579516 |     1      |
|   3     |    1    |     2     | 1640971553   | 1641582723 |     8      |
|   4     |    2    |     2     | 1640971585   | 1641404242 |     9      |
|   5     |    3    |     4     | 1641061431   | 1641754479 |     12     |
==========================================================================
</code>```

I have been able to combine the above table, with the below table;

game_types Table

```<code>==============================
| game_type | game_type_name |
|============================|
|     1     |   football     |
|     2     |   baseball     |
|     3     |     golf       |
|     4     |    tennis      |
==============================
</code>```

With the following SQL

```<code>SELECT *
    FROM sport_games
    INNER JOIN game_types
    ON sport_games.game_type = game_types.game_type
</code>```

However, I am now finding myself going round and around, attempting potential solution after the other. I need to include data from two more tables, participents and user_basic.

The participents table simply has the game_id and user_id columns, one row per participant, both combined to be the primary key, and within user_basic table, you can find user_id along with their user_name.

For the planned_by column in the firt table, this is also a user_id which I want to obtain their username too.

With all the participants, I would like them to be within one column grouped by their game.

Things That I've Tried

group_concat( .. ), perhaps I was using this completely wrong, I could only achieve this grouping the entire results set from the other table and could not seem to figure out how to use this in a join correctly.

STRING_AGG( ... ) Initially this lead down a path of turning out that I could not use this as I was running on 5.5 MariaDB, which lead down struggling path for me to update. Now I'm using MariaDB 10.3, however I still cannot seem to get the simplest function to work for this, despite going through several Stack Overflows and whatnot.

I feel like I'm at a bit of a loss, any progress I seem to make forward, I am taking two steps back! And then there is using the JOIN amongst these, I'm not sure if I am wording my searches right to place me on the right path, so my question title might be a bit ambiguous right now, sorry if this is the case! - Please suggest otherwise, thank you.

Example Desired Outcome

```<code>"2": { // <- game_id
        "game_type": 2,
        "game_type_name": "baseball",
        "participants": {
            "1": "username_1",
            "2": "username_21",
            "3": "username_3",
            "4": "username_4",
        },
        "time_started": 1641061431,
        "time_completed": 1641754479,
        "planned_by": {
            "851730": "username_1",
        }
}
</code>```

答:
You must join properly the tables and the table user_basic twice: to get the participants and the user who planned the game.

For MariaDB 10.5+ you can use JSON_ARRAYAGG():

```<code>SELECT sg.game_id,
       sg.game_type,
       gt.game_type_name,
       JSON_ARRAYAGG(JSON_OBJECT(ub.user_id, ub.user_name)) participants,
       sg.time_started,
       sg.time_ended,
       JSON_OBJECT(sg.planned_by, pb.user_name) planned_by
FROM sports_games sg
INNER JOIN user_basic pb ON pb.user_id = sg.planned_by
INNER JOIN game_types gt ON gt.game_type = sg.game_type
INNER JOIN participents p ON p.game_id = sg.game_id
INNER JOIN user_basic ub ON ub.user_id = p.user_id
GROUP BY sg.game_id;
</code>```

For previous versions use GROUP_CONCAT():

```<code>SELECT sg.game_id,
       sg.game_type,
       gt.game_type_name,
       CONCAT('{', GROUP_CONCAT(ub.user_id, ' : ', ub.user_name SEPARATOR ', '), '}') participants,
       sg.time_started,
       sg.time_ended,
       CONCAT('{', GROUP_CONCAT(DISTINCT sg.planned_by, ' : ', pb.user_name), '}') planned_by
FROM sports_games sg
INNER JOIN user_basic pb ON pb.user_id = sg.planned_by
INNER JOIN game_types gt ON gt.game_type = sg.game_type
INNER JOIN participents p ON p.game_id = sg.game_id
INNER JOIN user_basic ub ON ub.user_id = p.user_id
GROUP BY sg.game_id;
</code>```

See the demo.

Body:
sports_games Table

==========================================================================
| game_id | team_id | game_type | time_started | time_ended | planned_by |
|========================================================================|
|   1     |    1    |     1     | 1640799417   | 1641146196 |     1      |
|   2     |    2    |     1     | 1640971535   | 1641579516 |     1      |
|   3     |    1    |     2     | 1640971553   | 1641582723 |     8      |
|   4     |    2    |     2     | 1640971585   | 1641404242 |     9      |
|   5     |    3    |     4     | 1641061431   | 1641754479 |     12     |
==========================================================================

I have been able to combine the above table, with the below table;

game_types Table

==============================
| game_type | game_type_name |
|============================|
|     1     |   football     |
|     2     |   baseball     |
|     3     |     golf       |
|     4     |    tennis      |
==============================

With the following SQL

SELECT *
    FROM sport_games
    INNER JOIN game_types
    ON sport_games.game_type = game_types.game_type

However, I am now finding myself going round and around, attempting potential solution after the other. I need to include data from two more tables, participents and user_basic.

The participents table simply has the game_id and user_id columns, one row per participant, both combined to be the primary key, and within user_basic table, you can find user_id along with their user_name.

For the planned_by column in the firt table, this is also a user_id which I want to obtain their username too.

With all the participants, I would like them to be within one column grouped by their game.

Things That I've Tried

group_concat( .. ), perhaps I was using this completely wrong, I could only achieve this grouping the entire results set from the other table and could not seem to figure out how to use this in a join correctly.

STRING_AGG( ... ) Initially this lead down a path of turning out that I could not use this as I was running on 5.5 MariaDB, which lead down struggling path for me to update. Now I'm using MariaDB 10.3, however I still cannot seem to get the simplest function to work for this, despite going through several Stack Overflows and whatnot.

I feel like I'm at a bit of a loss, any progress I seem to make forward, I am taking two steps back! And then there is using the JOIN amongst these, I'm not sure if I am wording my searches right to place me on the right path, so my question title might be a bit ambiguous right now, sorry if this is the case! - Please suggest otherwise, thank you.

Example Desired Outcome

"2": { // <- game_id
        "game_type": 2,
        "game_type_name": "baseball",
        "participants": {
            "1": "username_1",
            "2": "username_21",
            "3": "username_3",
            "4": "username_4",
        },
        "time_started": 1641061431,
        "time_completed": 1641754479,
        "planned_by": {
            "851730": "username_1",
        }
}

Body:
You must join properly the tables and the table user_basic twice: to get the participants and the user who planned the game.

For MariaDB 10.5+ you can use JSON_ARRAYAGG():

SELECT sg.game_id,
       sg.game_type,
       gt.game_type_name,
       JSON_ARRAYAGG(JSON_OBJECT(ub.user_id, ub.user_name)) participants,
       sg.time_started,
       sg.time_ended,
       JSON_OBJECT(sg.planned_by, pb.user_name) planned_by
FROM sports_games sg
INNER JOIN user_basic pb ON pb.user_id = sg.planned_by
INNER JOIN game_types gt ON gt.game_type = sg.game_type
INNER JOIN participents p ON p.game_id = sg.game_id
INNER JOIN user_basic ub ON ub.user_id = p.user_id
GROUP BY sg.game_id;

For previous versions use GROUP_CONCAT():

SELECT sg.game_id,
       sg.game_type,
       gt.game_type_name,
       CONCAT('{', GROUP_CONCAT(ub.user_id, ' : ', ub.user_name SEPARATOR ', '), '}') participants,
       sg.time_started,
       sg.time_ended,
       CONCAT('{', GROUP_CONCAT(DISTINCT sg.planned_by, ' : ', pb.user_name), '}') planned_by
FROM sports_games sg
INNER JOIN user_basic pb ON pb.user_id = sg.planned_by
INNER JOIN game_types gt ON gt.game_type = sg.game_type
INNER JOIN participents p ON p.game_id = sg.game_id
INNER JOIN user_basic ub ON ub.user_id = p.user_id
GROUP BY sg.game_id;

See the demo.


来源: stackexchange

问:
Can I return value from action creator using redux-thunk?
I've seen a lot of examples of async action creators, but they all do some sort of fetching and pushing data to redux store and return nothing. I need another logic that looks something like:

```<code>const createUserAction = (user) => {
  firestore().collection('users').add(user)
  .then(result => {
     dispatch({type: 'SET_USER', payload: {...user, id: result.id}})
  })
}

</code>```

I need to return result.id from createUserAction to navigate to page that displays user by his id. In my imagine it should work like

```<code>createUserAction({name: John}).then(id => navigation.navigate('UserDetailPage', {userId: id}))
</code>```

I don't know how to implement that and I'll be glad if somebody can help

答:
Returning values from action creators is a No-Go. The solution for this scenario that I've used and think is better is to do the redirect in the async action itself:</p>
```<code>// afterCreation = callback function with one argument, the created user
const createUserAction = async (user, afterCreation) => {
  const createdUser = await firestore().collection('users').add(user);
  dispatch({type: 'SET_USER', payload: {...user, id: createdUser.id}});
  afterCreation(createdUser);
};

createUserAction(
  {name: John},
  // Pass callback to action creator
  (user) => navigation.navigate('UserDetailPage', {userId: user.id})
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've seen a lot of examples of async action creators, but they all do some sort of fetching and pushing data to redux store and return nothing. I need another logic that looks something like:

const createUserAction = (user) => {
  firestore().collection('users').add(user)
  .then(result => {
     dispatch({type: 'SET_USER', payload: {...user, id: result.id}})
  })
}

I need to return result.id from createUserAction to navigate to page that displays user by his id. In my imagine it should work like

createUserAction({name: John}).then(id => navigation.navigate('UserDetailPage', {userId: id}))

I don't know how to implement that and I'll be glad if somebody can help

Body:
Returning values from action creators is a No-Go. The solution for this scenario that I've used and think is better is to do the redirect in the async action itself:

// afterCreation = callback function with one argument, the created user
const createUserAction = async (user, afterCreation) => {
  const createdUser = await firestore().collection('users').add(user);
  dispatch({type: 'SET_USER', payload: {...user, id: createdUser.id}});
  afterCreation(createdUser);
};

createUserAction(
  {name: John},
  // Pass callback to action creator
  (user) => navigation.navigate('UserDetailPage', {userId: user.id})
);


问:
How to get current route name in react-navigation?
I want the name of the current route or screen in react-navigation which I want to use inside if condition to make some changes.</p>

答:
If you are using reach navigation version 6 you can retrieve screen name by</p>
```<code>props.route.name
</code>```

Body:
If you are using reach navigation version 6 you can retrieve screen name by

props.route.name


问:
Is OO design's strength in semantics or encapsulation?
Object-oriented design (OOD) combines data and its methods. This, as far as I can see, achieves two great things: it provides encapsulation (so I don't care what data there is, only how I get values I want) and semantics (it relates the data together with names, and its methods consistently use the data as originally intended).

So where does OOD's strength lie? In constrast, functional programming attributes the richness to the verbs rather than the nouns, and so both encapsulation and semantics are provided by the methods rather than the data structures.

I work with a system that is on the functional end of the spectrum, and continually long for the semantics and encapsulation of OO. But I can see that OO's encapsulation can be a barrier to flexible extension of an object. So at the moment, I can see the semantics as a greater strength.

Or is encapsulation the key to all worthwhile code?

Edit: I mean specifically the type of encapsulation OO provides here. changeColor(door,blue) becomes door.changeColor(blue).

答:
Let's take a step back and look at this from a higher level. The advantages of any language feature lie in the ability to succinctly express the problem/solution in a more natural way with respect to the problem domain.

The mechanics of OOP are easily implemented in plain C with structs and function pointers. You can even get a bit of OOP feel doing it that way. However, OOP idioms are not nearly as forthcoming in such an environment. When there's actual language support for OOP then the expressiveness of the paradigm comes out, and the way a language implements an idea has a very real impact on what is "said" and how. For example, see differences in code using closures/lambdas in lisp, python, ruby, etc.

So in the end it's not about the components and underlying concepts, but rather how they're put together and used that make OO in C++ what it is.

OwnerDisplayName: Phil H

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brian

OwnerDisplayName: dwc


问:
Calling an excel macro from the ribbon
Intro:
I have written some short excel macros (tested, they work fine) and want to link them to a button in the Ribbon (Excel 2010). I had already done it successfully in Excel 2007.
I am using Custom UI Editor to build a new ribbon, which also works fine. Everything is packaged in a .xlam add-in and added to Excel. The ribbon shows up nicely, all other buttons works, but ...

Problem:
when I hit the button that is linked to the macro I get the error: "wrong number of parameters or property assignment not valid" (message translated from Italian, might not be exactly the same in English)

Troubleshooting info:
The macros do not have parameters. The same macros can be successfully called and executed manually. I am even able to add the same macros to the Quick Access Toolbar.

Here is the specific portion of the ribbon script:

```<code><group id="DupNumber" label="Number" insertBeforeMso="GroupNumber" >
    <comboBox idMso="NumberFormatGallery"/>
    <box id="HN1" boxStyle="horizontal">
        <buttonGroup id="HNButtonGroup1">
            <button id="Euro" onAction="Roberto.xlam!EURZ" imageMso="F" supertip="text ..."/>
            <button id="EuroNZ" onAction="Roberto.xlam!EURNZ" imageMso="E" supertip="text ..."/>
            <button idMso="PercentStyle"/>
            <button id="Comma" onAction="Roberto.xlam!NewCommaFormat" imageMso="C" supertip="test ..."/>
            <button idMso="PercentStyle"/>
        </buttonGroup>
    </box>
</code>```

and here are the macros:

```<code>Sub EURZ()
    Application.ActiveCell.NumberFormat = "€ #,##0.00"
End Sub
Sub EURNZ()
    Application.ActiveCell.NumberFormat = "€ #,##0"
End Sub
Sub NewCommaFormat()
    Application.ActiveCell.NumberFormat = "#,##0"
End Sub
</code>```

Can you help me?
Thanks
Roberto

答:
I believe you need to add this param to your macro: control As IRibbonControl

So it should look like this:

```<code>Sub EURZ(control As IRibbonControl)
    Application.ActiveCell.NumberFormat = "€ #,##0.00"
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Calling an excel macro from the ribbon

Body:
Intro:
I have written some short excel macros (tested, they work fine) and want to link them to a button in the Ribbon (Excel 2010). I had already done it successfully in Excel 2007.
I am using Custom UI Editor to build a new ribbon, which also works fine. Everything is packaged in a .xlam add-in and added to Excel. The ribbon shows up nicely, all other buttons works, but ...

Problem:
when I hit the button that is linked to the macro I get the error: "wrong number of parameters or property assignment not valid" (message translated from Italian, might not be exactly the same in English)

Troubleshooting info:
The macros do not have parameters. The same macros can be successfully called and executed manually. I am even able to add the same macros to the Quick Access Toolbar.

Here is the specific portion of the ribbon script:

<group id="DupNumber" label="Number" insertBeforeMso="GroupNumber" >
    <comboBox idMso="NumberFormatGallery"/>
    <box id="HN1" boxStyle="horizontal">
        <buttonGroup id="HNButtonGroup1">
            <button id="Euro" onAction="Roberto.xlam!EURZ" imageMso="F" supertip="text ..."/>
            <button id="EuroNZ" onAction="Roberto.xlam!EURNZ" imageMso="E" supertip="text ..."/>
            <button idMso="PercentStyle"/>
            <button id="Comma" onAction="Roberto.xlam!NewCommaFormat" imageMso="C" supertip="test ..."/>
            <button idMso="PercentStyle"/>
        </buttonGroup>
    </box>

and here are the macros:

Sub EURZ()
    Application.ActiveCell.NumberFormat = "€ #,##0.00"
End Sub
Sub EURNZ()
    Application.ActiveCell.NumberFormat = "€ #,##0"
End Sub
Sub NewCommaFormat()
    Application.ActiveCell.NumberFormat = "#,##0"
End Sub

Can you help me?
Thanks
Roberto

Body:
I believe you need to add this param to your macro: control As IRibbonControl

So it should look like this:

Sub EURZ(control As IRibbonControl)
    Application.ActiveCell.NumberFormat = "€ #,##0.00"
End Sub


问:
Show JSON data objects in React Native
I'm working on a little project which related to connecting API's on React Native. In that, I got a JSON data object like this.

```<code>{
  success: 1,
  data: {
    monthly_income: {
      0: {
        en: 'Below Ten Thousand',
        expect_en: 'Neglected',
      },
      10000: {
        en: 'Above Ten Thousand',
      },
      25000: {
        en: 'Above Twenty Thousand',
      },
      50000: {
        en: 'Above Fifty Thousand',
      },
      75000: {
        en: 'Above Seventy Five Thousand',
      },
      100000: {
        en: 'Above Hundred Thousand',
      },
    },
    height: {
      5: {
        en: '5 Feet',
      },
      5.1: {
        en: '5 Feet and 1 Inches',
      },
      5.2: {
        en: '5 Feet and 2 Inches',
      },
      5.3: {
        en: '5 Feet and 3 Inches',
      },
      5.4: {
        en: '5 Feet and 4 Inches',
      },
      5.5: {
        en: '5 Feet and 5 Inches',
      },
      5.6: {
        en: '5 Feet and 6 Inches',
      },
      5.7: {
        en: '5 Feet and 7 Inches',
      },
      5.8: {
        en: '5 Feet and 8 Inches',
      },
      5.9: {
        en: '5 Feet and 9 Inches',
      },
      '5.10': {
        en: '5 Feet and 10 Inches',
      },
      5.11: {
        en: '5 Feet and 11 Inches',
      },
      6: {
        en: '6 Feet',
      },
    },
  },
};
</code>```

I wanted to display above data in a React Native picker in separately, like a Monthly Income in one picker & Height in another picker. I tried using map method to do that, but I couldn't  access to the data inside this. My questions are,

Can we use map method to access these kinds of JSON objects?

If we can, what is the best way to do that?

If can't, please suggest the way to do that work

答:
As Fernando suggests, transform object to array.

I build full working example for further details.

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Picker } from "@react-native-picker/picker";

// You can import from local files
import AssetExample from "./components/AssetExample";

// or any pure javascript modules available in npm
import { Card } from "react-native-paper";
import response from "./response";

const getMonthlyIncomes = (response) => {
  let monthlyIncomes = response.data.monthly_income;

  const keys = Object.keys(monthlyIncomes);

  return keys.map((key) => {
    let incomeData = monthlyIncomes[key];

    return { value: key, ...incomeData };
  });
};

const getHeights = (response) => {
  let heights = response.data.height;

  const keys = Object.keys(heights);

  return keys.map((key) => {
    let heightData = heights[key];

    return { value: key, ...heightData };
  });
};

const monthlyIncomes = getMonthlyIncomes(response);
const heights = getHeights(response);

export default function App() {
  return (
    <View style={styles.container}>
      <Card>
        <View style={{ padding: 20 }}>
          <Text style={styles.paragraph}>Monthly Income</Text>
          <Picker>
            {monthlyIncomes.map((income) => {
              return (
                <Picker.Item
                  key={income.value}
                  label={income.en}
                  value={income.value}
                />
              );
            })}
          </Picker>
        </View>
      </Card>

      {/** Heights */}

      <Card style={{ marginTop: 20 }}>
        <View style={{ padding: 20 }}>
          <Text style={styles.paragraph}>Heights</Text>
          <Picker>
            {heights.map((height) => {
              return (
                <Picker.Item
                  key={height.value}
                  label={height.en}
                  value={height.value}
                />
              );
            })}
          </Picker>
        </View>
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
  },
});
```

Expo Snack - https://snack.expo.dev/@emmbyiringiro/9b1520

Title: Show JSON data objects in React Native

Body:
I'm working on a little project which related to connecting API's on React Native. In that, I got a JSON data object like this.

{
  success: 1,
  data: {
    monthly_income: {
      0: {
        en: 'Below Ten Thousand',
        expect_en: 'Neglected',
      },
      10000: {
        en: 'Above Ten Thousand',
      },
      25000: {
        en: 'Above Twenty Thousand',
      },
      50000: {
        en: 'Above Fifty Thousand',
      },
      75000: {
        en: 'Above Seventy Five Thousand',
      },
      100000: {
        en: 'Above Hundred Thousand',
      },
    },
    height: {
      5: {
        en: '5 Feet',
      },
      5.1: {
        en: '5 Feet and 1 Inches',
      },
      5.2: {
        en: '5 Feet and 2 Inches',
      },
      5.3: {
        en: '5 Feet and 3 Inches',
      },
      5.4: {
        en: '5 Feet and 4 Inches',
      },
      5.5: {
        en: '5 Feet and 5 Inches',
      },
      5.6: {
        en: '5 Feet and 6 Inches',
      },
      5.7: {
        en: '5 Feet and 7 Inches',
      },
      5.8: {
        en: '5 Feet and 8 Inches',
      },
      5.9: {
        en: '5 Feet and 9 Inches',
      },
      '5.10': {
        en: '5 Feet and 10 Inches',
      },
      5.11: {
        en: '5 Feet and 11 Inches',
      },
      6: {
        en: '6 Feet',
      },
    },
  },
};

I wanted to display above data in a React Native picker in separately, like a Monthly Income in one picker & Height in another picker. I tried using map method to do that, but I couldn't  access to the data inside this. My questions are,

Can we use map method to access these kinds of JSON objects?

If we can, what is the best way to do that?

If can't, please suggest the way to do that work

Body:
As Fernando suggests, transform object to array.

I build full working example for further details.

import * as React from "react";
import { Text, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
import { Picker } from "@react-native-picker/picker";

// You can import from local files
import AssetExample from "./components/AssetExample";

// or any pure javascript modules available in npm
import { Card } from "react-native-paper";
import response from "./response";

const getMonthlyIncomes = (response) => {
  let monthlyIncomes = response.data.monthly_income;

  const keys = Object.keys(monthlyIncomes);

  return keys.map((key) => {
    let incomeData = monthlyIncomes[key];

    return { value: key, ...incomeData };
  });
};

const getHeights = (response) => {
  let heights = response.data.height;

  const keys = Object.keys(heights);

  return keys.map((key) => {
    let heightData = heights[key];

    return { value: key, ...heightData };
  });
};

const monthlyIncomes = getMonthlyIncomes(response);
const heights = getHeights(response);

export default function App() {
  return (
    <View style={styles.container}>
      <Card>
        <View style={{ padding: 20 }}>
          <Text style={styles.paragraph}>Monthly Income</Text>
          <Picker>
            {monthlyIncomes.map((income) => {
              return (
                <Picker.Item
                  key={income.value}
                  label={income.en}
                  value={income.value}
                />
              );
            })}
          </Picker>
        </View>
      </Card>

      {/** Heights */}

      <Card style={{ marginTop: 20 }}>
        <View style={{ padding: 20 }}>
          <Text style={styles.paragraph}>Heights</Text>
          <Picker>
            {heights.map((height) => {
              return (
                <Picker.Item
                  key={height.value}
                  label={height.en}
                  value={height.value}
                />
              );
            })}
          </Picker>
        </View>
      </Card>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    paddingTop: Constants.statusBarHeight,
    backgroundColor: "#ecf0f1",
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center",
  },
});

Expo Snack - https://snack.expo.dev/@emmbyiringiro/9b1520


问:
Getting error on closing excel macro using vbscript
```<code>Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.application.quit ' <--- error here

Set ObjWB = Nothing

Set ObjExcel = Nothing
</code>```

Getting error on the BOLD Part
Can anyone please suggest. tried everything to fix this.

答:
```<code>Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.DisplayAlerts = False

ObjWB.Close = False

ObjExcel.quit

Set ObjWB = Nothing

Set ObjExcel = Nothing
</code>```

It worked like this, I just passed ObjExcel.DisplayAlerts = False

it won't display any alerts and it will simply close the excel without saving it.

i hope this is right.

Body:
Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.application.quit ' <--- error here

Set ObjWB = Nothing

Set ObjExcel = Nothing

Getting error on the BOLD Part
Can anyone please suggest. tried everything to fix this.

Body:
Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.DisplayAlerts = False

ObjWB.Close = False

ObjExcel.quit

Set ObjWB = Nothing

Set ObjExcel = Nothing

It worked like this, I just passed ObjExcel.DisplayAlerts = False

it won't display any alerts and it will simply close the excel without saving it.

i hope this is right.


答:
I think there are two answers here. One is the solution to the question you asked, which is that you can prevent clashes using guide_axis(n.dodge = 2)

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  ) +
  guides(x = guide_axis(n.dodge = 2))
```
<p><img src="https://i.stack.imgur.com/lGneg.png" alt="enter image description here" /></p>
<p>But I think a better answer is that you should rename the levels you are plotting. This will make a plot that is easier for the viewer to parse and understand.</p>
<pre class="lang-r prettyprint-override"><code>datadim.lng$vizit <- gsub("X\\.Hemoglobin\\.\\.g\\.(l|L)", "Hb (g/l)",
                          datadim.lng$vizit)
datadim.lng$vizit <- gsub("\\.{3}", "\n", datadim.lng$vizit)
datadim.lng$vizit <- gsub("\\.", " ", datadim.lng$vizit)
datadim.lng$vizit <- gsub(" D", ", D", datadim.lng$vizit)
datadim.lng$vizit <- factor(datadim.lng$vizit,
                            levels(factor(datadim.lng$vizit))[c(6, 1:5)])

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  ) +
  theme(axis.text = element_text(size = 10, face = 2))
</code>```

Title: lack of space between signatures on the plot and wrong column order on the plot in R

Body:
I need create plot using ggplot2

Here my code with reproducible example

library(tidyverse)
    gemoglabin=structure(list(Therapy.group = c(1L, 2L, 1L, 2L, 1L, 2L, 2L,
2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L),
    X.Hemoglobin..g.l...WWScreening = c(139L, 168L, 152L, 122L,
    142L, 150L, 120L, 157L, 136L, 128L, 157L, 154L, 142L, 124L,
    138L, 138L, 151L, 148L, 148L, 142L, 149L, 157L, 137L, 135L,
    121L, 148L, 121L, 159L, 133L, 132L, 155L, 133L, 136L, 121L,
    140L, 142L, 137L, 147L), X.Hemoglobin..g.L...Visit.1.Day.2 = c(166L,
    141L, 144L, 121L, 141L, 145L, 121L, 158L, 135L, 121L, 158L,
    152L, 144L, 128L, 129L, 146L, 142L, 141L, 139L, 139L, 140L,
    159L, 143L, 132L, 134L, 149L, 123L, 163L, 145L, 141L, 145L,
    142L, 146L, 121L, 143L, 139L, 145L, 149L), X.Hemoglobin..g.L...Visit.2.Day.9 = c(140L,
    155L, 142L, 122L, 138L, 143L, 126L, 151L, 129L, 124L, 155L,
    140L, 140L, 122L, 132L, 136L, 135L, 140L, 141L, 142L, 136L,
    145L, 138L, 126L, 128L, 144L, 120L, 160L, 143L, 133L, 141L,
    142L, 147L, 121L, 138L, 139L, 142L, 152L), X.Hemoglobin..g.L...Visit.3.Day.16 = c(150L,
    157L, 153L, 117L, 140L, 143L, 122L, 155L, 125L, 121L, 156L,
    144L, 137L, 122L, 136L, 136L, 140L, 140L, 143L, 143L, 140L,
    143L, 141L, 123L, 129L, 150L, 121L, 163L, 149L, 143L, 136L,
    136L, 143L, 123L, 147L, 137L, 139L, 152L), X.Hemoglobin..g.L...Visit.4.Day.23 = c(140L,
    150L, 144L, 122L, 139L, 140L, 124L, 149L, 121L, 125L, 148L,
    141L, 132L, 126L, 133L, 136L, 137L, 141L, 141L, 137L, 141L,
    145L, 140L, 120L, 124L, 143L, 122L, 163L, 139L, 132L, 141L,
    141L, 138L, 121L, 134L, 134L, 137L, 148L), X.Hemoglobin..g.L...Visit.5.Day.29 = c(132L,
    165L, 141L, 122L, 143L, 140L, 131L, 153L, 123L, 121L, 150L,
    150L, 139L, 132L, 132L, 139L, 136L, 134L, 145L, 137L, 144L,
    147L, 134L, 124L, 128L, 148L, 121L, 167L, 142L, 127L, 140L,
    141L, 144L, 126L, 132L, 134L, 136L, 148L)), class = "data.frame", row.names = c(NA,
-38L))

datadim.lng <- gemoglabin %>% pivot_longer(-Therapy.group,names_to="vizit", values_to = "gem")

datadim.lng$Therapy.group <- as.factor(datadim.lng$Therapy.group)

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  )

as the result i get such screen

as we can see here the signatures on the vizit axis are mixed up and i can’t really see which vizit number.

How to make the signatures not mixed and visible? I must have space between visits in plot

only not in such small print otherwise it is hard to see.

Another problem is wrong order of signatures. WWscreening as we can see the first column in dataset ,but in the plot it is last in order

Can you please help me fix  space between signatures and correct order of column in the plot.
Thank you

Body:
I think there are two answers here. One is the solution to the question you asked, which is that you can prevent clashes using guide_axis(n.dodge = 2)

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  ) +
  guides(x = guide_axis(n.dodge = 2))

But I think a better answer is that you should rename the levels you are plotting. This will make a plot that is easier for the viewer to parse and understand.

datadim.lng$vizit <- gsub("X\\.Hemoglobin\\.\\.g\\.(l|L)", "Hb (g/l)",
                          datadim.lng$vizit)
datadim.lng$vizit <- gsub("\\.{3}", "\n", datadim.lng$vizit)
datadim.lng$vizit <- gsub("\\.", " ", datadim.lng$vizit)
datadim.lng$vizit <- gsub(" D", ", D", datadim.lng$vizit)
datadim.lng$vizit <- factor(datadim.lng$vizit,
                            levels(factor(datadim.lng$vizit))[c(6, 1:5)])

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  ) +
  theme(axis.text = element_text(size = 10, face = 2))


问:
How do I represent dates without the timezone using Apache CXF?
I have a WSDL that specifies an element's type to be xs:date.

When I use Apache CXF to generate the Java classes, it renders the variable as an javax.xml.datatype.XMLGregorianCalendar (all good so far).

When CXF renders an XML document containing this, it renders it in this form (where -06:00 represents the time zone):

2000-01-18-06:00

How can I configure CXF not to render the timezone?

答:
```<code>GregorianCalendar gcal = new GregorianCalendar();
start = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
start.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
</code>```

Don't ask me why in every bit of the sane logic - when marshalling the XMLgregorianCalendar to xs:date it retains the time zone.

I always thought - the time zone could be more applicable to xs:dateTime, but what I know ... about types.

For me, it doesn't make sense to have the time zone by default, for a xs:date type and this is a problem in the marshalling logic.

Body:
GregorianCalendar gcal = new GregorianCalendar();
start = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
start.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

Don't ask me why in every bit of the sane logic - when marshalling the XMLgregorianCalendar to xs:date it retains the time zone.

I always thought - the time zone could be more applicable to xs:dateTime, but what I know ... about types.

For me, it doesn't make sense to have the time zone by default, for a xs:date type and this is a problem in the marshalling logic.


问:
how to find the length of each element in a list python? then i need to calculate how many of them have more than 5 words
```<code>def counts(lst):
    count = 0
    for elem in lst:
        if len(elem) > 5:
            count += 1
    return count

lst = []
num = int(input("How Many Elements You Need To Add: "))
for i in range(num):
    ele = input()
    lst.append(ele)

print(counts(lst))
</code>```

答:
```<code>x, y = {i: len(i) for i in my_list}, len([i for i in my_list if len(i) > 5])
print('x: ', x)
print('y: ', y)
</code>```

Output:

```<code>x:  {'Tfjklfq': 7, 'dfdf': 4, 'd': 1, 'fdkmqdjfksd': 11}
y:  2
</code>```

Body:
x, y = {i: len(i) for i in my_list}, len([i for i in my_list if len(i) > 5])
print('x: ', x)
print('y: ', y)

Output:

x:  {'Tfjklfq': 7, 'dfdf': 4, 'd': 1, 'fdkmqdjfksd': 11}
y:  2


问:
Cannot find module 'file-name.png' or its corresponding type declarations - typescript react
i'm trying to import a png in my typescript react project like so:

import logo from 'assets/Logo.svg';

I'm getting this TS error though:

Cannot find module 'assets/Logo.svg' or its corresponding type declarations.ts(2307)

Any idea why this is? I have attached my tsconfig.json file below in case I have configured something incorrectly:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": ["src"]
}
```

答:
There should be a react-app-env.d.ts file in your src folder.

If you don't see it, Create a new file in src folder named react-app-env.d.ts.

Now, just add the code below in your react-app-env.d.ts file.

```<code>declare module "*.png";
declare module "*.svg";
declare module "*.jpeg";
declare module "*.jpg";
</code>```

and you are good to go :)

Body:
There should be a react-app-env.d.ts file in your src folder.

If you don't see it, Create a new file in src folder named react-app-env.d.ts.

Now, just add the code below in your react-app-env.d.ts file.

declare module "*.png";
declare module "*.svg";
declare module "*.jpeg";
declare module "*.jpg";

and you are good to go :)


问:
Flutter Api Data fetching Error with typeCast and asynchronous suspension
I'm trying to fetch the API Data , and it's just returned Circular Progress Indicator when I'm checking my response body from the client Im receiving my required but was unable to display it. Kindly guide me through it where Im going wrong.
My Data from API looks like this
I just want to access id and distance

```<code>[
  {
    "id": 1,
    "messageId": null,
    "distance": "39",
    "partitionId": "1",
    "eventProcessedUtcTime": "2022-02-08T10:48:12.81",
    "eventEnqueuedUtcTime": "2022-02-08T10:47:38.21",
    "ioThub": "{\"MessageId\":null,\"CorrelationId\":null,\"ConnectionDeviceId\":\"iotwmcs-esp32\",\"ConnectionDeviceGenerationId\":\"637798347400200573\",\"EnqueuedTime\":\"2022-02-08T10:47:38.2060000Z\"}"
  }
]
</code>```

This is my  file where I'm fetching data

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/ilmcs_info.dart';
import 'package:http/http.dart' as http;

class UpperLevelTankData extends StatefulWidget {
  const UpperLevelTankData({Key key}) : super(key: key);

  @override
  _UpperLevelTankDataState createState() => _UpperLevelTankDataState();
}

class _UpperLevelTankDataState extends State<UpperLevelTankData> {
  StreamController<IotWmcsModel> _streamController = StreamController();

  @override
  void dispose() {
    _streamController.close();
  }

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 3), (timer) {
      fetchApiData();
    });
  }

  Future<IotWmcsModel> fetchApiData() async {
    var url = Uri.parse(
        'https://iotwmcsapi20220208180616.azurewebsites.net/api/Iotwmcsta004');
    final response = await http.get(url);
    final dataBody = json.decode(response.body).first;
    // print(dataBody);
    IotWmcsModel iotWmcsModel = IotWmcsModel.fromJson(dataBody);
    _streamController.sink.add(iotWmcsModel);

  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<IotWmcsModel>(
      stream: _streamController.stream,
      builder: (context, snapdata) {
        switch (snapdata.connectionState) {
          case ConnectionState.waiting:
            return const CircularProgressIndicator();
          default:
            if (snapdata.hasError) {
              return const Text('Please Wait....');
            } else {
              return buildIotWmcsWidget(snapdata.data);
            }
        }
      },
    );
  }

  Widget buildIotWmcsWidget(IotWmcsModel iotWmcsModel) {
    print("${iotWmcsModel.distance}");
    return Text(
      "${iotWmcsModel.distance}".toString(),
      style: const TextStyle(
          color: Colors.white, fontSize: 25, fontWeight: FontWeight.w900),
    );
  }
}
</code>```

this is  the model of my data

```<code>class IotWmcsModel {
  final int distance;
  final int id;

  IotWmcsModel({this.distance, this.id});

  factory IotWmcsModel.fromJson(Map<String, dynamic> json) {
    return IotWmcsModel(
        distance: json['distance'] as int, id: json['id'] as int);
  }
  Map<String, dynamic> toJson() => {
        'distance': distance,
        'id': id,
      };
}
</code>```

答:
```<code>Future<List<IotWmcsModel>> fetchApiData() async {
    var url = Uri.parse(
        'https://iotwmcsapi20220208180616.azurewebsites.net/api/Iotwmcsta004');
    final response = await http.get(url);
    List<IotWmcsModel> iotWmcsModel = (response.body as List).map((e) => IotWmcsModel.fromJson(x));

  }
</code>```

coz your api return type is List. And you are trying to fetch as a object, I thing that's the problem

Just try to load as a list then it will work.
N.B: my given code would be bracket problem please make sure that you are fetching request as a List

if you can change the api like below type , then your code will be work

```<code>{
    "id": 1,
    "messageId": null,
    "distance": "39",
    "partitionId": "1",
    "eventProcessedUtcTime": "2022-02-08T10:48:12.81",
    "eventEnqueuedUtcTime": "2022-02-08T10:47:38.21",
    "ioThub": "{\"MessageId\":null,\"CorrelationId\":null,\"ConnectionDeviceId\":\"iotwmcs-esp32\",\"ConnectionDeviceGenerationId\":\"637798347400200573\",\"EnqueuedTime\":\"2022-02-08T10:47:38.2060000Z\"}"
  }
</code>```

Body:
I'm trying to fetch the API Data , and it's just returned Circular Progress Indicator when I'm checking my response body from the client Im receiving my required but was unable to display it. Kindly guide me through it where Im going wrong.
My Data from API looks like this
I just want to access id and distance

[
  {
    "id": 1,
    "messageId": null,
    "distance": "39",
    "partitionId": "1",
    "eventProcessedUtcTime": "2022-02-08T10:48:12.81",
    "eventEnqueuedUtcTime": "2022-02-08T10:47:38.21",
    "ioThub": "{\"MessageId\":null,\"CorrelationId\":null,\"ConnectionDeviceId\":\"iotwmcs-esp32\",\"ConnectionDeviceGenerationId\":\"637798347400200573\",\"EnqueuedTime\":\"2022-02-08T10:47:38.2060000Z\"}"
  }
]

This is my  file where I'm fetching data

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/models/ilmcs_info.dart';
import 'package:http/http.dart' as http;

class UpperLevelTankData extends StatefulWidget {
  const UpperLevelTankData({Key key}) : super(key: key);

  @override
  _UpperLevelTankDataState createState() => _UpperLevelTankDataState();
}

class _UpperLevelTankDataState extends State<UpperLevelTankData> {
  StreamController<IotWmcsModel> _streamController = StreamController();

  @override
  void dispose() {
    _streamController.close();
  }

  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(seconds: 3), (timer) {
      fetchApiData();
    });
  }

  Future<IotWmcsModel> fetchApiData() async {
    var url = Uri.parse(
        'https://iotwmcsapi20220208180616.azurewebsites.net/api/Iotwmcsta004');
    final response = await http.get(url);
    final dataBody = json.decode(response.body).first;
    // print(dataBody);
    IotWmcsModel iotWmcsModel = IotWmcsModel.fromJson(dataBody);
    _streamController.sink.add(iotWmcsModel);

  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<IotWmcsModel>(
      stream: _streamController.stream,
      builder: (context, snapdata) {
        switch (snapdata.connectionState) {
          case ConnectionState.waiting:
            return const CircularProgressIndicator();
          default:
            if (snapdata.hasError) {
              return const Text('Please Wait....');
            } else {
              return buildIotWmcsWidget(snapdata.data);
            }
        }
      },
    );
  }

  Widget buildIotWmcsWidget(IotWmcsModel iotWmcsModel) {
    print("${iotWmcsModel.distance}");
    return Text(
      "${iotWmcsModel.distance}".toString(),
      style: const TextStyle(
          color: Colors.white, fontSize: 25, fontWeight: FontWeight.w900),
    );
  }
}

this is  the model of my data

class IotWmcsModel {
  final int distance;
  final int id;

  IotWmcsModel({this.distance, this.id});

  factory IotWmcsModel.fromJson(Map<String, dynamic> json) {
    return IotWmcsModel(
        distance: json['distance'] as int, id: json['id'] as int);
  }
  Map<String, dynamic> toJson() => {
        'distance': distance,
        'id': id,
      };
}

Body:
Future<List<IotWmcsModel>> fetchApiData() async {
    var url = Uri.parse(
        'https://iotwmcsapi20220208180616.azurewebsites.net/api/Iotwmcsta004');
    final response = await http.get(url);
    List<IotWmcsModel> iotWmcsModel = (response.body as List).map((e) => IotWmcsModel.fromJson(x));

  }

coz your api return type is List. And you are trying to fetch as a object, I thing that's the problem

Just try to load as a list then it will work.
N.B: my given code would be bracket problem please make sure that you are fetching request as a List

if you can change the api like below type , then your code will be work

{
    "id": 1,
    "messageId": null,
    "distance": "39",
    "partitionId": "1",
    "eventProcessedUtcTime": "2022-02-08T10:48:12.81",
    "eventEnqueuedUtcTime": "2022-02-08T10:47:38.21",
    "ioThub": "{\"MessageId\":null,\"CorrelationId\":null,\"ConnectionDeviceId\":\"iotwmcs-esp32\",\"ConnectionDeviceGenerationId\":\"637798347400200573\",\"EnqueuedTime\":\"2022-02-08T10:47:38.2060000Z\"}"
  }


问:
While coding a login I want to set a limit to just allow you to try 3 times before resetting it
Disclaimer: Some code is in Spanish, let me know if you need it in English, also I didn't knew how to add the second HTML (plus IDK if it is relevant) please tell me if you need that too so I can change it.

I'm working on an ATM project, and I'm at the login part of it. I have 2 HTML pages, the first is the login and the second is the ATM (Ignore that part because is not finished yet)

Things I want to do:

If it validates the login, it will direct you to the .html page to work on the ATM

If the information is wrong it will give you 2 more tries and after the last one it will tell you that you ran out of tries and will start the count over and redirecting you to the first page. (This is the part where I need help for now)

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount<entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cuerpo{
    display: flex;
    background-color: #dad158;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.boton{
    margin-top: 1rem;
}

h1 {
    text-align: center;
    margin-bottom: 100px;
}

/* Estilos calculadora */
body{
    font-size: 18px;
    font-family: 'Roboto', sans-serif;
    margin: 0;
    padding: 0;
}
#contenedor {
    max-width: 1024px;
    margin: 0 auto;
}
.cajacentro {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 12% auto !important;
    width: 450px;
    height: 100%;
    background-color: #212121;
    padding:3%;
}
section header h5, section header h2, aside h4, aside p{
    color: #ffffff;
    margin: 10px 0;
    text-align: right;
}
.tamañoresultados{
    font-size: 0.6rem;
}
.columna1{
    height: 100%;
    width: 65%;
}
.columna2{
    height: 100%;
    width: 25%;
}
.gridbotones{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
        ". . . ."
        ". . . ."
        ". . . ."
        ". . . .";
}
button{
    background-color: #212121;
    color: #ffffff;
    border: 1px solid #ffffff;
    padding: 10px 0;
    cursor: pointer;
}
button:hover{
    background-color: #424242;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="css/styles.css">

    <title>ATM</title>

ATM

            <input type="" class="form-control" id="user" placeholder="username">
            Usuario

            <input type="password" class="form-control" id="password" placeholder="Password">
            Contraseña

            <button type="submit" class="btn btn-outline-success" onclick="login(location.href='cajero.html')">Ingresar</button>

```

答:
```<code>// Login 1
function login() {
    if (entryCount >= entryLimit) {
        alert('You reached the limit');
        return;
    }

    // login process..
    // if login validated redirect to html
    // window.location.href = "index.html";

    entryCount++;

    if (entryCount < entryLimit) {
        alert('Try again');
    }
}
</code>```

You shouldn't redirect to html page after increasing the count. You must check the limit at the start of login.

Body:
Disclaimer: Some code is in Spanish, let me know if you need it in English, also I didn't knew how to add the second HTML (plus IDK if it is relevant) please tell me if you need that too so I can change it.

I'm working on an ATM project, and I'm at the login part of it. I have 2 HTML pages, the first is the login and the second is the ATM (Ignore that part because is not finished yet)

Things I want to do:

If it validates the login, it will direct you to the .html page to work on the ATM

If the information is wrong it will give you 2 more tries and after the last one it will tell you that you ran out of tries and will start the count over and redirecting you to the first page. (This is the part where I need help for now)

// Variables para limite de intentos
let entryCount = 0
let entryLimit = 3
let error = false

// Variables para cambio de pagina
let mainScreen = document.getElementById('mainScreen')
let contentAccountScreen = document.createTextNode("Account Screen")
let accountScreen = document.createElement("span").setAttribute("id","accountScreen")

// Login 1
function login() {
    let response
    user = document.getElementById('user')
    pass = document.getElementById('password')
    if (user.value === 'Emilio' && pass.value === "abc123"){
        changeMainScreen.replaceChild(contentAccountScreen, mainScreen)
    } if (response != pass && entryCount < entryLimit) {
        entryCount++;
        alert('Contraseña o usuario invalido, intentelo nuevamente')
        window.location.href = "index.html"
    } else(entryCount<entryLimit)
    {
        alert('Pasaste el limite de intentos')
        window.location.href = "index.html"
    }
}

.cuerpo{
    display: flex;
    background-color: #dad158;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

.boton{
    margin-top: 1rem;
}

h1 {
    text-align: center;
    margin-bottom: 100px;
}

/* Estilos calculadora */
body{
    font-size: 18px;
    font-family: 'Roboto', sans-serif;
    margin: 0;
    padding: 0;
}
#contenedor {
    max-width: 1024px;
    margin: 0 auto;
}
.cajacentro {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 12% auto !important;
    width: 450px;
    height: 100%;
    background-color: #212121;
    padding:3%;
}
section header h5, section header h2, aside h4, aside p{
    color: #ffffff;
    margin: 10px 0;
    text-align: right;
}
.tamañoresultados{
    font-size: 0.6rem;
}
.columna1{
    height: 100%;
    width: 65%;
}
.columna2{
    height: 100%;
    width: 25%;
}
.gridbotones{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
    gap: 0px 0px;
    grid-template-areas:
        ". . . ."
        ". . . ."
        ". . . ."
        ". . . .";
}
button{
    background-color: #212121;
    color: #ffffff;
    border: 1px solid #ffffff;
    padding: 10px 0;
    cursor: pointer;
}
button:hover{
    background-color: #424242;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="css/styles.css">

    <title>ATM</title>

ATM

            <input type="" class="form-control" id="user" placeholder="username">
            Usuario

            <input type="password" class="form-control" id="password" placeholder="Password">
            Contraseña

            <button type="submit" class="btn btn-outline-success" onclick="login(location.href='cajero.html')">Ingresar</button>

Body:
// Login 1
function login() {
    if (entryCount >= entryLimit) {
        alert('You reached the limit');
        return;
    }

    // login process..
    // if login validated redirect to html
    // window.location.href = "index.html";

    entryCount++;

    if (entryCount < entryLimit) {
        alert('Try again');
    }
}

You shouldn't redirect to html page after increasing the count. You must check the limit at the start of login.


问:
Payee account is invalid. #PAYEE_ACCOUNT_INVALID
I am trying to implement PayPal Credit card functionality on Laravel for Rest Api. I am receiving the "PAYEE_ACCOUNT_INVALID" error. Any idea what am I doing wrong? Any help would be really appreciated.
I've tried with different test card numbers provided by PayPal via card generator mock.

Thanks.

This is my code snippet.

```<code>public function payment()
    {
        $gateway = Omnipay::create('PayPal_Rest');

        // Initialise the gateway
        $gateway->initialize(array(
            'clientId' => env('PAYPAL_SANDBOX_CLIENT_ID'),
            'secret' => env('PAYPAL_SANDBOX_CLIENT_SECRET'),
            'testMode' => true,
        ));

        #### Direct Credit Card Payment

        // Create a credit card object
        // DO NOT USE THESE CARD VALUES -- substitute your own
        // see the documentation in the class header.
        $card = new CreditCard([
            'firstName' => 'Example',
            'lastName' => 'User',
            'number' => '4111111111111111',
            'expiryMonth' => '01',
            'expiryYear' => '2027',
            'cvv' => '123',
        ]);

        // Do a purchase transaction on the gateway
        try {
            $transaction = $gateway->purchase([
                'amount' => '1.00',
                'currency' => 'AUD',
                'description' => 'This is a test purchase transaction.',
                'card' => $card,
            ]);

            $response = $transaction->send();
            $data = $response->getData();
            echo "Gateway purchase response data == " . print_r($data, true) . "\n";

            if ($response->isSuccessful()) {
                echo "Purchase transaction was successful!\n";
            }
        } catch (Exception $e) {
            echo "Exception caught while attempting authorize.\n";
            echo "Exception type == " . get_class($e) . "\n";
            echo "Message == " . $e->getMessage() . "\n";
        }
    }
</code>```

答:
Payee account invalid means the receiving account cannot process the transaction. Most likely this is a deprecated integration method, although it is hard to say without seeing the actual API request and response.

The current way to process credit cards is with the PayPal Checkout SDK, which has a black debit or credit card button that expands a form on your site. Optionally there is an Advanced integration that can be added on for presenting the card fields in a more customized way; it's more work to implement.

Body:
I am trying to implement PayPal Credit card functionality on Laravel for Rest Api. I am receiving the "PAYEE_ACCOUNT_INVALID" error. Any idea what am I doing wrong? Any help would be really appreciated.
I've tried with different test card numbers provided by PayPal via card generator mock.

Thanks.

This is my code snippet.

public function payment()
    {
        $gateway = Omnipay::create('PayPal_Rest');

        // Initialise the gateway
        $gateway->initialize(array(
            'clientId' => env('PAYPAL_SANDBOX_CLIENT_ID'),
            'secret' => env('PAYPAL_SANDBOX_CLIENT_SECRET'),
            'testMode' => true,
        ));

        #### Direct Credit Card Payment

        // Create a credit card object
        // DO NOT USE THESE CARD VALUES -- substitute your own
        // see the documentation in the class header.
        $card = new CreditCard([
            'firstName' => 'Example',
            'lastName' => 'User',
            'number' => '4111111111111111',
            'expiryMonth' => '01',
            'expiryYear' => '2027',
            'cvv' => '123',
        ]);

        // Do a purchase transaction on the gateway
        try {
            $transaction = $gateway->purchase([
                'amount' => '1.00',
                'currency' => 'AUD',
                'description' => 'This is a test purchase transaction.',
                'card' => $card,
            ]);

            $response = $transaction->send();
            $data = $response->getData();
            echo "Gateway purchase response data == " . print_r($data, true) . "\n";

            if ($response->isSuccessful()) {
                echo "Purchase transaction was successful!\n";
            }
        } catch (Exception $e) {
            echo "Exception caught while attempting authorize.\n";
            echo "Exception type == " . get_class($e) . "\n";
            echo "Message == " . $e->getMessage() . "\n";
        }
    }


问:
Returning Names from a Table dependant on a Cell Value and then Filtering
I have 3 different tables filled with names and job roles for people in 3 different companies. I need to return a table of names with a certain job title based on the value of a cell that says which company they belong to.

Can anyone help me out with a bit of excel magic?

答:
I used a VBA function in order to get the results I required.

With an IF command to set the variable of the different companies, the contacts belonged to and then added the following code within the IF function:

```<code>Dim RngWS As Worksheet
    Dim CoverSheet As Worksheet
    Dim UKCompanyMembers As Range
    Dim DropdownRange1 As Range
    Dim DropdownRange2 As Range

    Set RngWS = ThisWorkbook.Worksheets("Team Members")
    Set CoverSheet = ThisWorkbook.Worksheets("Cover Sheet")

    Set UKCompanyMembers = RngWS.Range("UK_Company_Members[Names]")
    Set DropdownRange1 = CoverSheet.Range("B5")
    Set DropdownRange2 = CoverSheet.Range("B6")

    With DropdownRange1.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & RngWS.Name & "'!" & UKCompanyMembers.Address
    End With
</code>```

I then applied the next IF function for US team members and included the same code as above but altered for the US Company Members, then again for the Asia company members.

Body:
I used a VBA function in order to get the results I required.

With an IF command to set the variable of the different companies, the contacts belonged to and then added the following code within the IF function:

Dim RngWS As Worksheet
    Dim CoverSheet As Worksheet
    Dim UKCompanyMembers As Range
    Dim DropdownRange1 As Range
    Dim DropdownRange2 As Range

    Set RngWS = ThisWorkbook.Worksheets("Team Members")
    Set CoverSheet = ThisWorkbook.Worksheets("Cover Sheet")

    Set UKCompanyMembers = RngWS.Range("UK_Company_Members[Names]")
    Set DropdownRange1 = CoverSheet.Range("B5")
    Set DropdownRange2 = CoverSheet.Range("B6")

    With DropdownRange1.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & RngWS.Name & "'!" & UKCompanyMembers.Address
    End With

I then applied the next IF function for US team members and included the same code as above but altered for the US Company Members, then again for the Asia company members.


问:
How to decode morse code in a more pythonic way
I have made a morse_code decoder in python as an assignment as shown below. It handles all characters available in morse_code. Although my approach works, it feels like a very amateurish way of doing things in python. The format in which morse code is sent:

Characters are encoded by substituting them with combinations of '.' and '-'

Characters are separated with " " (whitespace)

Words are separated with "   " (triple whitespace)

In my code below I create an empty list, which get filled with a list in which each item represents a single morse code character, that is then replaced with the actual character. Finally, the lists within the list are joined, and the resulting list is joined as well so it can be returned as a string value. The reason I work with lists is because strings are immutable in python. I can't create an empty string, go into a for loop, and append to the string. I can not create a new string within the for loop either, since the variable will be lost upon leaving the for loop scope.

I have tried to do it with the replace method first, but I ran into trouble because replace doesn't have the flexibility needed to decode morse code.

```<code>decode_morse(morse_code):
    morse_code_q = " "+morse_code+" "
    morse_code_r = morse_code_q.replace(" .- ", ' A ').replace(" -... ", ' B ').replace(' -.-. ', ' C ').replace(' -.. ', 'D ').replace(' . ', ' E ').replace(' ..-. ', ' F ').replace(' --. ', ' G ').replace(' .... ', ' H ').replace(' .. ', ' I ').replace(' .--- ', ' J ').replace(' .-. ', ' K ').replace(' .-.. ', ' L ').replace(' -- ', ' M ').replace(' -. ', ' N ').replace(' --- ', ' O ').replace(' .--. ', ' P ').replace(' --.- ', ' Q ').replace(' .-. ', ' R ').replace(' ... ', ' S ').replace(' - ', ' T ').replace(' ..- ', ' U ').replace(' ...- ', ' V ').replace(' .--', ' W ').replace(' -..- ', ' X ').replace(' -.-- ', ' Y ').replace(' --.. ', ' Z ').replace(' ----- ', '0').replace(' .---- ', '1').replace(' ..--- ', '2').replace(' ...-- ', '3').replace(' ....- ', '4').replace(' ..... ', '5').replace(' -.... ', '6').replace(' --... ', '7').replace(' ---.. ', '8').replace(' ----. ', '9').replace(' .-.-.- ', '.').replace(' --..-- ', ',').replace(' ..--.. ', '?')
    return morse_code_r.strip()
print(decode_morse('.... . -.--   .--- ..- -.. .'))
</code>```

This returns H E Y J U D E, rather than HEY JUDE. Leaving out the spaces won't do much good. After replacing a character, the next replace function won't be able to find a character, because it needs the spaces to determine the start and the end of a character (else .... for H would resolve to EEEE, since . = E)

So here is my very ugly but working approach:

```<code>def decode_morse(morse_code):
  result=[]
  words = morse_code.split("   ")
  for j in range(0,len(words)):
    reverser = words[j].split(" ")
    for i in range(0,len(reverser)):
      if reverser[i]==".-":
          reverser[i]='A'
      elif reverser[i]=="-...":
        reverser[i]='B'
      elif reverser[i]=="-.-.":
        reverser[i]='C'
      elif reverser[i]=="-..":
        reverser[i]='D'
      elif reverser[i]==".":
        reverser[i]='E'
      elif reverser[i]=="..-.":
        reverser[i]='F'
      elif reverser[i]=="--.":
        reverser[i]='G'
      elif reverser[i]=="....":
        reverser[i]='H'
      elif reverser[i]=="..":
        reverser[i]='I'
      elif reverser[i]==".---":
        reverser[i]='J'
      elif reverser[i]==".-.":
        reverser[i]='K'
      elif reverser[i]==".-..":
        reverser[i]='L'
      elif reverser[i]=="--":
        reverser[i]='M'
      elif reverser[i]=="-.":
        reverser[i]='N'
      elif reverser[i]=="---":
        reverser[i]='O'
      elif reverser[i]==".--.":
        reverser[i]='P'
      elif reverser[i]=="--.-":
        reverser[i]='Q'
      elif reverser[i]==".-.":
        reverser[i]='R'
      elif reverser[i]=="...":
        reverser[i]='S'
      elif reverser[i]=="-":
        reverser[i]='T'
      elif reverser[i]=="..-":
        reverser[i]='U'
      elif reverser[i]=="...-":
        reverser[i]='V'
      elif reverser[i]==".--":
        reverser[i]='W'
      elif reverser[i]=="-..-":
        reverser[i]='X'
      elif reverser[i]=="-.--":
        reverser[i]='Y'
      elif reverser[i]=="--..":
        reverser[i]='Z'
      elif reverser[i]=="-----":
        reverser[i]='0'
      elif reverser[i]==".----":
        reverser[i]='1'
      elif reverser[i]=="..---":
        reverser[i]='2'
      elif reverser[i]=="...--":
        reverser[i]='3'
      elif reverser[i]=="....-":
        reverser[i]='4'
      elif reverser[i]==".....":
        reverser[i]='5'
      elif reverser[i]=="-....":
        reverser[i]='6'
      elif reverser[i]=="--...":
        reverser[i]='7'
      elif reverser[i]=="---..":
        reverser[i]='8'
      elif reverser[i]=="----.":
        reverser[i]='9'
      elif reverser[i]==".-.-.-":
        reverser[i]='.'
      elif reverser[i]=="--..--":
        reverser[i]=','
      elif reverser[i]=="..--..":
        reverser[i]='?'
    result.append(reverser)
    final =[]
    for h in range(0,len(result)):
      final.append("".join(result[h])+" ")
  return "".join(final)

print(decode_morse('.... . -.--   .--- ..- -.. .'))  #returns HEY JUDE
</code>```

Anyone with a solution that makes this more pythonic? For this exercise, we are not allowed to use regexp library. Thanks in advance.

Body:
I have made a morse_code decoder in python as an assignment as shown below. It handles all characters available in morse_code. Although my approach works, it feels like a very amateurish way of doing things in python. The format in which morse code is sent:

Characters are encoded by substituting them with combinations of '.' and '-'

Characters are separated with " " (whitespace)

Words are separated with "   " (triple whitespace)

In my code below I create an empty list, which get filled with a list in which each item represents a single morse code character, that is then replaced with the actual character. Finally, the lists within the list are joined, and the resulting list is joined as well so it can be returned as a string value. The reason I work with lists is because strings are immutable in python. I can't create an empty string, go into a for loop, and append to the string. I can not create a new string within the for loop either, since the variable will be lost upon leaving the for loop scope.

I have tried to do it with the replace method first, but I ran into trouble because replace doesn't have the flexibility needed to decode morse code.

decode_morse(morse_code):
    morse_code_q = " "+morse_code+" "
    morse_code_r = morse_code_q.replace(" .- ", ' A ').replace(" -... ", ' B ').replace(' -.-. ', ' C ').replace(' -.. ', 'D ').replace(' . ', ' E ').replace(' ..-. ', ' F ').replace(' --. ', ' G ').replace(' .... ', ' H ').replace(' .. ', ' I ').replace(' .--- ', ' J ').replace(' .-. ', ' K ').replace(' .-.. ', ' L ').replace(' -- ', ' M ').replace(' -. ', ' N ').replace(' --- ', ' O ').replace(' .--. ', ' P ').replace(' --.- ', ' Q ').replace(' .-. ', ' R ').replace(' ... ', ' S ').replace(' - ', ' T ').replace(' ..- ', ' U ').replace(' ...- ', ' V ').replace(' .--', ' W ').replace(' -..- ', ' X ').replace(' -.-- ', ' Y ').replace(' --.. ', ' Z ').replace(' ----- ', '0').replace(' .---- ', '1').replace(' ..--- ', '2').replace(' ...-- ', '3').replace(' ....- ', '4').replace(' ..... ', '5').replace(' -.... ', '6').replace(' --... ', '7').replace(' ---.. ', '8').replace(' ----. ', '9').replace(' .-.-.- ', '.').replace(' --..-- ', ',').replace(' ..--.. ', '?')
    return morse_code_r.strip()
print(decode_morse('.... . -.--   .--- ..- -.. .'))

This returns H E Y J U D E, rather than HEY JUDE. Leaving out the spaces won't do much good. After replacing a character, the next replace function won't be able to find a character, because it needs the spaces to determine the start and the end of a character (else .... for H would resolve to EEEE, since . = E)

So here is my very ugly but working approach:

def decode_morse(morse_code):
  result=[]
  words = morse_code.split("   ")
  for j in range(0,len(words)):
    reverser = words[j].split(" ")
    for i in range(0,len(reverser)):
      if reverser[i]==".-":
          reverser[i]='A'
      elif reverser[i]=="-...":
        reverser[i]='B'
      elif reverser[i]=="-.-.":
        reverser[i]='C'
      elif reverser[i]=="-..":
        reverser[i]='D'
      elif reverser[i]==".":
        reverser[i]='E'
      elif reverser[i]=="..-.":
        reverser[i]='F'
      elif reverser[i]=="--.":
        reverser[i]='G'
      elif reverser[i]=="....":
        reverser[i]='H'
      elif reverser[i]=="..":
        reverser[i]='I'
      elif reverser[i]==".---":
        reverser[i]='J'
      elif reverser[i]==".-.":
        reverser[i]='K'
      elif reverser[i]==".-..":
        reverser[i]='L'
      elif reverser[i]=="--":
        reverser[i]='M'
      elif reverser[i]=="-.":
        reverser[i]='N'
      elif reverser[i]=="---":
        reverser[i]='O'
      elif reverser[i]==".--.":
        reverser[i]='P'
      elif reverser[i]=="--.-":
        reverser[i]='Q'
      elif reverser[i]==".-.":
        reverser[i]='R'
      elif reverser[i]=="...":
        reverser[i]='S'
      elif reverser[i]=="-":
        reverser[i]='T'
      elif reverser[i]=="..-":
        reverser[i]='U'
      elif reverser[i]=="...-":
        reverser[i]='V'
      elif reverser[i]==".--":
        reverser[i]='W'
      elif reverser[i]=="-..-":
        reverser[i]='X'
      elif reverser[i]=="-.--":
        reverser[i]='Y'
      elif reverser[i]=="--..":
        reverser[i]='Z'
      elif reverser[i]=="-----":
        reverser[i]='0'
      elif reverser[i]==".----":
        reverser[i]='1'
      elif reverser[i]=="..---":
        reverser[i]='2'
      elif reverser[i]=="...--":
        reverser[i]='3'
      elif reverser[i]=="....-":
        reverser[i]='4'
      elif reverser[i]==".....":
        reverser[i]='5'
      elif reverser[i]=="-....":
        reverser[i]='6'
      elif reverser[i]=="--...":
        reverser[i]='7'
      elif reverser[i]=="---..":
        reverser[i]='8'
      elif reverser[i]=="----.":
        reverser[i]='9'
      elif reverser[i]==".-.-.-":
        reverser[i]='.'
      elif reverser[i]=="--..--":
        reverser[i]=','
      elif reverser[i]=="..--..":
        reverser[i]='?'
    result.append(reverser)
    final =[]
    for h in range(0,len(result)):
      final.append("".join(result[h])+" ")
  return "".join(final)

print(decode_morse('.... . -.--   .--- ..- -.. .'))  #returns HEY JUDE

Anyone with a solution that makes this more pythonic? For this exercise, we are not allowed to use regexp library. Thanks in advance.

Body:
Always turn code into data whenever possible.

# Full table at bottom of answer.
encode_table = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    ...
    " ": "SPACE",  # Special "sentinel" value to simplify decoder.
}

# Reverse of encode_table.
decode_table = {v: k for k, v in encode_table.items()}

Now, simply:

def encode(s):
    enc = " ".join(encode_table[x] for x in s)
    return enc.replace(" SPACE ", "   ")

def decode(encoded):
    symbols = encoded.replace("   ", " SPACE ").split(" ")
    return "".join(decode_table[x] for x in symbols)

Test:

>>> encode("HEY JUDE")
'.... . -.--   .--- ..- -.. .'

>>> decode(".... . -.--   .--- ..- -.. .")
'HEY JUDE'

Full table:

encode_table = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    "D": "-..",
    "E": ".",
    "F": "..-.",
    "G": "--.",
    "H": "....",
    "I": "..",
    "J": ".---",
    "K": "-.-",
    "L": ".-..",
    "M": "--",
    "N": "-.",
    "O": "---",
    "P": ".--.",
    "Q": "--.-",
    "R": ".-.",
    "S": "...",
    "T": "-",
    "U": "..-",
    "V": "...-",
    "W": ".--",
    "X": "-..-",
    "Y": "-.--",
    "Z": "--..",
    "0": "-----",
    "1": ".----",
    "2": "..---",
    "3": "...--",
    "4": "....-",
    "5": ".....",
    "6": "-....",
    "7": "--...",
    "8": "---..",
    "9": "----.",
    ".": ".-.-.-",
    ",": "--..--",
    "?": "..--..",
    " ": "SPACE",
}


问:
Error 400: redirect_uri_mismatch How to format my URI?
I am trying to use Google Drive's API on my Web Application. I am trying to use localhost as my URIs. These are my URI and redirect URIs:

I am still, however, getting the following message, what can I do to fix it?

答:
First off unless you are using JavaScript you do not need to add anything to JavaScript origin its only used for implicit flow.

Second the Redirect uri must exactly match one that you have registered in Google developer console under redirect uris.  In your case you need to register http://127.0.0.1:500214/authorize/

Remember that your IDE must be using static ports if the port is changing then this isnt going to work the redirect uri must match exactly

This video will show you how to fix it Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

Lastly Your application is running with a start url of http://127.0.0.1 if you want it running at localhost then you need to fix that first.


问:
Always run cmd via ConEmu as administrator
I'm using ConEmu and I want to always have my cmds run as administrator.

I've changed the settings that forces all my cmds to run through ConEmu, so typing 'cmd' in the Windows Run will open ConEmu (Settings -> Integration -> Default term -> Force ConEmu as default terminal)

I've tried changing the (Settings -> Startup -> Command line) to cmd.exe -new_console:a which works for shortcuts but doesn't change the default (running cmd from Run or opening a new tab inside ConEmu)

Thanks

答:
on win11, it worked for me to go into the settings in conEmu, startup>Tasks, select your previously created predefined task, i called mine Ubuntu::Bash, and the in the commands parameter box: %windir%\system32\bash.exe ~ -cur_console:p  <<----this is what i had,
i added another line with an asterisk.  "*"

new commands parameter arguments:
%windir%\system32\bash.exe ~ -cur_console:p
CONEMU settings screengrab

*

worked great.


问:
Javascript: Calling Object Properties Multiple Times
I have an object:

```<code>var object = {
    string1 : 'hello',
    string2 : 'world'
}
</code>```

And If I want to call the string2 property of the object is it slower to call it multiple times like:

```<code>...object.string2...
...object.string2...
</code>```

or it would be faster to create a reference for it what holds the value of the parameter like:

```<code>var string2 = object.string2;
...string2...
...string2...
</code>```

The reason why I think that the second one could be faster, because I think right now that the first one always scans the whole object to grab the value.

答:
You are correct - the second one is faster, because JavaScript does not need to perform the lookup of string2 each time.  The change is even more profound in something like this:

```<code>(do stuff with foo.bar.baz.qux)
</code>```

versus

```<code>var property = foo.bar.baz.qux;
(do stuff with property)
</code>```

In that example, foo must be scanned for bar.  Then bar must be scanned for baz.  Et cetera.

In your example the gain will be minimal unless you are doing a lot of work with string2, but you are correct in saying that it is faster.

Body:
I have an object:

var object = {
    string1 : 'hello',
    string2 : 'world'
}

And If I want to call the string2 property of the object is it slower to call it multiple times like:

...object.string2...
...object.string2...

or it would be faster to create a reference for it what holds the value of the parameter like:

var string2 = object.string2;
...string2...
...string2...

The reason why I think that the second one could be faster, because I think right now that the first one always scans the whole object to grab the value.

Body:
You are correct - the second one is faster, because JavaScript does not need to perform the lookup of string2 each time.  The change is even more profound in something like this:

(do stuff with foo.bar.baz.qux)

versus

var property = foo.bar.baz.qux;
(do stuff with property)

In that example, foo must be scanned for bar.  Then bar must be scanned for baz.  Et cetera.

In your example the gain will be minimal unless you are doing a lot of work with string2, but you are correct in saying that it is faster.


问:
How can I install packages using pip according to the requirements.txt file from a local directory?
Here is the problem:

I have a requirements.txt file that looks like:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
<p>I have a local archive directory containing all the packages + others.</p>
<p>I have created a new virtualenv with</p>
<pre class="lang-none prettyprint-override"><code>bin/virtualenv testing
</code>```

Upon activating it, I tried to install the packages according to requirements.txt from the local archive directory.

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/
```
<p>I got some output that seems to indicate that the installation is fine:</p>
<pre class="lang-none prettyprint-override"><code>Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....
</code>```

But a later check revealed that none of the packages are installed properly. I cannot import the packages, and none are found in the site-packages directory of my virtualenv. So what went wrong?

答:
In Windows, this can lead to less format-related path issues, if you have

c:\folder\subfolder\requirements.txt

```<code>cd c:\folder\subfolder
pip install -r requirements.txt
</code>```

Body:
Here is the problem:

I have a requirements.txt file that looks like:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...

I have a local archive directory containing all the packages + others.

I have created a new virtualenv with

bin/virtualenv testing

Upon activating it, I tried to install the packages according to requirements.txt from the local archive directory.

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/

I got some output that seems to indicate that the installation is fine:

Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....

But a later check revealed that none of the packages are installed properly. I cannot import the packages, and none are found in the site-packages directory of my virtualenv. So what went wrong?

Body:
In Windows, this can lead to less format-related path issues, if you have

c:\folder\subfolder\requirements.txt

cd c:\folder\subfolder
pip install -r requirements.txt


问:
Mac Terminal Auto Complete
Usually on a Unix/Linux terminal when you press Tab it will auto-complete until there are several options, and then it will list the options below for you to select. For example:

```<code>cd he
helpFolder/ helpMe/ heIsThere/
cd help
</code>```

With the Mac terminal, it forces you to press it twice to see options. I wondering if it's possible to change that setting to one Tab press?

答:
Looks like the other comments are for bash whereas MacOs moved already to zsh as default shell. To enable autocompletion (including subcommands), putting the following line in zsh config file (~/.zshrc) works for me:

```<code>autoload -Uz compinit && compinit

</code>```

Title: Mac Terminal Auto Complete

Body:
Usually on a Unix/Linux terminal when you press Tab it will auto-complete until there are several options, and then it will list the options below for you to select. For example:

cd he
helpFolder/ helpMe/ heIsThere/
cd help

With the Mac terminal, it forces you to press it twice to see options. I wondering if it's possible to change that setting to one Tab press?

Body:
Looks like the other comments are for bash whereas MacOs moved already to zsh as default shell. To enable autocompletion (including subcommands), putting the following line in zsh config file (~/.zshrc) works for me:

autoload -Uz compinit && compinit


问:
NullInjectorError: No provider for e! in Angular 8
main-es2015.6f31d328c9edc909ac03.js:1 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(i)[Se -> e]:
StaticInjectorError(Platform: core)[Se -> e]:
NullInjectorError: No provider for e!

I get the above error only when I do --prod build.
FYI, the module is lazy loaded.

Any suggestions/help will be really appreciated.

答:
I had a similar problem with the same obscure error message. In my case it was caused by a class which I tought was an Angular service (I didn't write it) . I imported the class and injected it via my component's constructor. Then I got this error message and couldn't figure out why.
It turned out that the class I was using was not an Angular service, but a conventional TypeScript class. So I had to instantiate it conventionally (i.e., without Angular's dependency injection):</p>
```<code>export class MyComponent {

    // This is what caused my problem. "UtilClass" is no Angular service
    // It can therefore not be injected
    constructor(private util: UtilClass) {}

    // This is the way to use it
    const util = new UtilClass();
    util.doStuff();
}
</code>```

Body:
I had a similar problem with the same obscure error message. In my case it was caused by a class which I tought was an Angular service (I didn't write it) . I imported the class and injected it via my component's constructor. Then I got this error message and couldn't figure out why.
It turned out that the class I was using was not an Angular service, but a conventional TypeScript class. So I had to instantiate it conventionally (i.e., without Angular's dependency injection):

export class MyComponent {

    // This is what caused my problem. "UtilClass" is no Angular service
    // It can therefore not be injected
    constructor(private util: UtilClass) {}

    // This is the way to use it
    const util = new UtilClass();
    util.doStuff();
}


问:
Why will my physics 2D raycast not display or work correctly?
Basically i wanted to make a raycast for jumping but for some reason the distance of the raycast is wrong and never changes and the position of it is so wrong i cant even seem to find it:

```<code>    ray2D = Physics2D.Raycast(transform.position, -Vector2.up, .1f, GroundedLayers);
    Debug.Log(ray2D.distance);
    isGrounded = groundCheck();
</code>```

Grounded layers do not include the player, distance always returns as 0, grounded is always false and the gizmos line only draws when i open the prefab and not at all in the scene:

here the distance is set to .1f but displays the same as 1f

(EDIT: ok so i checked and for some reason the raycast happens around 0, -1 even tho thats nowhere near the player transform?)

答: I found that the raycast was detecting an invisible trigger so i had to put it on another layer :)</p>

Body:
Basically i wanted to make a raycast for jumping but for some reason the distance of the raycast is wrong and never changes and the position of it is so wrong i cant even seem to find it:

    ray2D = Physics2D.Raycast(transform.position, -Vector2.up, .1f, GroundedLayers);
    Debug.Log(ray2D.distance);
    isGrounded = groundCheck();

Grounded layers do not include the player, distance always returns as 0, grounded is always false and the gizmos line only draws when i open the prefab and not at all in the scene:

here the distance is set to .1f but displays the same as 1f

(EDIT: ok so i checked and for some reason the raycast happens around 0, -1 even tho thats nowhere near the player transform?)


问:
What happens when default.aspx page is requested for the first time?
What happens when default.aspx page is requested for the first time?

.net is pure a pure Object Oriented Framework.

_default is a class which extends Page.

Without instantiating, Pre-Init,Init,Load cannot be called.
So How _default class is instantiated?
Who is responsible for that?

I want to know very detailed technical steps?

Pleasa clarify!

答:
The ASP.NET Page Object Model

When the request is for an .aspx resource, the handler is a page
  handler—namely, an instance of a class that inherits from Page. The
  association between types of resources and types of handlers is stored
  in the configuration file of the application

The type of the HTTP handler for a particular page depends on the URL.
  The first time the URL is invoked, a new class is composed and
  dynamically compiled to an assembly. The source code of the class is
  the outcome of a parsing process that examines the .aspx sources. The
  class is defined as part of the namespace ASP and is given a name that
  mimics the original URL. For example, if the URL endpoint is
  page.aspx, the name of the class is ASP.Page_aspx. The class name,
  though, can be programmatically controlled by setting the ClassName
  attribute in the @Page directive.

The base class for the HTTP handler is Page. This class defines the
  minimum set of methods and properties shared by all page handlers. The
  Page class implements the IHttpHandler interface.

Under a couple of circumstances, the base class for the actual handler
  is not Page but a different class. This happens, for example, if
  code-behind is used. Code-behind is a development technique that
  insulates the code necessary to a page into a separate C# or Microsoft
  Visual Basic® .NET class. The code of a page is the set of event
  handlers and helper methods that actually create the behavior of the
  page. This code can be defined inline using the
  tag or placed in an external class—the code-behind class. A
  code-behind class is a class that inherits from Page and specializes
  it with extra methods. When specified, the code-behind class is used
  as the base class for the HTTP handler.


问:
SV Assertion - Implication matches unique valid sequences
I have assertion property as
assert property P;

```<code>property P;
@(posedge clk) A |-> ##[1:5] B;
endproperty
</code>```
```<code>clk - 0 1 2 3 4 5 6 7 8 9 10
A   - 0 1 0 1 0 0 0 0 0 0 0
B   - 0 0 0 0 1 0 0 1 0 0 0
</code>```

Here B = 1 at Clock num 4 satisfies assertion For A at Clocks 1 and 3.

How to write an assertion that checks for each A==1 we see a unique B==1 , meaning
A=1 at Clk 1 should match against B=1 at Clk 4
AND
A=1 at Clk 3 should match against B=1 at Clk 7.

Thanks,

答: I don't think there is a way you can do it with modelling layer code. When the SVA is triggered on A==1 it cannot know if there has been a previous A that hasn't been "acked" with a B</p>

Body:
I have assertion property as
assert property P;

property P;
@(posedge clk) A |-> ##[1:5] B;
endproperty

clk - 0 1 2 3 4 5 6 7 8 9 10
A   - 0 1 0 1 0 0 0 0 0 0 0
B   - 0 0 0 0 1 0 0 1 0 0 0

Here B = 1 at Clock num 4 satisfies assertion For A at Clocks 1 and 3.

How to write an assertion that checks for each A==1 we see a unique B==1 , meaning
A=1 at Clk 1 should match against B=1 at Clk 4
AND
A=1 at Clk 3 should match against B=1 at Clk 7.

Thanks,


问:
Blazor set background color with parameter
I have a card blazor component with css styling, i've tried to pass background color as a parameter to the styling in the following way:

```<code>@inject NavigationManager UriHelper

<SfCard @onclick=@Navigate CssClass="@NavigateUri">
    <CardHeader Title="@Title">
        <span class="fa fa-@CardIcon test-icon" aria-hidden="true"></span>
    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

<style>
    .e-card .e-card-header {
        background: @CardColor;
        height: 60px;
        align-self: flex-start;
    }

</style>

@code {
    [Parameter]
    public string Title { get; set; } = string.Empty;

    [Parameter]
    public string Content { get; set; } = string.Empty;

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    void Navigate()
    {
        UriHelper.NavigateTo(NavigateUri);
    }
}
</code>```

It works with 1 card, but when trying to create multiple instances of cards, like this for example:

```<code>    <Card Title="test1" NavigateUri="test1" CardIcon="random"
        Content="test1 content" CardColor="red">
    </Card>

    <Card Title="test2" NavigateUri="test2" CardIcon="random"
        Content="test2 content" CardColor="blue">
    </Card>
</code>```

They are all colored with the first color provided (red) and not each with its own color

答:
If you want to set the background color for the whole SfCard, not just the CardHeader, you could take advantage of the SfCard's property HtmlAttributes (docs) and set the parameter-dependent style value directly on the SfCard component in your Card implementation.

```<code><SfCard style="background-color: @CardColor">
    <!--Content-->
</SfCard>

</code>```

Body:
I have a card blazor component with css styling, i've tried to pass background color as a parameter to the styling in the following way:

@inject NavigationManager UriHelper

<SfCard @onclick=@Navigate CssClass="@NavigateUri">
    <CardHeader Title="@Title">

    </CardHeader>
    <CardContent Content="@Content" />
</SfCard>

@code {
    [Parameter]
    public string Title { get; set; } = string.Empty;

    [Parameter]
    public string Content { get; set; } = string.Empty;

    [Parameter]
    public string NavigateUri { get; set; } = string.Empty;

    [Parameter]
    public string CardColor { get; set; } = string.Empty;

    [Parameter]
    public string CardIcon { get; set; } = string.Empty;

    void Navigate()
    {
        UriHelper.NavigateTo(NavigateUri);
    }
}

It works with 1 card, but when trying to create multiple instances of cards, like this for example:

    <Card Title="test1" NavigateUri="test1" CardIcon="random"
        Content="test1 content" CardColor="red">
    </Card>

    <Card Title="test2" NavigateUri="test2" CardIcon="random"
        Content="test2 content" CardColor="blue">
    </Card>

They are all colored with the first color provided (red) and not each with its own color

Body:
If you want to set the background color for the whole SfCard, not just the CardHeader, you could take advantage of the SfCard's property HtmlAttributes (docs) and set the parameter-dependent style value directly on the SfCard component in your Card implementation.

<SfCard style="background-color: @CardColor">
    <!--Content-->
</SfCard>


问:
In an object nesting key-value pairs, how to convert a single-value array into just the value itself?
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]
```
<p>Since all the arrays are single-values, I would like to convert this entire <code>albums</code> object to:</p>
<pre class="lang-js prettyprint-override"><code>// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]
</code>```

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

答:
Edit: This changes the value in place rather than creating a new dictionary with the final result.</p>
```<code>for (var i = 0; i < albums.length; i++) {
   for (var key in albums[i]) {
      albums[i][key] = albums[i][key][0];
   }
}
</code>```

Body:
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]

Since all the arrays are single-values, I would like to convert this entire albums object to:

// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

Body:
Edit: This changes the value in place rather than creating a new dictionary with the final result.

for (var i = 0; i < albums.length; i++) {
   for (var key in albums[i]) {
      albums[i][key] = albums[i][key][0];
   }
}


问:
Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock
Trying to run this simple query, but getting this error
https://prnt.sc/1rb6pl5</p>

答: Make sure mysql is running on your server.</p>


问:
Transform the double differenced forecast to original time-series
I am working on the ARIMA model for time-series forecasting. As my time-series is indicating non-stationary, I have transformed the data to stationary by double differencing (differenced two times).
Now I have successfully fit the model and to get a good forecast I need to transform my datasets back to the original signal.

I am not getting how to do that. Please help me with possible solutions.

Thank you

答:
You can use this method below to inverse differencing and just call it twice. You must recall the first value of the series before differencing:</p>
```<code>def inverse_diff(series, last_observation):

    series_undifferenced = series.copy()

    series_undifferenced.iat[0] = series_undifferenced.iat[0] + last_observation

    series_undifferenced = series_undifferenced.cumsum()

    return series_undifferenced

inverse_1 = inverse_diff(your_differenced_series, first_value_of_differenced_series)
inverse = inverse_diff(inverse_1, first_value_of_original_seires)
</code>```

Body:
You can use this method below to inverse differencing and just call it twice. You must recall the first value of the series before differencing:

def inverse_diff(series, last_observation):

    series_undifferenced = series.copy()

    series_undifferenced.iat[0] = series_undifferenced.iat[0] + last_observation

    series_undifferenced = series_undifferenced.cumsum()

    return series_undifferenced

inverse_1 = inverse_diff(your_differenced_series, first_value_of_differenced_series)
inverse = inverse_diff(inverse_1, first_value_of_original_seires)